| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741 |
- (function webpackUniversalModuleDefinition(root, factory) {
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = factory(require("Rx"), require("rxjs/observable/fromPromise"), require("rxjs/operator/toPromise"));
- else if(typeof define === 'function' && define.amd)
- define(["Rx", "rxjs/observable/fromPromise", "rxjs/operator/toPromise"], factory);
- else if(typeof exports === 'object')
- exports["ng"] = factory(require("Rx"), require("rxjs/observable/fromPromise"), require("rxjs/operator/toPromise"));
- else
- root["ng"] = factory(root["Rx"], root["Rx"]["Observable"], root["Rx"]["Observable"]["prototype"]);
- })(this, function(__WEBPACK_EXTERNAL_MODULE_62__, __WEBPACK_EXTERNAL_MODULE_63__, __WEBPACK_EXTERNAL_MODULE_64__) {
- return /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId])
- /******/ return installedModules[moduleId].exports;
- /******/ // Create a new module (and put it into the cache)
- /******/ var module = installedModules[moduleId] = {
- /******/ exports: {},
- /******/ id: moduleId,
- /******/ loaded: false
- /******/ };
- /******/ // Execute the module function
- /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
- /******/ // Flag the module as loaded
- /******/ module.loaded = true;
- /******/ // Return the exports of the module
- /******/ return module.exports;
- /******/ }
- /******/ // expose the modules object (__webpack_modules__)
- /******/ __webpack_require__.m = modules;
- /******/ // expose the module cache
- /******/ __webpack_require__.c = installedModules;
- /******/ // __webpack_public_path__
- /******/ __webpack_require__.p = "";
- /******/ // Load entry module and return exports
- /******/ return __webpack_require__(0);
- /******/ })
- /************************************************************************/
- /******/ ([
- /* 0 */
- /***/ function(module, exports, __webpack_require__) {
- module.exports = __webpack_require__(1);
- /***/ },
- /* 1 */
- /***/ function(module, exports, __webpack_require__) {
- exports.core = __webpack_require__(2);
- exports.common = __webpack_require__(104);
- exports.compiler = __webpack_require__(147);
- exports.platform = {
- browser: __webpack_require__(179),
- common_dom: __webpack_require__(203)
- };
- exports.http = __webpack_require__(209);
- exports.router = __webpack_require__(224);
- exports.router_link_dsl = __webpack_require__(248);
- exports.instrumentation = __webpack_require__(250);
- exports.upgrade = __webpack_require__(251);
- /***/ },
- /* 2 */
- /***/ function(module, exports, __webpack_require__) {
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- /**
- * @module
- * @description
- * Starting point to import all public core APIs.
- */
- __export(__webpack_require__(3));
- __export(__webpack_require__(57));
- __export(__webpack_require__(58));
- __export(__webpack_require__(6));
- __export(__webpack_require__(59));
- var lang_1 = __webpack_require__(5);
- exports.enableProdMode = lang_1.enableProdMode;
- var application_ref_1 = __webpack_require__(65);
- exports.platform = application_ref_1.platform;
- exports.createNgZone = application_ref_1.createNgZone;
- exports.PlatformRef = application_ref_1.PlatformRef;
- exports.ApplicationRef = application_ref_1.ApplicationRef;
- var application_tokens_1 = __webpack_require__(67);
- exports.APP_ID = application_tokens_1.APP_ID;
- exports.APP_COMPONENT = application_tokens_1.APP_COMPONENT;
- exports.APP_INITIALIZER = application_tokens_1.APP_INITIALIZER;
- exports.PACKAGE_ROOT_URL = application_tokens_1.PACKAGE_ROOT_URL;
- exports.PLATFORM_INITIALIZER = application_tokens_1.PLATFORM_INITIALIZER;
- __export(__webpack_require__(98));
- __export(__webpack_require__(99));
- __export(__webpack_require__(100));
- var debug_element_1 = __webpack_require__(101);
- exports.DebugElement = debug_element_1.DebugElement;
- exports.Scope = debug_element_1.Scope;
- exports.inspectElement = debug_element_1.inspectElement;
- exports.asNativeElements = debug_element_1.asNativeElements;
- __export(__webpack_require__(68));
- __export(__webpack_require__(24));
- __export(__webpack_require__(95));
- __export(__webpack_require__(102));
- __export(__webpack_require__(103));
- __export(__webpack_require__(16));
- /***/ },
- /* 3 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * This indirection is needed to free up Component, etc symbols in the public API
- * to be used by the decorator versions of these annotations.
- */
- var di_1 = __webpack_require__(4);
- exports.QueryMetadata = di_1.QueryMetadata;
- exports.ContentChildrenMetadata = di_1.ContentChildrenMetadata;
- exports.ContentChildMetadata = di_1.ContentChildMetadata;
- exports.ViewChildrenMetadata = di_1.ViewChildrenMetadata;
- exports.ViewQueryMetadata = di_1.ViewQueryMetadata;
- exports.ViewChildMetadata = di_1.ViewChildMetadata;
- exports.AttributeMetadata = di_1.AttributeMetadata;
- var directives_1 = __webpack_require__(23);
- exports.ComponentMetadata = directives_1.ComponentMetadata;
- exports.DirectiveMetadata = directives_1.DirectiveMetadata;
- exports.PipeMetadata = directives_1.PipeMetadata;
- exports.InputMetadata = directives_1.InputMetadata;
- exports.OutputMetadata = directives_1.OutputMetadata;
- exports.HostBindingMetadata = directives_1.HostBindingMetadata;
- exports.HostListenerMetadata = directives_1.HostListenerMetadata;
- var view_1 = __webpack_require__(56);
- exports.ViewMetadata = view_1.ViewMetadata;
- exports.ViewEncapsulation = view_1.ViewEncapsulation;
- var di_2 = __webpack_require__(4);
- var directives_2 = __webpack_require__(23);
- var view_2 = __webpack_require__(56);
- var decorators_1 = __webpack_require__(9);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ComponentMetadata.
- /**
- * Declare reusable UI building blocks for an application.
- *
- * Each Angular component requires a single `@Component` and at least one `@View` annotation. The
- * `@Component`
- * annotation specifies when a component is instantiated, and which properties and hostListeners it
- * binds to.
- *
- * When a component is instantiated, Angular
- * - creates a shadow DOM for the component.
- * - loads the selected template into the shadow DOM.
- * - creates all the injectable objects configured with `providers` and `viewProviders`.
- *
- * All template expressions and statements are then evaluated against the component instance.
- *
- * For details on the `@View` annotation, see {@link ViewMetadata}.
- *
- * ## Lifecycle hooks
- *
- * When the component class implements some {@link angular2/lifecycle_hooks} the callbacks are
- * called by the change detection at defined points in time during the life of the component.
- *
- * ### Example
- *
- * {@example core/ts/metadata/metadata.ts region='component'}
- */
- exports.Component = decorators_1.makeDecorator(directives_2.ComponentMetadata, function (fn) { return fn.View = exports.View; });
- // TODO(alexeagle): remove the duplication of this doc. It is copied from DirectiveMetadata.
- /**
- * Directives allow you to attach behavior to elements in the DOM.
- *
- * {@link DirectiveMetadata}s with an embedded view are called {@link ComponentMetadata}s.
- *
- * A directive consists of a single directive annotation and a controller class. When the
- * directive's `selector` matches
- * elements in the DOM, the following steps occur:
- *
- * 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor
- * arguments.
- * 2. Angular instantiates directives for each matched element using `ElementInjector` in a
- * depth-first order,
- * as declared in the HTML.
- *
- * ## Understanding How Injection Works
- *
- * There are three stages of injection resolution.
- * - *Pre-existing Injectors*:
- * - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if
- * the dependency was
- * specified as `@Optional`, returns `null`.
- * - The platform injector resolves browser singleton resources, such as: cookies, title,
- * location, and others.
- * - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow
- * the same parent-child hierarchy
- * as the component instances in the DOM.
- * - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each
- * element has an `ElementInjector`
- * which follow the same parent-child hierarchy as the DOM elements themselves.
- *
- * When a template is instantiated, it also must instantiate the corresponding directives in a
- * depth-first order. The
- * current `ElementInjector` resolves the constructor dependencies for each directive.
- *
- * Angular then resolves dependencies as follows, according to the order in which they appear in the
- * {@link ViewMetadata}:
- *
- * 1. Dependencies on the current element
- * 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary
- * 3. Dependencies on component injectors and their parents until it encounters the root component
- * 4. Dependencies on pre-existing injectors
- *
- *
- * The `ElementInjector` can inject other directives, element-specific special objects, or it can
- * delegate to the parent
- * injector.
- *
- * To inject other directives, declare the constructor parameter as:
- * - `directive:DirectiveType`: a directive on the current element only
- * - `@Host() directive:DirectiveType`: any directive that matches the type between the current
- * element and the
- * Shadow DOM root.
- * - `@Query(DirectiveType) query:QueryList<DirectiveType>`: A live collection of direct child
- * directives.
- * - `@QueryDescendants(DirectiveType) query:QueryList<DirectiveType>`: A live collection of any
- * child directives.
- *
- * To inject element-specific special objects, declare the constructor parameter as:
- * - `element: ElementRef` to obtain a reference to logical element in the view.
- * - `viewContainer: ViewContainerRef` to control child template instantiation, for
- * {@link DirectiveMetadata} directives only
- * - `bindingPropagation: BindingPropagation` to control change detection in a more granular way.
- *
- * ### Example
- *
- * The following example demonstrates how dependency injection resolves constructor arguments in
- * practice.
- *
- *
- * Assume this HTML template:
- *
- * ```
- * <div dependency="1">
- * <div dependency="2">
- * <div dependency="3" my-directive>
- * <div dependency="4">
- * <div dependency="5"></div>
- * </div>
- * <div dependency="6"></div>
- * </div>
- * </div>
- * </div>
- * ```
- *
- * With the following `dependency` decorator and `SomeService` injectable class.
- *
- * ```
- * @Injectable()
- * class SomeService {
- * }
- *
- * @Directive({
- * selector: '[dependency]',
- * inputs: [
- * 'id: dependency'
- * ]
- * })
- * class Dependency {
- * id:string;
- * }
- * ```
- *
- * Let's step through the different ways in which `MyDirective` could be declared...
- *
- *
- * ### No injection
- *
- * Here the constructor is declared with no arguments, therefore nothing is injected into
- * `MyDirective`.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor() {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with no dependencies.
- *
- *
- * ### Component-level injection
- *
- * Directives can inject any injectable instance from the closest component injector or any of its
- * parents.
- *
- * Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type
- * from the parent
- * component's injector.
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(someService: SomeService) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a dependency on `SomeService`.
- *
- *
- * ### Injecting a directive from the current element
- *
- * Directives can inject other directives declared on the current element.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(dependency: Dependency) {
- * expect(dependency.id).toEqual(3);
- * }
- * }
- * ```
- * This directive would be instantiated with `Dependency` declared at the same element, in this case
- * `dependency="3"`.
- *
- * ### Injecting a directive from any ancestor elements
- *
- * Directives can inject other directives declared on any ancestor element (in the current Shadow
- * DOM), i.e. on the current element, the
- * parent element, or its parents.
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Host() dependency: Dependency) {
- * expect(dependency.id).toEqual(2);
- * }
- * }
- * ```
- *
- * `@Host` checks the current element, the parent, as well as its parents recursively. If
- * `dependency="2"` didn't
- * exist on the direct parent, this injection would
- * have returned
- * `dependency="1"`.
- *
- *
- * ### Injecting a live collection of direct child directives
- *
- *
- * A directive can also query for other child directives. Since parent directives are instantiated
- * before child directives, a directive can't simply inject the list of child directives. Instead,
- * the directive injects a {@link QueryList}, which updates its contents as children are added,
- * removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ngFor`, an
- * `ngIf`, or an `ngSwitch`.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Query(Dependency) dependencies:QueryList<Dependency>) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and
- * 6. Here, `Dependency` 5 would not be included, because it is not a direct child.
- *
- * ### Injecting a live collection of descendant directives
- *
- * By passing the descendant flag to `@Query` above, we can include the children of the child
- * elements.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList<Dependency>) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6.
- *
- * ### Optional injection
- *
- * The normal behavior of directives is to return an error when a specified dependency cannot be
- * resolved. If you
- * would like to inject `null` on unresolved dependency instead, you can annotate that dependency
- * with `@Optional()`.
- * This explicitly permits the author of a template to treat some of the surrounding directives as
- * optional.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Optional() dependency:Dependency) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a `Dependency` directive found on the current element.
- * If none can be
- * found, the injector supplies `null` instead of throwing an error.
- *
- * ### Example
- *
- * Here we use a decorator directive to simply define basic tool-tip behavior.
- *
- * ```
- * @Directive({
- * selector: '[tooltip]',
- * inputs: [
- * 'text: tooltip'
- * ],
- * host: {
- * '(mouseenter)': 'onMouseEnter()',
- * '(mouseleave)': 'onMouseLeave()'
- * }
- * })
- * class Tooltip{
- * text:string;
- * overlay:Overlay; // NOT YET IMPLEMENTED
- * overlayManager:OverlayManager; // NOT YET IMPLEMENTED
- *
- * constructor(overlayManager:OverlayManager) {
- * this.overlay = overlay;
- * }
- *
- * onMouseEnter() {
- * // exact signature to be determined
- * this.overlay = this.overlayManager.open(text, ...);
- * }
- *
- * onMouseLeave() {
- * this.overlay.close();
- * this.overlay = null;
- * }
- * }
- * ```
- * In our HTML template, we can then add this behavior to a `<div>` or any other element with the
- * `tooltip` selector,
- * like so:
- *
- * ```
- * <div tooltip="some text here"></div>
- * ```
- *
- * Directives can also control the instantiation, destruction, and positioning of inline template
- * elements:
- *
- * A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at
- * runtime.
- * The {@link ViewContainerRef} is created as a result of `<template>` element, and represents a
- * location in the current view
- * where these actions are performed.
- *
- * Views are always created as children of the current {@link ViewMetadata}, and as siblings of the
- * `<template>` element. Thus a
- * directive in a child view cannot inject the directive that created it.
- *
- * Since directives that create views via ViewContainers are common in Angular, and using the full
- * `<template>` element syntax is wordy, Angular
- * also supports a shorthand notation: `<li *foo="bar">` and `<li template="foo: bar">` are
- * equivalent.
- *
- * Thus,
- *
- * ```
- * <ul>
- * <li *foo="bar" title="text"></li>
- * </ul>
- * ```
- *
- * Expands in use to:
- *
- * ```
- * <ul>
- * <template [foo]="bar">
- * <li title="text"></li>
- * </template>
- * </ul>
- * ```
- *
- * Notice that although the shorthand places `*foo="bar"` within the `<li>` element, the binding for
- * the directive
- * controller is correctly instantiated on the `<template>` element rather than the `<li>` element.
- *
- * ## Lifecycle hooks
- *
- * When the directive class implements some {@link angular2/lifecycle_hooks} the callbacks are
- * called by the change detection at defined points in time during the life of the directive.
- *
- * ### Example
- *
- * Let's suppose we want to implement the `unless` behavior, to conditionally include a template.
- *
- * Here is a simple directive that triggers on an `unless` selector:
- *
- * ```
- * @Directive({
- * selector: '[unless]',
- * inputs: ['unless']
- * })
- * export class Unless {
- * viewContainer: ViewContainerRef;
- * templateRef: TemplateRef;
- * prevCondition: boolean;
- *
- * constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef) {
- * this.viewContainer = viewContainer;
- * this.templateRef = templateRef;
- * this.prevCondition = null;
- * }
- *
- * set unless(newCondition) {
- * if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) {
- * this.prevCondition = true;
- * this.viewContainer.clear();
- * } else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) {
- * this.prevCondition = false;
- * this.viewContainer.create(this.templateRef);
- * }
- * }
- * }
- * ```
- *
- * We can then use this `unless` selector in a template:
- * ```
- * <ul>
- * <li *unless="expr"></li>
- * </ul>
- * ```
- *
- * Once the directive instantiates the child view, the shorthand notation for the template expands
- * and the result is:
- *
- * ```
- * <ul>
- * <template [unless]="exp">
- * <li></li>
- * </template>
- * <li></li>
- * </ul>
- * ```
- *
- * Note also that although the `<li></li>` template still exists inside the `<template></template>`,
- * the instantiated
- * view occurs on the second `<li></li>` which is a sibling to the `<template>` element.
- */
- exports.Directive = decorators_1.makeDecorator(directives_2.DirectiveMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ViewMetadata.
- /**
- * Metadata properties available for configuring Views.
- *
- * Each Angular component requires a single `@Component` and at least one `@View` annotation. The
- * `@View` annotation specifies the HTML template to use, and lists the directives that are active
- * within the template.
- *
- * When a component is instantiated, the template is loaded into the component's shadow root, and
- * the expressions and statements in the template are evaluated against the component.
- *
- * For details on the `@Component` annotation, see {@link ComponentMetadata}.
- *
- * ### Example
- *
- * ```
- * @Component({
- * selector: 'greet',
- * template: 'Hello {{name}}!',
- * directives: [GreetUser, Bold]
- * })
- * class Greet {
- * name: string;
- *
- * constructor() {
- * this.name = 'World';
- * }
- * }
- * ```
- */
- exports.View = decorators_1.makeDecorator(view_2.ViewMetadata, function (fn) { return fn.View = exports.View; });
- /**
- * Specifies that a constant attribute value should be injected.
- *
- * The directive can inject constant string literals of host element attributes.
- *
- * ### Example
- *
- * Suppose we have an `<input>` element and want to know its `type`.
- *
- * ```html
- * <input type="text">
- * ```
- *
- * A decorator can inject string literal `text` like so:
- *
- * {@example core/ts/metadata/metadata.ts region='attributeMetadata'}
- */
- exports.Attribute = decorators_1.makeParamDecorator(di_2.AttributeMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from QueryMetadata.
- /**
- * Declares an injectable parameter to be a live list of directives or variable
- * bindings from the content children of a directive.
- *
- * ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview))
- *
- * Assume that `<tabs>` component would like to get a list its children `<pane>`
- * components as shown in this example:
- *
- * ```html
- * <tabs>
- * <pane title="Overview">...</pane>
- * <pane *ngFor="#o of objects" [title]="o.title">{{o.text}}</pane>
- * </tabs>
- * ```
- *
- * The preferred solution is to query for `Pane` directives using this decorator.
- *
- * ```javascript
- * @Component({
- * selector: 'pane',
- * inputs: ['title']
- * })
- * class Pane {
- * title:string;
- * }
- *
- * @Component({
- * selector: 'tabs',
- * template: `
- * <ul>
- * <li *ngFor="#pane of panes">{{pane.title}}</li>
- * </ul>
- * <content></content>
- * `
- * })
- * class Tabs {
- * panes: QueryList<Pane>;
- * constructor(@Query(Pane) panes:QueryList<Pane>) {
- * this.panes = panes;
- * }
- * }
- * ```
- *
- * A query can look for variable bindings by passing in a string with desired binding symbol.
- *
- * ### Example ([live demo](http://plnkr.co/edit/sT2j25cH1dURAyBRCKx1?p=preview))
- * ```html
- * <seeker>
- * <div #findme>...</div>
- * </seeker>
- *
- * @Component({ selector: 'foo' })
- * class seeker {
- * constructor(@Query('findme') elList: QueryList<ElementRef>) {...}
- * }
- * ```
- *
- * In this case the object that is injected depend on the type of the variable
- * binding. It can be an ElementRef, a directive or a component.
- *
- * Passing in a comma separated list of variable bindings will query for all of them.
- *
- * ```html
- * <seeker>
- * <div #findMe>...</div>
- * <div #findMeToo>...</div>
- * </seeker>
- *
- * @Component({
- * selector: 'foo'
- * })
- * class Seeker {
- * constructor(@Query('findMe, findMeToo') elList: QueryList<ElementRef>) {...}
- * }
- * ```
- *
- * Configure whether query looks for direct children or all descendants
- * of the querying element, by using the `descendants` parameter.
- * It is set to `false` by default.
- *
- * ### Example ([live demo](http://plnkr.co/edit/wtGeB977bv7qvA5FTYl9?p=preview))
- * ```html
- * <container #first>
- * <item>a</item>
- * <item>b</item>
- * <container #second>
- * <item>c</item>
- * </container>
- * </container>
- * ```
- *
- * When querying for items, the first container will see only `a` and `b` by default,
- * but with `Query(TextDirective, {descendants: true})` it will see `c` too.
- *
- * The queried directives are kept in a depth-first pre-order with respect to their
- * positions in the DOM.
- *
- * Query does not look deep into any subcomponent views.
- *
- * Query is updated as part of the change-detection cycle. Since change detection
- * happens after construction of a directive, QueryList will always be empty when observed in the
- * constructor.
- *
- * The injected object is an unmodifiable live list.
- * See {@link QueryList} for more details.
- */
- exports.Query = decorators_1.makeParamDecorator(di_2.QueryMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ContentChildrenMetadata.
- /**
- * Configures a content query.
- *
- * Content queries are set before the `ngAfterContentInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Directive({
- * selector: 'someDir'
- * })
- * class SomeDir {
- * @ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>;
- *
- * ngAfterContentInit() {
- * // contentChildren is set
- * }
- * }
- * ```
- */
- exports.ContentChildren = decorators_1.makePropDecorator(di_2.ContentChildrenMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ContentChildMetadata.
- /**
- * Configures a content query.
- *
- * Content queries are set before the `ngAfterContentInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Directive({
- * selector: 'someDir'
- * })
- * class SomeDir {
- * @ContentChild(ChildDirective) contentChild;
- *
- * ngAfterContentInit() {
- * // contentChild is set
- * }
- * }
- * ```
- */
- exports.ContentChild = decorators_1.makePropDecorator(di_2.ContentChildMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ViewChildrenMetadata.
- /**
- * Configures a view query.
- *
- * View queries are set before the `ngAfterViewInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Component({
- * selector: 'someDir',
- * templateUrl: 'someTemplate',
- * directives: [ItemDirective]
- * })
- * class SomeDir {
- * @ViewChildren(ItemDirective) viewChildren: QueryList<ItemDirective>;
- *
- * ngAfterViewInit() {
- * // viewChildren is set
- * }
- * }
- * ```
- */
- exports.ViewChildren = decorators_1.makePropDecorator(di_2.ViewChildrenMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ViewChildMetadata.
- /**
- * Configures a view query.
- *
- * View queries are set before the `ngAfterViewInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Component({
- * selector: 'someDir',
- * templateUrl: 'someTemplate',
- * directives: [ItemDirective]
- * })
- * class SomeDir {
- * @ViewChild(ItemDirective) viewChild:ItemDirective;
- *
- * ngAfterViewInit() {
- * // viewChild is set
- * }
- * }
- * ```
- */
- exports.ViewChild = decorators_1.makePropDecorator(di_2.ViewChildMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from ViewQueryMetadata.
- /**
- * Similar to {@link QueryMetadata}, but querying the component view, instead of
- * the content children.
- *
- * ### Example ([live demo](http://plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview))
- *
- * ```javascript
- * @Component({...})
- * @View({
- * template: `
- * <item> a </item>
- * <item> b </item>
- * <item> c </item>
- * `
- * })
- * class MyComponent {
- * shown: boolean;
- *
- * constructor(private @Query(Item) items:QueryList<Item>) {
- * items.onChange(() => console.log(items.length));
- * }
- * }
- * ```
- *
- * Supports the same querying parameters as {@link QueryMetadata}, except
- * `descendants`. This always queries the whole view.
- *
- * As `shown` is flipped between true and false, items will contain zero of one
- * items.
- *
- * Specifies that a {@link QueryList} should be injected.
- *
- * The injected object is an iterable and observable live list.
- * See {@link QueryList} for more details.
- */
- exports.ViewQuery = decorators_1.makeParamDecorator(di_2.ViewQueryMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from PipeMetadata.
- /**
- * Declare reusable pipe function.
- *
- * ### Example
- *
- * {@example core/ts/metadata/metadata.ts region='pipe'}
- */
- exports.Pipe = decorators_1.makeDecorator(directives_2.PipeMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from InputMetadata.
- /**
- * Declares a data-bound input property.
- *
- * Angular automatically updates data-bound properties during change detection.
- *
- * `InputMetadata` takes an optional parameter that specifies the name
- * used when instantiating a component in the template. When not provided,
- * the name of the decorated property is used.
- *
- * ### Example
- *
- * The following example creates a component with two input properties.
- *
- * ```typescript
- * @Component({
- * selector: 'bank-account',
- * template: `
- * Bank Name: {{bankName}}
- * Account Id: {{id}}
- * `
- * })
- * class BankAccount {
- * @Input() bankName: string;
- * @Input('account-id') id: string;
- *
- * // this property is not bound, and won't be automatically updated by Angular
- * normalizedBankName: string;
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <bank-account bank-name="RBC" account-id="4747"></bank-account>
- * `,
- * directives: [BankAccount]
- * })
- * class App {}
- *
- * bootstrap(App);
- * ```
- */
- exports.Input = decorators_1.makePropDecorator(directives_2.InputMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from OutputMetadata.
- /**
- * Declares an event-bound output property.
- *
- * When an output property emits an event, an event handler attached to that event
- * the template is invoked.
- *
- * `OutputMetadata` takes an optional parameter that specifies the name
- * used when instantiating a component in the template. When not provided,
- * the name of the decorated property is used.
- *
- * ### Example
- *
- * ```typescript
- * @Directive({
- * selector: 'interval-dir',
- * })
- * class IntervalDir {
- * @Output() everySecond = new EventEmitter();
- * @Output('everyFiveSeconds') five5Secs = new EventEmitter();
- *
- * constructor() {
- * setInterval(() => this.everySecond.emit("event"), 1000);
- * setInterval(() => this.five5Secs.emit("event"), 5000);
- * }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <interval-dir (every-second)="everySecond()" (every-five-seconds)="everyFiveSeconds()">
- * </interval-dir>
- * `,
- * directives: [IntervalDir]
- * })
- * class App {
- * everySecond() { console.log('second'); }
- * everyFiveSeconds() { console.log('five seconds'); }
- * }
- * bootstrap(App);
- * ```
- */
- exports.Output = decorators_1.makePropDecorator(directives_2.OutputMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from HostBindingMetadata.
- /**
- * Declares a host property binding.
- *
- * Angular automatically checks host property bindings during change detection.
- * If a binding changes, it will update the host element of the directive.
- *
- * `HostBindingMetadata` takes an optional parameter that specifies the property
- * name of the host element that will be updated. When not provided,
- * the class property name is used.
- *
- * ### Example
- *
- * The following example creates a directive that sets the `valid` and `invalid` classes
- * on the DOM element that has ngModel directive on it.
- *
- * ```typescript
- * @Directive({selector: '[ngModel]'})
- * class NgModelStatus {
- * constructor(public control:NgModel) {}
- * @HostBinding('[class.valid]') get valid { return this.control.valid; }
- * @HostBinding('[class.invalid]') get invalid { return this.control.invalid; }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `<input [(ngModel)]="prop">`,
- * directives: [FORM_DIRECTIVES, NgModelStatus]
- * })
- * class App {
- * prop;
- * }
- *
- * bootstrap(App);
- * ```
- */
- exports.HostBinding = decorators_1.makePropDecorator(directives_2.HostBindingMetadata);
- // TODO(alexeagle): remove the duplication of this doc. It is copied from HostListenerMetadata.
- /**
- * Declares a host listener.
- *
- * Angular will invoke the decorated method when the host element emits the specified event.
- *
- * If the decorated method returns `false`, then `preventDefault` is applied on the DOM
- * event.
- *
- * ### Example
- *
- * The following example declares a directive that attaches a click listener to the button and
- * counts clicks.
- *
- * ```typescript
- * @Directive({selector: 'button[counting]'})
- * class CountClicks {
- * numberOfClicks = 0;
- *
- * @HostListener('click', ['$event.target'])
- * onClick(btn) {
- * console.log("button", btn, "number of clicks:", this.numberOfClicks++);
- * }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `<button counting>Increment</button>`,
- * directives: [CountClicks]
- * })
- * class App {}
- *
- * bootstrap(App);
- * ```
- */
- exports.HostListener = decorators_1.makePropDecorator(directives_2.HostListenerMetadata);
- /***/ },
- /* 4 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var di_1 = __webpack_require__(6);
- var metadata_1 = __webpack_require__(7);
- /**
- * Specifies that a constant attribute value should be injected.
- *
- * The directive can inject constant string literals of host element attributes.
- *
- * ### Example
- *
- * Suppose we have an `<input>` element and want to know its `type`.
- *
- * ```html
- * <input type="text">
- * ```
- *
- * A decorator can inject string literal `text` like so:
- *
- * {@example core/ts/metadata/metadata.ts region='attributeMetadata'}
- */
- var AttributeMetadata = (function (_super) {
- __extends(AttributeMetadata, _super);
- function AttributeMetadata(attributeName) {
- _super.call(this);
- this.attributeName = attributeName;
- }
- Object.defineProperty(AttributeMetadata.prototype, "token", {
- get: function () {
- // Normally one would default a token to a type of an injected value but here
- // the type of a variable is "string" and we can't use primitive type as a return value
- // so we use instance of Attribute instead. This doesn't matter much in practice as arguments
- // with @Attribute annotation are injected by ElementInjector that doesn't take tokens into
- // account.
- return this;
- },
- enumerable: true,
- configurable: true
- });
- AttributeMetadata.prototype.toString = function () { return "@Attribute(" + lang_1.stringify(this.attributeName) + ")"; };
- AttributeMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], AttributeMetadata);
- return AttributeMetadata;
- })(metadata_1.DependencyMetadata);
- exports.AttributeMetadata = AttributeMetadata;
- /**
- * Declares an injectable parameter to be a live list of directives or variable
- * bindings from the content children of a directive.
- *
- * ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview))
- *
- * Assume that `<tabs>` component would like to get a list its children `<pane>`
- * components as shown in this example:
- *
- * ```html
- * <tabs>
- * <pane title="Overview">...</pane>
- * <pane *ngFor="#o of objects" [title]="o.title">{{o.text}}</pane>
- * </tabs>
- * ```
- *
- * The preferred solution is to query for `Pane` directives using this decorator.
- *
- * ```javascript
- * @Component({
- * selector: 'pane',
- * inputs: ['title']
- * })
- * class Pane {
- * title:string;
- * }
- *
- * @Component({
- * selector: 'tabs',
- * template: `
- * <ul>
- * <li *ngFor="#pane of panes">{{pane.title}}</li>
- * </ul>
- * <content></content>
- * `
- * })
- * class Tabs {
- * panes: QueryList<Pane>;
- * constructor(@Query(Pane) panes:QueryList<Pane>) {
- * this.panes = panes;
- * }
- * }
- * ```
- *
- * A query can look for variable bindings by passing in a string with desired binding symbol.
- *
- * ### Example ([live demo](http://plnkr.co/edit/sT2j25cH1dURAyBRCKx1?p=preview))
- * ```html
- * <seeker>
- * <div #findme>...</div>
- * </seeker>
- *
- * @Component({ selector: 'seeker' })
- * class Seeker {
- * constructor(@Query('findme') elList: QueryList<ElementRef>) {...}
- * }
- * ```
- *
- * In this case the object that is injected depend on the type of the variable
- * binding. It can be an ElementRef, a directive or a component.
- *
- * Passing in a comma separated list of variable bindings will query for all of them.
- *
- * ```html
- * <seeker>
- * <div #find-me>...</div>
- * <div #find-me-too>...</div>
- * </seeker>
- *
- * @Component({
- * selector: 'seeker'
- * })
- * class Seeker {
- * constructor(@Query('findMe, findMeToo') elList: QueryList<ElementRef>) {...}
- * }
- * ```
- *
- * Configure whether query looks for direct children or all descendants
- * of the querying element, by using the `descendants` parameter.
- * It is set to `false` by default.
- *
- * ### Example ([live demo](http://plnkr.co/edit/wtGeB977bv7qvA5FTYl9?p=preview))
- * ```html
- * <container #first>
- * <item>a</item>
- * <item>b</item>
- * <container #second>
- * <item>c</item>
- * </container>
- * </container>
- * ```
- *
- * When querying for items, the first container will see only `a` and `b` by default,
- * but with `Query(TextDirective, {descendants: true})` it will see `c` too.
- *
- * The queried directives are kept in a depth-first pre-order with respect to their
- * positions in the DOM.
- *
- * Query does not look deep into any subcomponent views.
- *
- * Query is updated as part of the change-detection cycle. Since change detection
- * happens after construction of a directive, QueryList will always be empty when observed in the
- * constructor.
- *
- * The injected object is an unmodifiable live list.
- * See {@link QueryList} for more details.
- */
- var QueryMetadata = (function (_super) {
- __extends(QueryMetadata, _super);
- function QueryMetadata(_selector, _a) {
- var _b = _a === void 0 ? {} : _a, _c = _b.descendants, descendants = _c === void 0 ? false : _c, _d = _b.first, first = _d === void 0 ? false : _d;
- _super.call(this);
- this._selector = _selector;
- this.descendants = descendants;
- this.first = first;
- }
- Object.defineProperty(QueryMetadata.prototype, "isViewQuery", {
- /**
- * always `false` to differentiate it with {@link ViewQueryMetadata}.
- */
- get: function () { return false; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(QueryMetadata.prototype, "selector", {
- /**
- * what this is querying for.
- */
- get: function () { return di_1.resolveForwardRef(this._selector); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(QueryMetadata.prototype, "isVarBindingQuery", {
- /**
- * whether this is querying for a variable binding or a directive.
- */
- get: function () { return lang_1.isString(this.selector); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(QueryMetadata.prototype, "varBindings", {
- /**
- * returns a list of variable bindings this is querying for.
- * Only applicable if this is a variable bindings query.
- */
- get: function () { return this.selector.split(','); },
- enumerable: true,
- configurable: true
- });
- QueryMetadata.prototype.toString = function () { return "@Query(" + lang_1.stringify(this.selector) + ")"; };
- QueryMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object, Object])
- ], QueryMetadata);
- return QueryMetadata;
- })(metadata_1.DependencyMetadata);
- exports.QueryMetadata = QueryMetadata;
- // TODO: add an example after ContentChildren and ViewChildren are in master
- /**
- * Configures a content query.
- *
- * Content queries are set before the `ngAfterContentInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Directive({
- * selector: 'someDir'
- * })
- * class SomeDir {
- * @ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>;
- *
- * ngAfterContentInit() {
- * // contentChildren is set
- * }
- * }
- * ```
- */
- var ContentChildrenMetadata = (function (_super) {
- __extends(ContentChildrenMetadata, _super);
- function ContentChildrenMetadata(_selector, _a) {
- var _b = (_a === void 0 ? {} : _a).descendants, descendants = _b === void 0 ? false : _b;
- _super.call(this, _selector, { descendants: descendants });
- }
- ContentChildrenMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object, Object])
- ], ContentChildrenMetadata);
- return ContentChildrenMetadata;
- })(QueryMetadata);
- exports.ContentChildrenMetadata = ContentChildrenMetadata;
- // TODO: add an example after ContentChild and ViewChild are in master
- /**
- * Configures a content query.
- *
- * Content queries are set before the `ngAfterContentInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Directive({
- * selector: 'someDir'
- * })
- * class SomeDir {
- * @ContentChild(ChildDirective) contentChild;
- *
- * ngAfterContentInit() {
- * // contentChild is set
- * }
- * }
- * ```
- */
- var ContentChildMetadata = (function (_super) {
- __extends(ContentChildMetadata, _super);
- function ContentChildMetadata(_selector) {
- _super.call(this, _selector, { descendants: true, first: true });
- }
- ContentChildMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], ContentChildMetadata);
- return ContentChildMetadata;
- })(QueryMetadata);
- exports.ContentChildMetadata = ContentChildMetadata;
- /**
- * Similar to {@link QueryMetadata}, but querying the component view, instead of
- * the content children.
- *
- * ### Example ([live demo](http://plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview))
- *
- * ```javascript
- * @Component({...})
- * @View({
- * template: `
- * <item> a </item>
- * <item> b </item>
- * <item> c </item>
- * `
- * })
- * class MyComponent {
- * shown: boolean;
- *
- * constructor(private @Query(Item) items:QueryList<Item>) {
- * items.onChange(() => console.log(items.length));
- * }
- * }
- * ```
- *
- * Supports the same querying parameters as {@link QueryMetadata}, except
- * `descendants`. This always queries the whole view.
- *
- * As `shown` is flipped between true and false, items will contain zero of one
- * items.
- *
- * Specifies that a {@link QueryList} should be injected.
- *
- * The injected object is an iterable and observable live list.
- * See {@link QueryList} for more details.
- */
- var ViewQueryMetadata = (function (_super) {
- __extends(ViewQueryMetadata, _super);
- function ViewQueryMetadata(_selector, _a) {
- var _b = _a === void 0 ? {} : _a, _c = _b.descendants, descendants = _c === void 0 ? false : _c, _d = _b.first, first = _d === void 0 ? false : _d;
- _super.call(this, _selector, { descendants: descendants, first: first });
- }
- Object.defineProperty(ViewQueryMetadata.prototype, "isViewQuery", {
- /**
- * always `true` to differentiate it with {@link QueryMetadata}.
- */
- get: function () { return true; },
- enumerable: true,
- configurable: true
- });
- ViewQueryMetadata.prototype.toString = function () { return "@ViewQuery(" + lang_1.stringify(this.selector) + ")"; };
- ViewQueryMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object, Object])
- ], ViewQueryMetadata);
- return ViewQueryMetadata;
- })(QueryMetadata);
- exports.ViewQueryMetadata = ViewQueryMetadata;
- /**
- * Configures a view query.
- *
- * View queries are set before the `ngAfterViewInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Component({
- * selector: 'someDir',
- * templateUrl: 'someTemplate',
- * directives: [ItemDirective]
- * })
- * class SomeDir {
- * @ViewChildren(ItemDirective) viewChildren: QueryList<ItemDirective>;
- *
- * ngAfterViewInit() {
- * // viewChildren is set
- * }
- * }
- * ```
- */
- var ViewChildrenMetadata = (function (_super) {
- __extends(ViewChildrenMetadata, _super);
- function ViewChildrenMetadata(_selector) {
- _super.call(this, _selector, { descendants: true });
- }
- ViewChildrenMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], ViewChildrenMetadata);
- return ViewChildrenMetadata;
- })(ViewQueryMetadata);
- exports.ViewChildrenMetadata = ViewChildrenMetadata;
- /**
- * Configures a view query.
- *
- * View queries are set before the `ngAfterViewInit` callback is called.
- *
- * ### Example
- *
- * ```
- * @Component({
- * selector: 'someDir',
- * templateUrl: 'someTemplate',
- * directives: [ItemDirective]
- * })
- * class SomeDir {
- * @ViewChild(ItemDirective) viewChild:ItemDirective;
- *
- * ngAfterViewInit() {
- * // viewChild is set
- * }
- * }
- * ```
- */
- var ViewChildMetadata = (function (_super) {
- __extends(ViewChildMetadata, _super);
- function ViewChildMetadata(_selector) {
- _super.call(this, _selector, { descendants: true, first: true });
- }
- ViewChildMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], ViewChildMetadata);
- return ViewChildMetadata;
- })(ViewQueryMetadata);
- exports.ViewChildMetadata = ViewChildMetadata;
- /***/ },
- /* 5 */
- /***/ function(module, exports) {
- /* WEBPACK VAR INJECTION */(function(global) {var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var globalScope;
- if (typeof window === 'undefined') {
- if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
- // TODO: Replace any with WorkerGlobalScope from lib.webworker.d.ts #3492
- globalScope = self;
- }
- else {
- globalScope = global;
- }
- }
- else {
- globalScope = window;
- }
- ;
- exports.IS_DART = false;
- // Need to declare a new variable for global here since TypeScript
- // exports the original value of the symbol.
- var _global = globalScope;
- exports.global = _global;
- exports.Type = Function;
- function getTypeNameForDebugging(type) {
- return type['name'];
- }
- exports.getTypeNameForDebugging = getTypeNameForDebugging;
- exports.Math = _global.Math;
- exports.Date = _global.Date;
- var _devMode = true;
- var _modeLocked = false;
- function lockMode() {
- _modeLocked = true;
- }
- exports.lockMode = lockMode;
- /**
- * Disable Angular's development mode, which turns off assertions and other
- * checks within the framework.
- *
- * One important assertion this disables verifies that a change detection pass
- * does not result in additional changes to any bindings (also known as
- * unidirectional data flow).
- */
- function enableProdMode() {
- if (_modeLocked) {
- // Cannot use BaseException as that ends up importing from facade/lang.
- throw 'Cannot enable prod mode after platform setup.';
- }
- _devMode = false;
- }
- exports.enableProdMode = enableProdMode;
- function assertionsEnabled() {
- return _devMode;
- }
- exports.assertionsEnabled = assertionsEnabled;
- // TODO: remove calls to assert in production environment
- // Note: Can't just export this and import in in other files
- // as `assert` is a reserved keyword in Dart
- _global.assert = function assert(condition) {
- // TODO: to be fixed properly via #2830, noop for now
- };
- // This function is needed only to properly support Dart's const expressions
- // see https://github.com/angular/ts2dart/pull/151 for more info
- function CONST_EXPR(expr) {
- return expr;
- }
- exports.CONST_EXPR = CONST_EXPR;
- function CONST() {
- return function (target) { return target; };
- }
- exports.CONST = CONST;
- function isPresent(obj) {
- return obj !== undefined && obj !== null;
- }
- exports.isPresent = isPresent;
- function isBlank(obj) {
- return obj === undefined || obj === null;
- }
- exports.isBlank = isBlank;
- function isString(obj) {
- return typeof obj === "string";
- }
- exports.isString = isString;
- function isFunction(obj) {
- return typeof obj === "function";
- }
- exports.isFunction = isFunction;
- function isType(obj) {
- return isFunction(obj);
- }
- exports.isType = isType;
- function isStringMap(obj) {
- return typeof obj === 'object' && obj !== null;
- }
- exports.isStringMap = isStringMap;
- function isPromise(obj) {
- return obj instanceof _global.Promise;
- }
- exports.isPromise = isPromise;
- function isArray(obj) {
- return Array.isArray(obj);
- }
- exports.isArray = isArray;
- function isNumber(obj) {
- return typeof obj === 'number';
- }
- exports.isNumber = isNumber;
- function isDate(obj) {
- return obj instanceof exports.Date && !isNaN(obj.valueOf());
- }
- exports.isDate = isDate;
- function noop() { }
- exports.noop = noop;
- function stringify(token) {
- if (typeof token === 'string') {
- return token;
- }
- if (token === undefined || token === null) {
- return '' + token;
- }
- if (token.name) {
- return token.name;
- }
- var res = token.toString();
- var newLineIndex = res.indexOf("\n");
- return (newLineIndex === -1) ? res : res.substring(0, newLineIndex);
- }
- exports.stringify = stringify;
- // serialize / deserialize enum exist only for consistency with dart API
- // enums in typescript don't need to be serialized
- function serializeEnum(val) {
- return val;
- }
- exports.serializeEnum = serializeEnum;
- function deserializeEnum(val, values) {
- return val;
- }
- exports.deserializeEnum = deserializeEnum;
- var StringWrapper = (function () {
- function StringWrapper() {
- }
- StringWrapper.fromCharCode = function (code) { return String.fromCharCode(code); };
- StringWrapper.charCodeAt = function (s, index) { return s.charCodeAt(index); };
- StringWrapper.split = function (s, regExp) { return s.split(regExp); };
- StringWrapper.equals = function (s, s2) { return s === s2; };
- StringWrapper.stripLeft = function (s, charVal) {
- if (s && s.length) {
- var pos = 0;
- for (var i = 0; i < s.length; i++) {
- if (s[i] != charVal)
- break;
- pos++;
- }
- s = s.substring(pos);
- }
- return s;
- };
- StringWrapper.stripRight = function (s, charVal) {
- if (s && s.length) {
- var pos = s.length;
- for (var i = s.length - 1; i >= 0; i--) {
- if (s[i] != charVal)
- break;
- pos--;
- }
- s = s.substring(0, pos);
- }
- return s;
- };
- StringWrapper.replace = function (s, from, replace) {
- return s.replace(from, replace);
- };
- StringWrapper.replaceAll = function (s, from, replace) {
- return s.replace(from, replace);
- };
- StringWrapper.slice = function (s, from, to) {
- if (from === void 0) { from = 0; }
- if (to === void 0) { to = null; }
- return s.slice(from, to === null ? undefined : to);
- };
- StringWrapper.replaceAllMapped = function (s, from, cb) {
- return s.replace(from, function () {
- var matches = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- matches[_i - 0] = arguments[_i];
- }
- // Remove offset & string from the result array
- matches.splice(-2, 2);
- // The callback receives match, p1, ..., pn
- return cb(matches);
- });
- };
- StringWrapper.contains = function (s, substr) { return s.indexOf(substr) != -1; };
- StringWrapper.compare = function (a, b) {
- if (a < b) {
- return -1;
- }
- else if (a > b) {
- return 1;
- }
- else {
- return 0;
- }
- };
- return StringWrapper;
- })();
- exports.StringWrapper = StringWrapper;
- var StringJoiner = (function () {
- function StringJoiner(parts) {
- if (parts === void 0) { parts = []; }
- this.parts = parts;
- }
- StringJoiner.prototype.add = function (part) { this.parts.push(part); };
- StringJoiner.prototype.toString = function () { return this.parts.join(""); };
- return StringJoiner;
- })();
- exports.StringJoiner = StringJoiner;
- var NumberParseError = (function (_super) {
- __extends(NumberParseError, _super);
- function NumberParseError(message) {
- _super.call(this);
- this.message = message;
- }
- NumberParseError.prototype.toString = function () { return this.message; };
- return NumberParseError;
- })(Error);
- exports.NumberParseError = NumberParseError;
- var NumberWrapper = (function () {
- function NumberWrapper() {
- }
- NumberWrapper.toFixed = function (n, fractionDigits) { return n.toFixed(fractionDigits); };
- NumberWrapper.equal = function (a, b) { return a === b; };
- NumberWrapper.parseIntAutoRadix = function (text) {
- var result = parseInt(text);
- if (isNaN(result)) {
- throw new NumberParseError("Invalid integer literal when parsing " + text);
- }
- return result;
- };
- NumberWrapper.parseInt = function (text, radix) {
- if (radix == 10) {
- if (/^(\-|\+)?[0-9]+$/.test(text)) {
- return parseInt(text, radix);
- }
- }
- else if (radix == 16) {
- if (/^(\-|\+)?[0-9ABCDEFabcdef]+$/.test(text)) {
- return parseInt(text, radix);
- }
- }
- else {
- var result = parseInt(text, radix);
- if (!isNaN(result)) {
- return result;
- }
- }
- throw new NumberParseError("Invalid integer literal when parsing " + text + " in base " +
- radix);
- };
- // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error.
- NumberWrapper.parseFloat = function (text) { return parseFloat(text); };
- Object.defineProperty(NumberWrapper, "NaN", {
- get: function () { return NaN; },
- enumerable: true,
- configurable: true
- });
- NumberWrapper.isNaN = function (value) { return isNaN(value); };
- NumberWrapper.isInteger = function (value) { return Number.isInteger(value); };
- return NumberWrapper;
- })();
- exports.NumberWrapper = NumberWrapper;
- exports.RegExp = _global.RegExp;
- var RegExpWrapper = (function () {
- function RegExpWrapper() {
- }
- RegExpWrapper.create = function (regExpStr, flags) {
- if (flags === void 0) { flags = ''; }
- flags = flags.replace(/g/g, '');
- return new _global.RegExp(regExpStr, flags + 'g');
- };
- RegExpWrapper.firstMatch = function (regExp, input) {
- // Reset multimatch regex state
- regExp.lastIndex = 0;
- return regExp.exec(input);
- };
- RegExpWrapper.test = function (regExp, input) {
- regExp.lastIndex = 0;
- return regExp.test(input);
- };
- RegExpWrapper.matcher = function (regExp, input) {
- // Reset regex state for the case
- // someone did not loop over all matches
- // last time.
- regExp.lastIndex = 0;
- return { re: regExp, input: input };
- };
- return RegExpWrapper;
- })();
- exports.RegExpWrapper = RegExpWrapper;
- var RegExpMatcherWrapper = (function () {
- function RegExpMatcherWrapper() {
- }
- RegExpMatcherWrapper.next = function (matcher) {
- return matcher.re.exec(matcher.input);
- };
- return RegExpMatcherWrapper;
- })();
- exports.RegExpMatcherWrapper = RegExpMatcherWrapper;
- var FunctionWrapper = (function () {
- function FunctionWrapper() {
- }
- FunctionWrapper.apply = function (fn, posArgs) { return fn.apply(null, posArgs); };
- return FunctionWrapper;
- })();
- exports.FunctionWrapper = FunctionWrapper;
- // JS has NaN !== NaN
- function looseIdentical(a, b) {
- return a === b || typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b);
- }
- exports.looseIdentical = looseIdentical;
- // JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise)
- // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
- function getMapKey(value) {
- return value;
- }
- exports.getMapKey = getMapKey;
- function normalizeBlank(obj) {
- return isBlank(obj) ? null : obj;
- }
- exports.normalizeBlank = normalizeBlank;
- function normalizeBool(obj) {
- return isBlank(obj) ? false : obj;
- }
- exports.normalizeBool = normalizeBool;
- function isJsObject(o) {
- return o !== null && (typeof o === "function" || typeof o === "object");
- }
- exports.isJsObject = isJsObject;
- function print(obj) {
- console.log(obj);
- }
- exports.print = print;
- // Can't be all uppercase as our transpiler would think it is a special directive...
- var Json = (function () {
- function Json() {
- }
- Json.parse = function (s) { return _global.JSON.parse(s); };
- Json.stringify = function (data) {
- // Dart doesn't take 3 arguments
- return _global.JSON.stringify(data, null, 2);
- };
- return Json;
- })();
- exports.Json = Json;
- var DateWrapper = (function () {
- function DateWrapper() {
- }
- DateWrapper.create = function (year, month, day, hour, minutes, seconds, milliseconds) {
- if (month === void 0) { month = 1; }
- if (day === void 0) { day = 1; }
- if (hour === void 0) { hour = 0; }
- if (minutes === void 0) { minutes = 0; }
- if (seconds === void 0) { seconds = 0; }
- if (milliseconds === void 0) { milliseconds = 0; }
- return new exports.Date(year, month - 1, day, hour, minutes, seconds, milliseconds);
- };
- DateWrapper.fromISOString = function (str) { return new exports.Date(str); };
- DateWrapper.fromMillis = function (ms) { return new exports.Date(ms); };
- DateWrapper.toMillis = function (date) { return date.getTime(); };
- DateWrapper.now = function () { return new exports.Date(); };
- DateWrapper.toJson = function (date) { return date.toJSON(); };
- return DateWrapper;
- })();
- exports.DateWrapper = DateWrapper;
- function setValueOnPath(global, path, value) {
- var parts = path.split('.');
- var obj = global;
- while (parts.length > 1) {
- var name = parts.shift();
- if (obj.hasOwnProperty(name) && isPresent(obj[name])) {
- obj = obj[name];
- }
- else {
- obj = obj[name] = {};
- }
- }
- if (obj === undefined || obj === null) {
- obj = {};
- }
- obj[parts.shift()] = value;
- }
- exports.setValueOnPath = setValueOnPath;
- var _symbolIterator = null;
- function getSymbolIterator() {
- if (isBlank(_symbolIterator)) {
- if (isPresent(Symbol) && isPresent(Symbol.iterator)) {
- _symbolIterator = Symbol.iterator;
- }
- else {
- // es6-shim specific logic
- var keys = Object.getOwnPropertyNames(Map.prototype);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (key !== 'entries' && key !== 'size' &&
- Map.prototype[key] === Map.prototype['entries']) {
- _symbolIterator = key;
- }
- }
- }
- }
- return _symbolIterator;
- }
- exports.getSymbolIterator = getSymbolIterator;
- /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
- /***/ },
- /* 6 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * The `di` module provides dependency injection container services.
- */
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- var metadata_1 = __webpack_require__(7);
- exports.InjectMetadata = metadata_1.InjectMetadata;
- exports.OptionalMetadata = metadata_1.OptionalMetadata;
- exports.InjectableMetadata = metadata_1.InjectableMetadata;
- exports.SelfMetadata = metadata_1.SelfMetadata;
- exports.HostMetadata = metadata_1.HostMetadata;
- exports.SkipSelfMetadata = metadata_1.SkipSelfMetadata;
- exports.DependencyMetadata = metadata_1.DependencyMetadata;
- // we have to reexport * because Dart and TS export two different sets of types
- __export(__webpack_require__(8));
- var forward_ref_1 = __webpack_require__(10);
- exports.forwardRef = forward_ref_1.forwardRef;
- exports.resolveForwardRef = forward_ref_1.resolveForwardRef;
- var injector_1 = __webpack_require__(11);
- exports.Injector = injector_1.Injector;
- var provider_1 = __webpack_require__(13);
- exports.Binding = provider_1.Binding;
- exports.ProviderBuilder = provider_1.ProviderBuilder;
- exports.ResolvedFactory = provider_1.ResolvedFactory;
- exports.Dependency = provider_1.Dependency;
- exports.bind = provider_1.bind;
- exports.Provider = provider_1.Provider;
- exports.provide = provider_1.provide;
- var key_1 = __webpack_require__(19);
- exports.Key = key_1.Key;
- exports.TypeLiteral = key_1.TypeLiteral;
- var exceptions_1 = __webpack_require__(21);
- exports.NoProviderError = exceptions_1.NoProviderError;
- exports.AbstractProviderError = exceptions_1.AbstractProviderError;
- exports.CyclicDependencyError = exceptions_1.CyclicDependencyError;
- exports.InstantiationError = exceptions_1.InstantiationError;
- exports.InvalidProviderError = exceptions_1.InvalidProviderError;
- exports.NoAnnotationError = exceptions_1.NoAnnotationError;
- exports.OutOfBoundsError = exceptions_1.OutOfBoundsError;
- var opaque_token_1 = __webpack_require__(22);
- exports.OpaqueToken = opaque_token_1.OpaqueToken;
- /***/ },
- /* 7 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- /**
- * A parameter metadata that specifies a dependency.
- *
- * ### Example ([live demo](http://plnkr.co/edit/6uHYJK?p=preview))
- *
- * ```typescript
- * class Engine {}
- *
- * @Injectable()
- * class Car {
- * engine;
- * constructor(@Inject("MyEngine") engine:Engine) {
- * this.engine = engine;
- * }
- * }
- *
- * var injector = Injector.resolveAndCreate([
- * provide("MyEngine", {useClass: Engine}),
- * Car
- * ]);
- *
- * expect(injector.get(Car).engine instanceof Engine).toBe(true);
- * ```
- *
- * When `@Inject()` is not present, {@link Injector} will use the type annotation of the parameter.
- *
- * ### Example
- *
- * ```typescript
- * class Engine {}
- *
- * @Injectable()
- * class Car {
- * constructor(public engine: Engine) {} //same as constructor(@Inject(Engine) engine:Engine)
- * }
- *
- * var injector = Injector.resolveAndCreate([Engine, Car]);
- * expect(injector.get(Car).engine instanceof Engine).toBe(true);
- * ```
- */
- var InjectMetadata = (function () {
- function InjectMetadata(token) {
- this.token = token;
- }
- InjectMetadata.prototype.toString = function () { return "@Inject(" + lang_1.stringify(this.token) + ")"; };
- InjectMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], InjectMetadata);
- return InjectMetadata;
- })();
- exports.InjectMetadata = InjectMetadata;
- /**
- * A parameter metadata that marks a dependency as optional. {@link Injector} provides `null` if
- * the dependency is not found.
- *
- * ### Example ([live demo](http://plnkr.co/edit/AsryOm?p=preview))
- *
- * ```typescript
- * class Engine {}
- *
- * @Injectable()
- * class Car {
- * engine;
- * constructor(@Optional() engine:Engine) {
- * this.engine = engine;
- * }
- * }
- *
- * var injector = Injector.resolveAndCreate([Car]);
- * expect(injector.get(Car).engine).toBeNull();
- * ```
- */
- var OptionalMetadata = (function () {
- function OptionalMetadata() {
- }
- OptionalMetadata.prototype.toString = function () { return "@Optional()"; };
- OptionalMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], OptionalMetadata);
- return OptionalMetadata;
- })();
- exports.OptionalMetadata = OptionalMetadata;
- /**
- * `DependencyMetadata` is used by the framework to extend DI.
- * This is internal to Angular and should not be used directly.
- */
- var DependencyMetadata = (function () {
- function DependencyMetadata() {
- }
- Object.defineProperty(DependencyMetadata.prototype, "token", {
- get: function () { return null; },
- enumerable: true,
- configurable: true
- });
- DependencyMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], DependencyMetadata);
- return DependencyMetadata;
- })();
- exports.DependencyMetadata = DependencyMetadata;
- /**
- * A marker metadata that marks a class as available to {@link Injector} for creation.
- *
- * ### Example ([live demo](http://plnkr.co/edit/Wk4DMQ?p=preview))
- *
- * ```typescript
- * @Injectable()
- * class UsefulService {}
- *
- * @Injectable()
- * class NeedsService {
- * constructor(public service:UsefulService) {}
- * }
- *
- * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]);
- * expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
- * ```
- * {@link Injector} will throw {@link NoAnnotationError} when trying to instantiate a class that
- * does not have `@Injectable` marker, as shown in the example below.
- *
- * ```typescript
- * class UsefulService {}
- *
- * class NeedsService {
- * constructor(public service:UsefulService) {}
- * }
- *
- * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]);
- * expect(() => injector.get(NeedsService)).toThrowError();
- * ```
- */
- var InjectableMetadata = (function () {
- function InjectableMetadata() {
- }
- InjectableMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], InjectableMetadata);
- return InjectableMetadata;
- })();
- exports.InjectableMetadata = InjectableMetadata;
- /**
- * Specifies that an {@link Injector} should retrieve a dependency only from itself.
- *
- * ### Example ([live demo](http://plnkr.co/edit/NeagAg?p=preview))
- *
- * ```typescript
- * class Dependency {
- * }
- *
- * @Injectable()
- * class NeedsDependency {
- * dependency;
- * constructor(@Self() dependency:Dependency) {
- * this.dependency = dependency;
- * }
- * }
- *
- * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]);
- * var nd = inj.get(NeedsDependency);
- *
- * expect(nd.dependency instanceof Dependency).toBe(true);
- *
- * var inj = Injector.resolveAndCreate([Dependency]);
- * var child = inj.resolveAndCreateChild([NeedsDependency]);
- * expect(() => child.get(NeedsDependency)).toThrowError();
- * ```
- */
- var SelfMetadata = (function () {
- function SelfMetadata() {
- }
- SelfMetadata.prototype.toString = function () { return "@Self()"; };
- SelfMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], SelfMetadata);
- return SelfMetadata;
- })();
- exports.SelfMetadata = SelfMetadata;
- /**
- * Specifies that the dependency resolution should start from the parent injector.
- *
- * ### Example ([live demo](http://plnkr.co/edit/Wchdzb?p=preview))
- *
- * ```typescript
- * class Dependency {
- * }
- *
- * @Injectable()
- * class NeedsDependency {
- * dependency;
- * constructor(@SkipSelf() dependency:Dependency) {
- * this.dependency = dependency;
- * }
- * }
- *
- * var parent = Injector.resolveAndCreate([Dependency]);
- * var child = parent.resolveAndCreateChild([NeedsDependency]);
- * expect(child.get(NeedsDependency).dependency instanceof Depedency).toBe(true);
- *
- * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]);
- * expect(() => inj.get(NeedsDependency)).toThrowError();
- * ```
- */
- var SkipSelfMetadata = (function () {
- function SkipSelfMetadata() {
- }
- SkipSelfMetadata.prototype.toString = function () { return "@SkipSelf()"; };
- SkipSelfMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], SkipSelfMetadata);
- return SkipSelfMetadata;
- })();
- exports.SkipSelfMetadata = SkipSelfMetadata;
- /**
- * Specifies that an injector should retrieve a dependency from any injector until reaching the
- * closest host.
- *
- * In Angular, a component element is automatically declared as a host for all the injectors in
- * its view.
- *
- * ### Example ([live demo](http://plnkr.co/edit/GX79pV?p=preview))
- *
- * In the following example `App` contains `ParentCmp`, which contains `ChildDirective`.
- * So `ParentCmp` is the host of `ChildDirective`.
- *
- * `ChildDirective` depends on two services: `HostService` and `OtherService`.
- * `HostService` is defined at `ParentCmp`, and `OtherService` is defined at `App`.
- *
- *```typescript
- * class OtherService {}
- * class HostService {}
- *
- * @Directive({
- * selector: 'child-directive'
- * })
- * class ChildDirective {
- * constructor(@Optional() @Host() os:OtherService, @Optional() @Host() hs:HostService){
- * console.log("os is null", os);
- * console.log("hs is NOT null", hs);
- * }
- * }
- *
- * @Component({
- * selector: 'parent-cmp',
- * providers: [HostService],
- * template: `
- * Dir: <child-directive></child-directive>
- * `,
- * directives: [ChildDirective]
- * })
- * class ParentCmp {
- * }
- *
- * @Component({
- * selector: 'app',
- * providers: [OtherService],
- * template: `
- * Parent: <parent-cmp></parent-cmp>
- * `,
- * directives: [ParentCmp]
- * })
- * class App {
- * }
- *
- * bootstrap(App);
- *```
- */
- var HostMetadata = (function () {
- function HostMetadata() {
- }
- HostMetadata.prototype.toString = function () { return "@Host()"; };
- HostMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], HostMetadata);
- return HostMetadata;
- })();
- exports.HostMetadata = HostMetadata;
- /***/ },
- /* 8 */
- /***/ function(module, exports, __webpack_require__) {
- var metadata_1 = __webpack_require__(7);
- var decorators_1 = __webpack_require__(9);
- /**
- * Factory for creating {@link InjectMetadata}.
- */
- exports.Inject = decorators_1.makeParamDecorator(metadata_1.InjectMetadata);
- /**
- * Factory for creating {@link OptionalMetadata}.
- */
- exports.Optional = decorators_1.makeParamDecorator(metadata_1.OptionalMetadata);
- /**
- * Factory for creating {@link InjectableMetadata}.
- */
- exports.Injectable = decorators_1.makeDecorator(metadata_1.InjectableMetadata);
- /**
- * Factory for creating {@link SelfMetadata}.
- */
- exports.Self = decorators_1.makeParamDecorator(metadata_1.SelfMetadata);
- /**
- * Factory for creating {@link HostMetadata}.
- */
- exports.Host = decorators_1.makeParamDecorator(metadata_1.HostMetadata);
- /**
- * Factory for creating {@link SkipSelfMetadata}.
- */
- exports.SkipSelf = decorators_1.makeParamDecorator(metadata_1.SkipSelfMetadata);
- /***/ },
- /* 9 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- function extractAnnotation(annotation) {
- if (lang_1.isFunction(annotation) && annotation.hasOwnProperty('annotation')) {
- // it is a decorator, extract annotation
- annotation = annotation.annotation;
- }
- return annotation;
- }
- function applyParams(fnOrArray, key) {
- if (fnOrArray === Object || fnOrArray === String || fnOrArray === Function ||
- fnOrArray === Number || fnOrArray === Array) {
- throw new Error("Can not use native " + lang_1.stringify(fnOrArray) + " as constructor");
- }
- if (lang_1.isFunction(fnOrArray)) {
- return fnOrArray;
- }
- else if (fnOrArray instanceof Array) {
- var annotations = fnOrArray;
- var fn = fnOrArray[fnOrArray.length - 1];
- if (!lang_1.isFunction(fn)) {
- throw new Error("Last position of Class method array must be Function in key " + key + " was '" + lang_1.stringify(fn) + "'");
- }
- var annoLength = annotations.length - 1;
- if (annoLength != fn.length) {
- throw new Error("Number of annotations (" + annoLength + ") does not match number of arguments (" + fn.length + ") in the function: " + lang_1.stringify(fn));
- }
- var paramsAnnotations = [];
- for (var i = 0, ii = annotations.length - 1; i < ii; i++) {
- var paramAnnotations = [];
- paramsAnnotations.push(paramAnnotations);
- var annotation = annotations[i];
- if (annotation instanceof Array) {
- for (var j = 0; j < annotation.length; j++) {
- paramAnnotations.push(extractAnnotation(annotation[j]));
- }
- }
- else if (lang_1.isFunction(annotation)) {
- paramAnnotations.push(extractAnnotation(annotation));
- }
- else {
- paramAnnotations.push(annotation);
- }
- }
- Reflect.defineMetadata('parameters', paramsAnnotations, fn);
- return fn;
- }
- else {
- throw new Error("Only Function or Array is supported in Class definition for key '" + key + "' is '" + lang_1.stringify(fnOrArray) + "'");
- }
- }
- /**
- * Provides a way for expressing ES6 classes with parameter annotations in ES5.
- *
- * ## Basic Example
- *
- * ```
- * var Greeter = ng.Class({
- * constructor: function(name) {
- * this.name = name;
- * },
- *
- * greet: function() {
- * alert('Hello ' + this.name + '!');
- * }
- * });
- * ```
- *
- * is equivalent to ES6:
- *
- * ```
- * class Greeter {
- * constructor(name) {
- * this.name = name;
- * }
- *
- * greet() {
- * alert('Hello ' + this.name + '!');
- * }
- * }
- * ```
- *
- * or equivalent to ES5:
- *
- * ```
- * var Greeter = function (name) {
- * this.name = name;
- * }
- *
- * Greeter.prototype.greet = function () {
- * alert('Hello ' + this.name + '!');
- * }
- * ```
- *
- * ### Example with parameter annotations
- *
- * ```
- * var MyService = ng.Class({
- * constructor: [String, [new Query(), QueryList], function(name, queryList) {
- * ...
- * }]
- * });
- * ```
- *
- * is equivalent to ES6:
- *
- * ```
- * class MyService {
- * constructor(name: string, @Query() queryList: QueryList) {
- * ...
- * }
- * }
- * ```
- *
- * ### Example with inheritance
- *
- * ```
- * var Shape = ng.Class({
- * constructor: (color) {
- * this.color = color;
- * }
- * });
- *
- * var Square = ng.Class({
- * extends: Shape,
- * constructor: function(color, size) {
- * Shape.call(this, color);
- * this.size = size;
- * }
- * });
- * ```
- */
- function Class(clsDef) {
- var constructor = applyParams(clsDef.hasOwnProperty('constructor') ? clsDef.constructor : undefined, 'constructor');
- var proto = constructor.prototype;
- if (clsDef.hasOwnProperty('extends')) {
- if (lang_1.isFunction(clsDef.extends)) {
- constructor.prototype = proto =
- Object.create(clsDef.extends.prototype);
- }
- else {
- throw new Error("Class definition 'extends' property must be a constructor function was: " + lang_1.stringify(clsDef.extends));
- }
- }
- for (var key in clsDef) {
- if (key != 'extends' && key != 'prototype' && clsDef.hasOwnProperty(key)) {
- proto[key] = applyParams(clsDef[key], key);
- }
- }
- if (this && this.annotations instanceof Array) {
- Reflect.defineMetadata('annotations', this.annotations, constructor);
- }
- return constructor;
- }
- exports.Class = Class;
- var Reflect = lang_1.global.Reflect;
- if (!(Reflect && Reflect.getMetadata)) {
- throw 'reflect-metadata shim is required when using class decorators';
- }
- function makeDecorator(annotationCls, chainFn) {
- if (chainFn === void 0) { chainFn = null; }
- function DecoratorFactory(objOrType) {
- var annotationInstance = new annotationCls(objOrType);
- if (this instanceof annotationCls) {
- return annotationInstance;
- }
- else {
- var chainAnnotation = lang_1.isFunction(this) && this.annotations instanceof Array ? this.annotations : [];
- chainAnnotation.push(annotationInstance);
- var TypeDecorator = function TypeDecorator(cls) {
- var annotations = Reflect.getOwnMetadata('annotations', cls);
- annotations = annotations || [];
- annotations.push(annotationInstance);
- Reflect.defineMetadata('annotations', annotations, cls);
- return cls;
- };
- TypeDecorator.annotations = chainAnnotation;
- TypeDecorator.Class = Class;
- if (chainFn)
- chainFn(TypeDecorator);
- return TypeDecorator;
- }
- }
- DecoratorFactory.prototype = Object.create(annotationCls.prototype);
- return DecoratorFactory;
- }
- exports.makeDecorator = makeDecorator;
- function makeParamDecorator(annotationCls) {
- function ParamDecoratorFactory() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i - 0] = arguments[_i];
- }
- var annotationInstance = Object.create(annotationCls.prototype);
- annotationCls.apply(annotationInstance, args);
- if (this instanceof annotationCls) {
- return annotationInstance;
- }
- else {
- ParamDecorator.annotation = annotationInstance;
- return ParamDecorator;
- }
- function ParamDecorator(cls, unusedKey, index) {
- var parameters = Reflect.getMetadata('parameters', cls);
- parameters = parameters || [];
- // there might be gaps if some in between parameters do not have annotations.
- // we pad with nulls.
- while (parameters.length <= index) {
- parameters.push(null);
- }
- parameters[index] = parameters[index] || [];
- var annotationsForParam = parameters[index];
- annotationsForParam.push(annotationInstance);
- Reflect.defineMetadata('parameters', parameters, cls);
- return cls;
- }
- }
- ParamDecoratorFactory.prototype = Object.create(annotationCls.prototype);
- return ParamDecoratorFactory;
- }
- exports.makeParamDecorator = makeParamDecorator;
- function makePropDecorator(decoratorCls) {
- function PropDecoratorFactory() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i - 0] = arguments[_i];
- }
- var decoratorInstance = Object.create(decoratorCls.prototype);
- decoratorCls.apply(decoratorInstance, args);
- if (this instanceof decoratorCls) {
- return decoratorInstance;
- }
- else {
- return function PropDecorator(target, name) {
- var meta = Reflect.getOwnMetadata('propMetadata', target.constructor);
- meta = meta || {};
- meta[name] = meta[name] || [];
- meta[name].unshift(decoratorInstance);
- Reflect.defineMetadata('propMetadata', meta, target.constructor);
- };
- }
- }
- PropDecoratorFactory.prototype = Object.create(decoratorCls.prototype);
- return PropDecoratorFactory;
- }
- exports.makePropDecorator = makePropDecorator;
- /***/ },
- /* 10 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- /**
- * Allows to refer to references which are not yet defined.
- *
- * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
- * DI is declared,
- * but not yet defined. It is also used when the `token` which we use when creating a query is not
- * yet defined.
- *
- * ### Example
- * {@example core/di/ts/forward_ref/forward_ref.ts region='forward_ref'}
- */
- function forwardRef(forwardRefFn) {
- forwardRefFn.__forward_ref__ = forwardRef;
- forwardRefFn.toString = function () { return lang_1.stringify(this()); };
- return forwardRefFn;
- }
- exports.forwardRef = forwardRef;
- /**
- * Lazily retrieves the reference value from a forwardRef.
- *
- * Acts as the identity function when given a non-forward-ref value.
- *
- * ### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview))
- *
- * ```typescript
- * var ref = forwardRef(() => "refValue");
- * expect(resolveForwardRef(ref)).toEqual("refValue");
- * expect(resolveForwardRef("regularValue")).toEqual("regularValue");
- * ```
- *
- * See: {@link forwardRef}
- */
- function resolveForwardRef(type) {
- if (lang_1.isFunction(type) && type.hasOwnProperty('__forward_ref__') &&
- type.__forward_ref__ === forwardRef) {
- return type();
- }
- else {
- return type;
- }
- }
- exports.resolveForwardRef = resolveForwardRef;
- /***/ },
- /* 11 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var provider_1 = __webpack_require__(13);
- var exceptions_1 = __webpack_require__(21);
- var lang_1 = __webpack_require__(5);
- var key_1 = __webpack_require__(19);
- var metadata_1 = __webpack_require__(7);
- // Threshold for the dynamic version
- var _MAX_CONSTRUCTION_COUNTER = 10;
- exports.UNDEFINED = lang_1.CONST_EXPR(new Object());
- /**
- * Visibility of a {@link Provider}.
- */
- (function (Visibility) {
- /**
- * A `Public` {@link Provider} is only visible to regular (as opposed to host) child injectors.
- */
- Visibility[Visibility["Public"] = 0] = "Public";
- /**
- * A `Private` {@link Provider} is only visible to host (as opposed to regular) child injectors.
- */
- Visibility[Visibility["Private"] = 1] = "Private";
- /**
- * A `PublicAndPrivate` {@link Provider} is visible to both host and regular child injectors.
- */
- Visibility[Visibility["PublicAndPrivate"] = 2] = "PublicAndPrivate";
- })(exports.Visibility || (exports.Visibility = {}));
- var Visibility = exports.Visibility;
- function canSee(src, dst) {
- return (src === dst) ||
- (dst === Visibility.PublicAndPrivate || src === Visibility.PublicAndPrivate);
- }
- var ProtoInjectorInlineStrategy = (function () {
- function ProtoInjectorInlineStrategy(protoEI, bwv) {
- this.provider0 = null;
- this.provider1 = null;
- this.provider2 = null;
- this.provider3 = null;
- this.provider4 = null;
- this.provider5 = null;
- this.provider6 = null;
- this.provider7 = null;
- this.provider8 = null;
- this.provider9 = null;
- this.keyId0 = null;
- this.keyId1 = null;
- this.keyId2 = null;
- this.keyId3 = null;
- this.keyId4 = null;
- this.keyId5 = null;
- this.keyId6 = null;
- this.keyId7 = null;
- this.keyId8 = null;
- this.keyId9 = null;
- this.visibility0 = null;
- this.visibility1 = null;
- this.visibility2 = null;
- this.visibility3 = null;
- this.visibility4 = null;
- this.visibility5 = null;
- this.visibility6 = null;
- this.visibility7 = null;
- this.visibility8 = null;
- this.visibility9 = null;
- var length = bwv.length;
- if (length > 0) {
- this.provider0 = bwv[0].provider;
- this.keyId0 = bwv[0].getKeyId();
- this.visibility0 = bwv[0].visibility;
- }
- if (length > 1) {
- this.provider1 = bwv[1].provider;
- this.keyId1 = bwv[1].getKeyId();
- this.visibility1 = bwv[1].visibility;
- }
- if (length > 2) {
- this.provider2 = bwv[2].provider;
- this.keyId2 = bwv[2].getKeyId();
- this.visibility2 = bwv[2].visibility;
- }
- if (length > 3) {
- this.provider3 = bwv[3].provider;
- this.keyId3 = bwv[3].getKeyId();
- this.visibility3 = bwv[3].visibility;
- }
- if (length > 4) {
- this.provider4 = bwv[4].provider;
- this.keyId4 = bwv[4].getKeyId();
- this.visibility4 = bwv[4].visibility;
- }
- if (length > 5) {
- this.provider5 = bwv[5].provider;
- this.keyId5 = bwv[5].getKeyId();
- this.visibility5 = bwv[5].visibility;
- }
- if (length > 6) {
- this.provider6 = bwv[6].provider;
- this.keyId6 = bwv[6].getKeyId();
- this.visibility6 = bwv[6].visibility;
- }
- if (length > 7) {
- this.provider7 = bwv[7].provider;
- this.keyId7 = bwv[7].getKeyId();
- this.visibility7 = bwv[7].visibility;
- }
- if (length > 8) {
- this.provider8 = bwv[8].provider;
- this.keyId8 = bwv[8].getKeyId();
- this.visibility8 = bwv[8].visibility;
- }
- if (length > 9) {
- this.provider9 = bwv[9].provider;
- this.keyId9 = bwv[9].getKeyId();
- this.visibility9 = bwv[9].visibility;
- }
- }
- ProtoInjectorInlineStrategy.prototype.getProviderAtIndex = function (index) {
- if (index == 0)
- return this.provider0;
- if (index == 1)
- return this.provider1;
- if (index == 2)
- return this.provider2;
- if (index == 3)
- return this.provider3;
- if (index == 4)
- return this.provider4;
- if (index == 5)
- return this.provider5;
- if (index == 6)
- return this.provider6;
- if (index == 7)
- return this.provider7;
- if (index == 8)
- return this.provider8;
- if (index == 9)
- return this.provider9;
- throw new exceptions_1.OutOfBoundsError(index);
- };
- ProtoInjectorInlineStrategy.prototype.createInjectorStrategy = function (injector) {
- return new InjectorInlineStrategy(injector, this);
- };
- return ProtoInjectorInlineStrategy;
- })();
- exports.ProtoInjectorInlineStrategy = ProtoInjectorInlineStrategy;
- var ProtoInjectorDynamicStrategy = (function () {
- function ProtoInjectorDynamicStrategy(protoInj, bwv) {
- var len = bwv.length;
- this.providers = collection_1.ListWrapper.createFixedSize(len);
- this.keyIds = collection_1.ListWrapper.createFixedSize(len);
- this.visibilities = collection_1.ListWrapper.createFixedSize(len);
- for (var i = 0; i < len; i++) {
- this.providers[i] = bwv[i].provider;
- this.keyIds[i] = bwv[i].getKeyId();
- this.visibilities[i] = bwv[i].visibility;
- }
- }
- ProtoInjectorDynamicStrategy.prototype.getProviderAtIndex = function (index) {
- if (index < 0 || index >= this.providers.length) {
- throw new exceptions_1.OutOfBoundsError(index);
- }
- return this.providers[index];
- };
- ProtoInjectorDynamicStrategy.prototype.createInjectorStrategy = function (ei) {
- return new InjectorDynamicStrategy(this, ei);
- };
- return ProtoInjectorDynamicStrategy;
- })();
- exports.ProtoInjectorDynamicStrategy = ProtoInjectorDynamicStrategy;
- var ProtoInjector = (function () {
- function ProtoInjector(bwv) {
- this.numberOfProviders = bwv.length;
- this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ?
- new ProtoInjectorDynamicStrategy(this, bwv) :
- new ProtoInjectorInlineStrategy(this, bwv);
- }
- ProtoInjector.prototype.getProviderAtIndex = function (index) { return this._strategy.getProviderAtIndex(index); };
- return ProtoInjector;
- })();
- exports.ProtoInjector = ProtoInjector;
- var InjectorInlineStrategy = (function () {
- function InjectorInlineStrategy(injector, protoStrategy) {
- this.injector = injector;
- this.protoStrategy = protoStrategy;
- this.obj0 = exports.UNDEFINED;
- this.obj1 = exports.UNDEFINED;
- this.obj2 = exports.UNDEFINED;
- this.obj3 = exports.UNDEFINED;
- this.obj4 = exports.UNDEFINED;
- this.obj5 = exports.UNDEFINED;
- this.obj6 = exports.UNDEFINED;
- this.obj7 = exports.UNDEFINED;
- this.obj8 = exports.UNDEFINED;
- this.obj9 = exports.UNDEFINED;
- }
- InjectorInlineStrategy.prototype.resetConstructionCounter = function () { this.injector._constructionCounter = 0; };
- InjectorInlineStrategy.prototype.instantiateProvider = function (provider, visibility) {
- return this.injector._new(provider, visibility);
- };
- InjectorInlineStrategy.prototype.attach = function (parent, isHost) {
- var inj = this.injector;
- inj._parent = parent;
- inj._isHost = isHost;
- };
- InjectorInlineStrategy.prototype.getObjByKeyId = function (keyId, visibility) {
- var p = this.protoStrategy;
- var inj = this.injector;
- if (p.keyId0 === keyId && canSee(p.visibility0, visibility)) {
- if (this.obj0 === exports.UNDEFINED) {
- this.obj0 = inj._new(p.provider0, p.visibility0);
- }
- return this.obj0;
- }
- if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) {
- if (this.obj1 === exports.UNDEFINED) {
- this.obj1 = inj._new(p.provider1, p.visibility1);
- }
- return this.obj1;
- }
- if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) {
- if (this.obj2 === exports.UNDEFINED) {
- this.obj2 = inj._new(p.provider2, p.visibility2);
- }
- return this.obj2;
- }
- if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) {
- if (this.obj3 === exports.UNDEFINED) {
- this.obj3 = inj._new(p.provider3, p.visibility3);
- }
- return this.obj3;
- }
- if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) {
- if (this.obj4 === exports.UNDEFINED) {
- this.obj4 = inj._new(p.provider4, p.visibility4);
- }
- return this.obj4;
- }
- if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) {
- if (this.obj5 === exports.UNDEFINED) {
- this.obj5 = inj._new(p.provider5, p.visibility5);
- }
- return this.obj5;
- }
- if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) {
- if (this.obj6 === exports.UNDEFINED) {
- this.obj6 = inj._new(p.provider6, p.visibility6);
- }
- return this.obj6;
- }
- if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) {
- if (this.obj7 === exports.UNDEFINED) {
- this.obj7 = inj._new(p.provider7, p.visibility7);
- }
- return this.obj7;
- }
- if (p.keyId8 === keyId && canSee(p.visibility8, visibility)) {
- if (this.obj8 === exports.UNDEFINED) {
- this.obj8 = inj._new(p.provider8, p.visibility8);
- }
- return this.obj8;
- }
- if (p.keyId9 === keyId && canSee(p.visibility9, visibility)) {
- if (this.obj9 === exports.UNDEFINED) {
- this.obj9 = inj._new(p.provider9, p.visibility9);
- }
- return this.obj9;
- }
- return exports.UNDEFINED;
- };
- InjectorInlineStrategy.prototype.getObjAtIndex = function (index) {
- if (index == 0)
- return this.obj0;
- if (index == 1)
- return this.obj1;
- if (index == 2)
- return this.obj2;
- if (index == 3)
- return this.obj3;
- if (index == 4)
- return this.obj4;
- if (index == 5)
- return this.obj5;
- if (index == 6)
- return this.obj6;
- if (index == 7)
- return this.obj7;
- if (index == 8)
- return this.obj8;
- if (index == 9)
- return this.obj9;
- throw new exceptions_1.OutOfBoundsError(index);
- };
- InjectorInlineStrategy.prototype.getMaxNumberOfObjects = function () { return _MAX_CONSTRUCTION_COUNTER; };
- return InjectorInlineStrategy;
- })();
- exports.InjectorInlineStrategy = InjectorInlineStrategy;
- var InjectorDynamicStrategy = (function () {
- function InjectorDynamicStrategy(protoStrategy, injector) {
- this.protoStrategy = protoStrategy;
- this.injector = injector;
- this.objs = collection_1.ListWrapper.createFixedSize(protoStrategy.providers.length);
- collection_1.ListWrapper.fill(this.objs, exports.UNDEFINED);
- }
- InjectorDynamicStrategy.prototype.resetConstructionCounter = function () { this.injector._constructionCounter = 0; };
- InjectorDynamicStrategy.prototype.instantiateProvider = function (provider, visibility) {
- return this.injector._new(provider, visibility);
- };
- InjectorDynamicStrategy.prototype.attach = function (parent, isHost) {
- var inj = this.injector;
- inj._parent = parent;
- inj._isHost = isHost;
- };
- InjectorDynamicStrategy.prototype.getObjByKeyId = function (keyId, visibility) {
- var p = this.protoStrategy;
- for (var i = 0; i < p.keyIds.length; i++) {
- if (p.keyIds[i] === keyId && canSee(p.visibilities[i], visibility)) {
- if (this.objs[i] === exports.UNDEFINED) {
- this.objs[i] = this.injector._new(p.providers[i], p.visibilities[i]);
- }
- return this.objs[i];
- }
- }
- return exports.UNDEFINED;
- };
- InjectorDynamicStrategy.prototype.getObjAtIndex = function (index) {
- if (index < 0 || index >= this.objs.length) {
- throw new exceptions_1.OutOfBoundsError(index);
- }
- return this.objs[index];
- };
- InjectorDynamicStrategy.prototype.getMaxNumberOfObjects = function () { return this.objs.length; };
- return InjectorDynamicStrategy;
- })();
- exports.InjectorDynamicStrategy = InjectorDynamicStrategy;
- var ProviderWithVisibility = (function () {
- function ProviderWithVisibility(provider, visibility) {
- this.provider = provider;
- this.visibility = visibility;
- }
- ;
- ProviderWithVisibility.prototype.getKeyId = function () { return this.provider.key.id; };
- return ProviderWithVisibility;
- })();
- exports.ProviderWithVisibility = ProviderWithVisibility;
- /**
- * A dependency injection container used for instantiating objects and resolving dependencies.
- *
- * An `Injector` is a replacement for a `new` operator, which can automatically resolve the
- * constructor dependencies.
- *
- * In typical use, application code asks for the dependencies in the constructor and they are
- * resolved by the `Injector`.
- *
- * ### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
- *
- * The following example creates an `Injector` configured to create `Engine` and `Car`.
- *
- * ```typescript
- * @Injectable()
- * class Engine {
- * }
- *
- * @Injectable()
- * class Car {
- * constructor(public engine:Engine) {}
- * }
- *
- * var injector = Injector.resolveAndCreate([Car, Engine]);
- * var car = injector.get(Car);
- * expect(car instanceof Car).toBe(true);
- * expect(car.engine instanceof Engine).toBe(true);
- * ```
- *
- * Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
- * resolve all of the object's dependencies automatically.
- */
- var Injector = (function () {
- /**
- * Private
- */
- function Injector(_proto /* ProtoInjector */, _parent, _depProvider, _debugContext) {
- if (_parent === void 0) { _parent = null; }
- if (_depProvider === void 0) { _depProvider = null; }
- if (_debugContext === void 0) { _debugContext = null; }
- this._depProvider = _depProvider;
- this._debugContext = _debugContext;
- /** @internal */
- this._isHost = false;
- /** @internal */
- this._constructionCounter = 0;
- this._proto = _proto;
- this._parent = _parent;
- this._strategy = _proto._strategy.createInjectorStrategy(this);
- }
- /**
- * Turns an array of provider definitions into an array of resolved providers.
- *
- * A resolution is a process of flattening multiple nested arrays and converting individual
- * providers into an array of {@link ResolvedProvider}s.
- *
- * ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
- *
- * ```typescript
- * @Injectable()
- * class Engine {
- * }
- *
- * @Injectable()
- * class Car {
- * constructor(public engine:Engine) {}
- * }
- *
- * var providers = Injector.resolve([Car, [[Engine]]]);
- *
- * expect(providers.length).toEqual(2);
- *
- * expect(providers[0] instanceof ResolvedProvider).toBe(true);
- * expect(providers[0].key.displayName).toBe("Car");
- * expect(providers[0].dependencies.length).toEqual(1);
- * expect(providers[0].factory).toBeDefined();
- *
- * expect(providers[1].key.displayName).toBe("Engine");
- * });
- * ```
- *
- * See {@link Injector#fromResolvedProviders} for more info.
- */
- Injector.resolve = function (providers) {
- return provider_1.resolveProviders(providers);
- };
- /**
- * Resolves an array of providers and creates an injector from those providers.
- *
- * The passed-in providers can be an array of `Type`, {@link Provider},
- * or a recursive array of more providers.
- *
- * ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
- *
- * ```typescript
- * @Injectable()
- * class Engine {
- * }
- *
- * @Injectable()
- * class Car {
- * constructor(public engine:Engine) {}
- * }
- *
- * var injector = Injector.resolveAndCreate([Car, Engine]);
- * expect(injector.get(Car) instanceof Car).toBe(true);
- * ```
- *
- * This function is slower than the corresponding `fromResolvedProviders`
- * because it needs to resolve the passed-in providers first.
- * See {@link Injector#resolve} and {@link Injector#fromResolvedProviders}.
- */
- Injector.resolveAndCreate = function (providers) {
- var resolvedProviders = Injector.resolve(providers);
- return Injector.fromResolvedProviders(resolvedProviders);
- };
- /**
- * Creates an injector from previously resolved providers.
- *
- * This API is the recommended way to construct injectors in performance-sensitive parts.
- *
- * ### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
- *
- * ```typescript
- * @Injectable()
- * class Engine {
- * }
- *
- * @Injectable()
- * class Car {
- * constructor(public engine:Engine) {}
- * }
- *
- * var providers = Injector.resolve([Car, Engine]);
- * var injector = Injector.fromResolvedProviders(providers);
- * expect(injector.get(Car) instanceof Car).toBe(true);
- * ```
- */
- Injector.fromResolvedProviders = function (providers) {
- var bd = providers.map(function (b) { return new ProviderWithVisibility(b, Visibility.Public); });
- var proto = new ProtoInjector(bd);
- return new Injector(proto, null, null);
- };
- /**
- * @deprecated
- */
- Injector.fromResolvedBindings = function (providers) {
- return Injector.fromResolvedProviders(providers);
- };
- /**
- * @internal
- */
- Injector.prototype.debugContext = function () { return this._debugContext(); };
- /**
- * Retrieves an instance from the injector based on the provided token.
- * Throws {@link NoProviderError} if not found.
- *
- * ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview))
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * provide("validToken", {useValue: "Value"})
- * ]);
- * expect(injector.get("validToken")).toEqual("Value");
- * expect(() => injector.get("invalidToken")).toThrowError();
- * ```
- *
- * `Injector` returns itself when given `Injector` as a token.
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([]);
- * expect(injector.get(Injector)).toBe(injector);
- * ```
- */
- Injector.prototype.get = function (token) {
- return this._getByKey(key_1.Key.get(token), null, null, false, Visibility.PublicAndPrivate);
- };
- /**
- * Retrieves an instance from the injector based on the provided token.
- * Returns null if not found.
- *
- * ### Example ([live demo](http://plnkr.co/edit/tpEbEy?p=preview))
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * provide("validToken", {useValue: "Value"})
- * ]);
- * expect(injector.getOptional("validToken")).toEqual("Value");
- * expect(injector.getOptional("invalidToken")).toBe(null);
- * ```
- *
- * `Injector` returns itself when given `Injector` as a token.
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([]);
- * expect(injector.getOptional(Injector)).toBe(injector);
- * ```
- */
- Injector.prototype.getOptional = function (token) {
- return this._getByKey(key_1.Key.get(token), null, null, true, Visibility.PublicAndPrivate);
- };
- /**
- * @internal
- */
- Injector.prototype.getAt = function (index) { return this._strategy.getObjAtIndex(index); };
- Object.defineProperty(Injector.prototype, "parent", {
- /**
- * Parent of this injector.
- *
- * <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
- * -->
- *
- * ### Example ([live demo](http://plnkr.co/edit/eosMGo?p=preview))
- *
- * ```typescript
- * var parent = Injector.resolveAndCreate([]);
- * var child = parent.resolveAndCreateChild([]);
- * expect(child.parent).toBe(parent);
- * ```
- */
- get: function () { return this._parent; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Injector.prototype, "internalStrategy", {
- /**
- * @internal
- * Internal. Do not use.
- * We return `any` not to export the InjectorStrategy type.
- */
- get: function () { return this._strategy; },
- enumerable: true,
- configurable: true
- });
- /**
- * Resolves an array of providers and creates a child injector from those providers.
- *
- * <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
- * -->
- *
- * The passed-in providers can be an array of `Type`, {@link Provider},
- * or a recursive array of more providers.
- *
- * ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
- *
- * ```typescript
- * class ParentProvider {}
- * class ChildProvider {}
- *
- * var parent = Injector.resolveAndCreate([ParentProvider]);
- * var child = parent.resolveAndCreateChild([ChildProvider]);
- *
- * expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
- * expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
- * expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
- * ```
- *
- * This function is slower than the corresponding `createChildFromResolved`
- * because it needs to resolve the passed-in providers first.
- * See {@link Injector#resolve} and {@link Injector#createChildFromResolved}.
- */
- Injector.prototype.resolveAndCreateChild = function (providers) {
- var resolvedProviders = Injector.resolve(providers);
- return this.createChildFromResolved(resolvedProviders);
- };
- /**
- * Creates a child injector from previously resolved providers.
- *
- * <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
- * -->
- *
- * This API is the recommended way to construct injectors in performance-sensitive parts.
- *
- * ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
- *
- * ```typescript
- * class ParentProvider {}
- * class ChildProvider {}
- *
- * var parentProviders = Injector.resolve([ParentProvider]);
- * var childProviders = Injector.resolve([ChildProvider]);
- *
- * var parent = Injector.fromResolvedProviders(parentProviders);
- * var child = parent.createChildFromResolved(childProviders);
- *
- * expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
- * expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
- * expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
- * ```
- */
- Injector.prototype.createChildFromResolved = function (providers) {
- var bd = providers.map(function (b) { return new ProviderWithVisibility(b, Visibility.Public); });
- var proto = new ProtoInjector(bd);
- var inj = new Injector(proto, null, null);
- inj._parent = this;
- return inj;
- };
- /**
- * Resolves a provider and instantiates an object in the context of the injector.
- *
- * The created object does not get cached by the injector.
- *
- * ### Example ([live demo](http://plnkr.co/edit/yvVXoB?p=preview))
- *
- * ```typescript
- * @Injectable()
- * class Engine {
- * }
- *
- * @Injectable()
- * class Car {
- * constructor(public engine:Engine) {}
- * }
- *
- * var injector = Injector.resolveAndCreate([Engine]);
- *
- * var car = injector.resolveAndInstantiate(Car);
- * expect(car.engine).toBe(injector.get(Engine));
- * expect(car).not.toBe(injector.resolveAndInstantiate(Car));
- * ```
- */
- Injector.prototype.resolveAndInstantiate = function (provider) {
- return this.instantiateResolved(Injector.resolve([provider])[0]);
- };
- /**
- * Instantiates an object using a resolved provider in the context of the injector.
- *
- * The created object does not get cached by the injector.
- *
- * ### Example ([live demo](http://plnkr.co/edit/ptCImQ?p=preview))
- *
- * ```typescript
- * @Injectable()
- * class Engine {
- * }
- *
- * @Injectable()
- * class Car {
- * constructor(public engine:Engine) {}
- * }
- *
- * var injector = Injector.resolveAndCreate([Engine]);
- * var carProvider = Injector.resolve([Car])[0];
- * var car = injector.instantiateResolved(carProvider);
- * expect(car.engine).toBe(injector.get(Engine));
- * expect(car).not.toBe(injector.instantiateResolved(carProvider));
- * ```
- */
- Injector.prototype.instantiateResolved = function (provider) {
- return this._instantiateProvider(provider, Visibility.PublicAndPrivate);
- };
- /** @internal */
- Injector.prototype._new = function (provider, visibility) {
- if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) {
- throw new exceptions_1.CyclicDependencyError(this, provider.key);
- }
- return this._instantiateProvider(provider, visibility);
- };
- Injector.prototype._instantiateProvider = function (provider, visibility) {
- if (provider.multiProvider) {
- var res = collection_1.ListWrapper.createFixedSize(provider.resolvedFactories.length);
- for (var i = 0; i < provider.resolvedFactories.length; ++i) {
- res[i] = this._instantiate(provider, provider.resolvedFactories[i], visibility);
- }
- return res;
- }
- else {
- return this._instantiate(provider, provider.resolvedFactories[0], visibility);
- }
- };
- Injector.prototype._instantiate = function (provider, resolvedFactory, visibility) {
- var factory = resolvedFactory.factory;
- var deps = resolvedFactory.dependencies;
- var length = deps.length;
- var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19;
- try {
- d0 = length > 0 ? this._getByDependency(provider, deps[0], visibility) : null;
- d1 = length > 1 ? this._getByDependency(provider, deps[1], visibility) : null;
- d2 = length > 2 ? this._getByDependency(provider, deps[2], visibility) : null;
- d3 = length > 3 ? this._getByDependency(provider, deps[3], visibility) : null;
- d4 = length > 4 ? this._getByDependency(provider, deps[4], visibility) : null;
- d5 = length > 5 ? this._getByDependency(provider, deps[5], visibility) : null;
- d6 = length > 6 ? this._getByDependency(provider, deps[6], visibility) : null;
- d7 = length > 7 ? this._getByDependency(provider, deps[7], visibility) : null;
- d8 = length > 8 ? this._getByDependency(provider, deps[8], visibility) : null;
- d9 = length > 9 ? this._getByDependency(provider, deps[9], visibility) : null;
- d10 = length > 10 ? this._getByDependency(provider, deps[10], visibility) : null;
- d11 = length > 11 ? this._getByDependency(provider, deps[11], visibility) : null;
- d12 = length > 12 ? this._getByDependency(provider, deps[12], visibility) : null;
- d13 = length > 13 ? this._getByDependency(provider, deps[13], visibility) : null;
- d14 = length > 14 ? this._getByDependency(provider, deps[14], visibility) : null;
- d15 = length > 15 ? this._getByDependency(provider, deps[15], visibility) : null;
- d16 = length > 16 ? this._getByDependency(provider, deps[16], visibility) : null;
- d17 = length > 17 ? this._getByDependency(provider, deps[17], visibility) : null;
- d18 = length > 18 ? this._getByDependency(provider, deps[18], visibility) : null;
- d19 = length > 19 ? this._getByDependency(provider, deps[19], visibility) : null;
- }
- catch (e) {
- if (e instanceof exceptions_1.AbstractProviderError || e instanceof exceptions_1.InstantiationError) {
- e.addKey(this, provider.key);
- }
- throw e;
- }
- var obj;
- try {
- switch (length) {
- case 0:
- obj = factory();
- break;
- case 1:
- obj = factory(d0);
- break;
- case 2:
- obj = factory(d0, d1);
- break;
- case 3:
- obj = factory(d0, d1, d2);
- break;
- case 4:
- obj = factory(d0, d1, d2, d3);
- break;
- case 5:
- obj = factory(d0, d1, d2, d3, d4);
- break;
- case 6:
- obj = factory(d0, d1, d2, d3, d4, d5);
- break;
- case 7:
- obj = factory(d0, d1, d2, d3, d4, d5, d6);
- break;
- case 8:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7);
- break;
- case 9:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8);
- break;
- case 10:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9);
- break;
- case 11:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10);
- break;
- case 12:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11);
- break;
- case 13:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12);
- break;
- case 14:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13);
- break;
- case 15:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14);
- break;
- case 16:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15);
- break;
- case 17:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16);
- break;
- case 18:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17);
- break;
- case 19:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18);
- break;
- case 20:
- obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19);
- break;
- }
- }
- catch (e) {
- throw new exceptions_1.InstantiationError(this, e, e.stack, provider.key);
- }
- return obj;
- };
- Injector.prototype._getByDependency = function (provider, dep, providerVisibility) {
- var special = lang_1.isPresent(this._depProvider) ?
- this._depProvider.getDependency(this, provider, dep) :
- exports.UNDEFINED;
- if (special !== exports.UNDEFINED) {
- return special;
- }
- else {
- return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility, dep.optional, providerVisibility);
- }
- };
- Injector.prototype._getByKey = function (key, lowerBoundVisibility, upperBoundVisibility, optional, providerVisibility) {
- if (key === INJECTOR_KEY) {
- return this;
- }
- if (upperBoundVisibility instanceof metadata_1.SelfMetadata) {
- return this._getByKeySelf(key, optional, providerVisibility);
- }
- else if (upperBoundVisibility instanceof metadata_1.HostMetadata) {
- return this._getByKeyHost(key, optional, providerVisibility, lowerBoundVisibility);
- }
- else {
- return this._getByKeyDefault(key, optional, providerVisibility, lowerBoundVisibility);
- }
- };
- /** @internal */
- Injector.prototype._throwOrNull = function (key, optional) {
- if (optional) {
- return null;
- }
- else {
- throw new exceptions_1.NoProviderError(this, key);
- }
- };
- /** @internal */
- Injector.prototype._getByKeySelf = function (key, optional, providerVisibility) {
- var obj = this._strategy.getObjByKeyId(key.id, providerVisibility);
- return (obj !== exports.UNDEFINED) ? obj : this._throwOrNull(key, optional);
- };
- /** @internal */
- Injector.prototype._getByKeyHost = function (key, optional, providerVisibility, lowerBoundVisibility) {
- var inj = this;
- if (lowerBoundVisibility instanceof metadata_1.SkipSelfMetadata) {
- if (inj._isHost) {
- return this._getPrivateDependency(key, optional, inj);
- }
- else {
- inj = inj._parent;
- }
- }
- while (inj != null) {
- var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility);
- if (obj !== exports.UNDEFINED)
- return obj;
- if (lang_1.isPresent(inj._parent) && inj._isHost) {
- return this._getPrivateDependency(key, optional, inj);
- }
- else {
- inj = inj._parent;
- }
- }
- return this._throwOrNull(key, optional);
- };
- /** @internal */
- Injector.prototype._getPrivateDependency = function (key, optional, inj) {
- var obj = inj._parent._strategy.getObjByKeyId(key.id, Visibility.Private);
- return (obj !== exports.UNDEFINED) ? obj : this._throwOrNull(key, optional);
- };
- /** @internal */
- Injector.prototype._getByKeyDefault = function (key, optional, providerVisibility, lowerBoundVisibility) {
- var inj = this;
- if (lowerBoundVisibility instanceof metadata_1.SkipSelfMetadata) {
- providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
- inj = inj._parent;
- }
- while (inj != null) {
- var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility);
- if (obj !== exports.UNDEFINED)
- return obj;
- providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public;
- inj = inj._parent;
- }
- return this._throwOrNull(key, optional);
- };
- Object.defineProperty(Injector.prototype, "displayName", {
- get: function () {
- return "Injector(providers: [" + _mapProviders(this, function (b) { return (" \"" + b.key.displayName + "\" "); }).join(", ") + "])";
- },
- enumerable: true,
- configurable: true
- });
- Injector.prototype.toString = function () { return this.displayName; };
- return Injector;
- })();
- exports.Injector = Injector;
- var INJECTOR_KEY = key_1.Key.get(Injector);
- function _mapProviders(injector, fn) {
- var res = [];
- for (var i = 0; i < injector._proto.numberOfProviders; ++i) {
- res.push(fn(injector._proto.getProviderAtIndex(i)));
- }
- return res;
- }
- /***/ },
- /* 12 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- exports.Map = lang_1.global.Map;
- exports.Set = lang_1.global.Set;
- // Safari and Internet Explorer do not support the iterable parameter to the
- // Map constructor. We work around that by manually adding the items.
- var createMapFromPairs = (function () {
- try {
- if (new exports.Map([[1, 2]]).size === 1) {
- return function createMapFromPairs(pairs) { return new exports.Map(pairs); };
- }
- }
- catch (e) {
- }
- return function createMapAndPopulateFromPairs(pairs) {
- var map = new exports.Map();
- for (var i = 0; i < pairs.length; i++) {
- var pair = pairs[i];
- map.set(pair[0], pair[1]);
- }
- return map;
- };
- })();
- var createMapFromMap = (function () {
- try {
- if (new exports.Map(new exports.Map())) {
- return function createMapFromMap(m) { return new exports.Map(m); };
- }
- }
- catch (e) {
- }
- return function createMapAndPopulateFromMap(m) {
- var map = new exports.Map();
- m.forEach(function (v, k) { map.set(k, v); });
- return map;
- };
- })();
- var _clearValues = (function () {
- if ((new exports.Map()).keys().next) {
- return function _clearValues(m) {
- var keyIterator = m.keys();
- var k;
- while (!((k = keyIterator.next()).done)) {
- m.set(k.value, null);
- }
- };
- }
- else {
- return function _clearValuesWithForeEach(m) {
- m.forEach(function (v, k) { m.set(k, null); });
- };
- }
- })();
- // Safari doesn't implement MapIterator.next(), which is used is Traceur's polyfill of Array.from
- // TODO(mlaval): remove the work around once we have a working polyfill of Array.from
- var _arrayFromMap = (function () {
- try {
- if ((new exports.Map()).values().next) {
- return function createArrayFromMap(m, getValues) {
- return getValues ? Array.from(m.values()) : Array.from(m.keys());
- };
- }
- }
- catch (e) {
- }
- return function createArrayFromMapWithForeach(m, getValues) {
- var res = ListWrapper.createFixedSize(m.size), i = 0;
- m.forEach(function (v, k) {
- res[i] = getValues ? v : k;
- i++;
- });
- return res;
- };
- })();
- var MapWrapper = (function () {
- function MapWrapper() {
- }
- MapWrapper.clone = function (m) { return createMapFromMap(m); };
- MapWrapper.createFromStringMap = function (stringMap) {
- var result = new exports.Map();
- for (var prop in stringMap) {
- result.set(prop, stringMap[prop]);
- }
- return result;
- };
- MapWrapper.toStringMap = function (m) {
- var r = {};
- m.forEach(function (v, k) { return r[k] = v; });
- return r;
- };
- MapWrapper.createFromPairs = function (pairs) { return createMapFromPairs(pairs); };
- MapWrapper.clearValues = function (m) { _clearValues(m); };
- MapWrapper.iterable = function (m) { return m; };
- MapWrapper.keys = function (m) { return _arrayFromMap(m, false); };
- MapWrapper.values = function (m) { return _arrayFromMap(m, true); };
- return MapWrapper;
- })();
- exports.MapWrapper = MapWrapper;
- /**
- * Wraps Javascript Objects
- */
- var StringMapWrapper = (function () {
- function StringMapWrapper() {
- }
- StringMapWrapper.create = function () {
- // Note: We are not using Object.create(null) here due to
- // performance!
- // http://jsperf.com/ng2-object-create-null
- return {};
- };
- StringMapWrapper.contains = function (map, key) {
- return map.hasOwnProperty(key);
- };
- StringMapWrapper.get = function (map, key) {
- return map.hasOwnProperty(key) ? map[key] : undefined;
- };
- StringMapWrapper.set = function (map, key, value) { map[key] = value; };
- StringMapWrapper.keys = function (map) { return Object.keys(map); };
- StringMapWrapper.isEmpty = function (map) {
- for (var prop in map) {
- return false;
- }
- return true;
- };
- StringMapWrapper.delete = function (map, key) { delete map[key]; };
- StringMapWrapper.forEach = function (map, callback) {
- for (var prop in map) {
- if (map.hasOwnProperty(prop)) {
- callback(map[prop], prop);
- }
- }
- };
- StringMapWrapper.merge = function (m1, m2) {
- var m = {};
- for (var attr in m1) {
- if (m1.hasOwnProperty(attr)) {
- m[attr] = m1[attr];
- }
- }
- for (var attr in m2) {
- if (m2.hasOwnProperty(attr)) {
- m[attr] = m2[attr];
- }
- }
- return m;
- };
- StringMapWrapper.equals = function (m1, m2) {
- var k1 = Object.keys(m1);
- var k2 = Object.keys(m2);
- if (k1.length != k2.length) {
- return false;
- }
- var key;
- for (var i = 0; i < k1.length; i++) {
- key = k1[i];
- if (m1[key] !== m2[key]) {
- return false;
- }
- }
- return true;
- };
- return StringMapWrapper;
- })();
- exports.StringMapWrapper = StringMapWrapper;
- var ListWrapper = (function () {
- function ListWrapper() {
- }
- // JS has no way to express a statically fixed size list, but dart does so we
- // keep both methods.
- ListWrapper.createFixedSize = function (size) { return new Array(size); };
- ListWrapper.createGrowableSize = function (size) { return new Array(size); };
- ListWrapper.clone = function (array) { return array.slice(0); };
- ListWrapper.forEachWithIndex = function (array, fn) {
- for (var i = 0; i < array.length; i++) {
- fn(array[i], i);
- }
- };
- ListWrapper.first = function (array) {
- if (!array)
- return null;
- return array[0];
- };
- ListWrapper.last = function (array) {
- if (!array || array.length == 0)
- return null;
- return array[array.length - 1];
- };
- ListWrapper.indexOf = function (array, value, startIndex) {
- if (startIndex === void 0) { startIndex = 0; }
- return array.indexOf(value, startIndex);
- };
- ListWrapper.contains = function (list, el) { return list.indexOf(el) !== -1; };
- ListWrapper.reversed = function (array) {
- var a = ListWrapper.clone(array);
- return a.reverse();
- };
- ListWrapper.concat = function (a, b) { return a.concat(b); };
- ListWrapper.insert = function (list, index, value) { list.splice(index, 0, value); };
- ListWrapper.removeAt = function (list, index) {
- var res = list[index];
- list.splice(index, 1);
- return res;
- };
- ListWrapper.removeAll = function (list, items) {
- for (var i = 0; i < items.length; ++i) {
- var index = list.indexOf(items[i]);
- list.splice(index, 1);
- }
- };
- ListWrapper.remove = function (list, el) {
- var index = list.indexOf(el);
- if (index > -1) {
- list.splice(index, 1);
- return true;
- }
- return false;
- };
- ListWrapper.clear = function (list) { list.length = 0; };
- ListWrapper.isEmpty = function (list) { return list.length == 0; };
- ListWrapper.fill = function (list, value, start, end) {
- if (start === void 0) { start = 0; }
- if (end === void 0) { end = null; }
- list.fill(value, start, end === null ? list.length : end);
- };
- ListWrapper.equals = function (a, b) {
- if (a.length != b.length)
- return false;
- for (var i = 0; i < a.length; ++i) {
- if (a[i] !== b[i])
- return false;
- }
- return true;
- };
- ListWrapper.slice = function (l, from, to) {
- if (from === void 0) { from = 0; }
- if (to === void 0) { to = null; }
- return l.slice(from, to === null ? undefined : to);
- };
- ListWrapper.splice = function (l, from, length) { return l.splice(from, length); };
- ListWrapper.sort = function (l, compareFn) {
- if (lang_1.isPresent(compareFn)) {
- l.sort(compareFn);
- }
- else {
- l.sort();
- }
- };
- ListWrapper.toString = function (l) { return l.toString(); };
- ListWrapper.toJSON = function (l) { return JSON.stringify(l); };
- ListWrapper.maximum = function (list, predicate) {
- if (list.length == 0) {
- return null;
- }
- var solution = null;
- var maxValue = -Infinity;
- for (var index = 0; index < list.length; index++) {
- var candidate = list[index];
- if (lang_1.isBlank(candidate)) {
- continue;
- }
- var candidateValue = predicate(candidate);
- if (candidateValue > maxValue) {
- solution = candidate;
- maxValue = candidateValue;
- }
- }
- return solution;
- };
- return ListWrapper;
- })();
- exports.ListWrapper = ListWrapper;
- function isListLikeIterable(obj) {
- if (!lang_1.isJsObject(obj))
- return false;
- return lang_1.isArray(obj) ||
- (!(obj instanceof exports.Map) &&
- lang_1.getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
- }
- exports.isListLikeIterable = isListLikeIterable;
- function iterateListLike(obj, fn) {
- if (lang_1.isArray(obj)) {
- for (var i = 0; i < obj.length; i++) {
- fn(obj[i]);
- }
- }
- else {
- var iterator = obj[lang_1.getSymbolIterator()]();
- var item;
- while (!((item = iterator.next()).done)) {
- fn(item.value);
- }
- }
- }
- exports.iterateListLike = iterateListLike;
- // Safari and Internet Explorer do not support the iterable parameter to the
- // Set constructor. We work around that by manually adding the items.
- var createSetFromList = (function () {
- var test = new exports.Set([1, 2, 3]);
- if (test.size === 3) {
- return function createSetFromList(lst) { return new exports.Set(lst); };
- }
- else {
- return function createSetAndPopulateFromList(lst) {
- var res = new exports.Set(lst);
- if (res.size !== lst.length) {
- for (var i = 0; i < lst.length; i++) {
- res.add(lst[i]);
- }
- }
- return res;
- };
- }
- })();
- var SetWrapper = (function () {
- function SetWrapper() {
- }
- SetWrapper.createFromList = function (lst) { return createSetFromList(lst); };
- SetWrapper.has = function (s, key) { return s.has(key); };
- SetWrapper.delete = function (m, k) { m.delete(k); };
- return SetWrapper;
- })();
- exports.SetWrapper = SetWrapper;
- /***/ },
- /* 13 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var reflection_1 = __webpack_require__(16);
- var key_1 = __webpack_require__(19);
- var metadata_1 = __webpack_require__(7);
- var exceptions_2 = __webpack_require__(21);
- var forward_ref_1 = __webpack_require__(10);
- /**
- * `Dependency` is used by the framework to extend DI.
- * This is internal to Angular and should not be used directly.
- */
- var Dependency = (function () {
- function Dependency(key, optional, lowerBoundVisibility, upperBoundVisibility, properties) {
- this.key = key;
- this.optional = optional;
- this.lowerBoundVisibility = lowerBoundVisibility;
- this.upperBoundVisibility = upperBoundVisibility;
- this.properties = properties;
- }
- Dependency.fromKey = function (key) { return new Dependency(key, false, null, null, []); };
- return Dependency;
- })();
- exports.Dependency = Dependency;
- var _EMPTY_LIST = lang_1.CONST_EXPR([]);
- /**
- * Describes how the {@link Injector} should instantiate a given token.
- *
- * See {@link provide}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/GNAyj6K6PfYg2NBzgwZ5?p%3Dpreview&p=preview))
- *
- * ```javascript
- * var injector = Injector.resolveAndCreate([
- * new Provider("message", { useValue: 'Hello' })
- * ]);
- *
- * expect(injector.get("message")).toEqual('Hello');
- * ```
- */
- var Provider = (function () {
- function Provider(token, _a) {
- var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
- this.token = token;
- this.useClass = useClass;
- this.useValue = useValue;
- this.useExisting = useExisting;
- this.useFactory = useFactory;
- this.dependencies = deps;
- this._multi = multi;
- }
- Object.defineProperty(Provider.prototype, "multi", {
- // TODO: Provide a full working example after alpha38 is released.
- /**
- * Creates multiple providers matching the same token (a multi-provider).
- *
- * Multi-providers are used for creating pluggable service, where the system comes
- * with some default providers, and the user can register additonal providers.
- * The combination of the default providers and the additional providers will be
- * used to drive the behavior of the system.
- *
- * ### Example
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * new Provider("Strings", { useValue: "String1", multi: true}),
- * new Provider("Strings", { useValue: "String2", multi: true})
- * ]);
- *
- * expect(injector.get("Strings")).toEqual(["String1", "String2"]);
- * ```
- *
- * Multi-providers and regular providers cannot be mixed. The following
- * will throw an exception:
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * new Provider("Strings", { useValue: "String1", multi: true }),
- * new Provider("Strings", { useValue: "String2"})
- * ]);
- * ```
- */
- get: function () { return lang_1.normalizeBool(this._multi); },
- enumerable: true,
- configurable: true
- });
- Provider = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object, Object])
- ], Provider);
- return Provider;
- })();
- exports.Provider = Provider;
- /**
- * See {@link Provider} instead.
- *
- * @deprecated
- */
- var Binding = (function (_super) {
- __extends(Binding, _super);
- function Binding(token, _a) {
- var toClass = _a.toClass, toValue = _a.toValue, toAlias = _a.toAlias, toFactory = _a.toFactory, deps = _a.deps, multi = _a.multi;
- _super.call(this, token, {
- useClass: toClass,
- useValue: toValue,
- useExisting: toAlias,
- useFactory: toFactory,
- deps: deps,
- multi: multi
- });
- }
- Object.defineProperty(Binding.prototype, "toClass", {
- /**
- * @deprecated
- */
- get: function () { return this.useClass; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Binding.prototype, "toAlias", {
- /**
- * @deprecated
- */
- get: function () { return this.useExisting; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Binding.prototype, "toFactory", {
- /**
- * @deprecated
- */
- get: function () { return this.useFactory; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Binding.prototype, "toValue", {
- /**
- * @deprecated
- */
- get: function () { return this.useValue; },
- enumerable: true,
- configurable: true
- });
- Binding = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object, Object])
- ], Binding);
- return Binding;
- })(Provider);
- exports.Binding = Binding;
- var ResolvedProvider_ = (function () {
- function ResolvedProvider_(key, resolvedFactories, multiProvider) {
- this.key = key;
- this.resolvedFactories = resolvedFactories;
- this.multiProvider = multiProvider;
- }
- Object.defineProperty(ResolvedProvider_.prototype, "resolvedFactory", {
- get: function () { return this.resolvedFactories[0]; },
- enumerable: true,
- configurable: true
- });
- return ResolvedProvider_;
- })();
- exports.ResolvedProvider_ = ResolvedProvider_;
- /**
- * An internal resolved representation of a factory function created by resolving {@link Provider}.
- */
- var ResolvedFactory = (function () {
- function ResolvedFactory(
- /**
- * Factory function which can return an instance of an object represented by a key.
- */
- factory,
- /**
- * Arguments (dependencies) to the `factory` function.
- */
- dependencies) {
- this.factory = factory;
- this.dependencies = dependencies;
- }
- return ResolvedFactory;
- })();
- exports.ResolvedFactory = ResolvedFactory;
- /**
- * Creates a {@link Provider}.
- *
- * To construct a {@link Provider}, bind a `token` to either a class, a value, a factory function,
- * or
- * to an existing `token`.
- * See {@link ProviderBuilder} for more details.
- *
- * The `token` is most commonly a class or {@link angular2/di/OpaqueToken}.
- *
- * @deprecated
- */
- function bind(token) {
- return new ProviderBuilder(token);
- }
- exports.bind = bind;
- /**
- * Creates a {@link Provider}.
- *
- * See {@link Provider} for more details.
- *
- * <!-- TODO: improve the docs -->
- */
- function provide(token, _a) {
- var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
- return new Provider(token, {
- useClass: useClass,
- useValue: useValue,
- useExisting: useExisting,
- useFactory: useFactory,
- deps: deps,
- multi: multi
- });
- }
- exports.provide = provide;
- /**
- * Helper class for the {@link bind} function.
- */
- var ProviderBuilder = (function () {
- function ProviderBuilder(token) {
- this.token = token;
- }
- /**
- * Binds a DI token to a class.
- *
- * ### Example ([live demo](http://plnkr.co/edit/ZpBCSYqv6e2ud5KXLdxQ?p=preview))
- *
- * Because `toAlias` and `toClass` are often confused, the example contains
- * both use cases for easy comparison.
- *
- * ```typescript
- * class Vehicle {}
- *
- * class Car extends Vehicle {}
- *
- * var injectorClass = Injector.resolveAndCreate([
- * Car,
- * provide(Vehicle, {useClass: Car})
- * ]);
- * var injectorAlias = Injector.resolveAndCreate([
- * Car,
- * provide(Vehicle, {useExisting: Car})
- * ]);
- *
- * expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
- * expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
- *
- * expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
- * expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
- * ```
- */
- ProviderBuilder.prototype.toClass = function (type) {
- if (!lang_1.isType(type)) {
- throw new exceptions_1.BaseException("Trying to create a class provider but \"" + lang_1.stringify(type) + "\" is not a class!");
- }
- return new Provider(this.token, { useClass: type });
- };
- /**
- * Binds a DI token to a value.
- *
- * ### Example ([live demo](http://plnkr.co/edit/G024PFHmDL0cJFgfZK8O?p=preview))
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * provide('message', {useValue: 'Hello'})
- * ]);
- *
- * expect(injector.get('message')).toEqual('Hello');
- * ```
- */
- ProviderBuilder.prototype.toValue = function (value) { return new Provider(this.token, { useValue: value }); };
- /**
- * Binds a DI token to an existing token.
- *
- * Angular will return the same instance as if the provided token was used. (This is
- * in contrast to `useClass` where a separate instance of `useClass` will be returned.)
- *
- * ### Example ([live demo](http://plnkr.co/edit/uBaoF2pN5cfc5AfZapNw?p=preview))
- *
- * Because `toAlias` and `toClass` are often confused, the example contains
- * both use cases for easy comparison.
- *
- * ```typescript
- * class Vehicle {}
- *
- * class Car extends Vehicle {}
- *
- * var injectorAlias = Injector.resolveAndCreate([
- * Car,
- * provide(Vehicle, {useExisting: Car})
- * ]);
- * var injectorClass = Injector.resolveAndCreate([
- * Car,
- * provide(Vehicle, {useClass: Car})
- * ]);
- *
- * expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
- * expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
- *
- * expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
- * expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
- * ```
- */
- ProviderBuilder.prototype.toAlias = function (aliasToken) {
- if (lang_1.isBlank(aliasToken)) {
- throw new exceptions_1.BaseException("Can not alias " + lang_1.stringify(this.token) + " to a blank value!");
- }
- return new Provider(this.token, { useExisting: aliasToken });
- };
- /**
- * Binds a DI token to a function which computes the value.
- *
- * ### Example ([live demo](http://plnkr.co/edit/OejNIfTT3zb1iBxaIYOb?p=preview))
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * provide(Number, {useFactory: () => { return 1+2; }}),
- * provide(String, {useFactory: (v) => { return "Value: " + v; }, deps: [Number]})
- * ]);
- *
- * expect(injector.get(Number)).toEqual(3);
- * expect(injector.get(String)).toEqual('Value: 3');
- * ```
- */
- ProviderBuilder.prototype.toFactory = function (factory, dependencies) {
- if (!lang_1.isFunction(factory)) {
- throw new exceptions_1.BaseException("Trying to create a factory provider but \"" + lang_1.stringify(factory) + "\" is not a function!");
- }
- return new Provider(this.token, { useFactory: factory, deps: dependencies });
- };
- return ProviderBuilder;
- })();
- exports.ProviderBuilder = ProviderBuilder;
- /**
- * Resolve a single provider.
- */
- function resolveFactory(provider) {
- var factoryFn;
- var resolvedDeps;
- if (lang_1.isPresent(provider.useClass)) {
- var useClass = forward_ref_1.resolveForwardRef(provider.useClass);
- factoryFn = reflection_1.reflector.factory(useClass);
- resolvedDeps = _dependenciesFor(useClass);
- }
- else if (lang_1.isPresent(provider.useExisting)) {
- factoryFn = function (aliasInstance) { return aliasInstance; };
- resolvedDeps = [Dependency.fromKey(key_1.Key.get(provider.useExisting))];
- }
- else if (lang_1.isPresent(provider.useFactory)) {
- factoryFn = provider.useFactory;
- resolvedDeps = _constructDependencies(provider.useFactory, provider.dependencies);
- }
- else {
- factoryFn = function () { return provider.useValue; };
- resolvedDeps = _EMPTY_LIST;
- }
- return new ResolvedFactory(factoryFn, resolvedDeps);
- }
- exports.resolveFactory = resolveFactory;
- /**
- * Converts the {@link Provider} into {@link ResolvedProvider}.
- *
- * {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
- * convenience provider syntax.
- */
- function resolveProvider(provider) {
- return new ResolvedProvider_(key_1.Key.get(provider.token), [resolveFactory(provider)], false);
- }
- exports.resolveProvider = resolveProvider;
- /**
- * Resolve a list of Providers.
- */
- function resolveProviders(providers) {
- var normalized = _createListOfProviders(_normalizeProviders(providers, new Map()));
- return normalized.map(function (b) {
- if (b instanceof _NormalizedProvider) {
- return new ResolvedProvider_(b.key, [b.resolvedFactory], false);
- }
- else {
- var arr = b;
- return new ResolvedProvider_(arr[0].key, arr.map(function (_) { return _.resolvedFactory; }), true);
- }
- });
- }
- exports.resolveProviders = resolveProviders;
- /**
- * The algorithm works as follows:
- *
- * [Provider] -> [_NormalizedProvider|[_NormalizedProvider]] -> [ResolvedProvider]
- *
- * _NormalizedProvider is essentially a resolved provider before it was grouped by key.
- */
- var _NormalizedProvider = (function () {
- function _NormalizedProvider(key, resolvedFactory) {
- this.key = key;
- this.resolvedFactory = resolvedFactory;
- }
- return _NormalizedProvider;
- })();
- function _createListOfProviders(flattenedProviders) {
- return collection_1.MapWrapper.values(flattenedProviders);
- }
- function _normalizeProviders(providers, res) {
- providers.forEach(function (b) {
- if (b instanceof lang_1.Type) {
- _normalizeProvider(provide(b, { useClass: b }), res);
- }
- else if (b instanceof Provider) {
- _normalizeProvider(b, res);
- }
- else if (b instanceof Array) {
- _normalizeProviders(b, res);
- }
- else if (b instanceof ProviderBuilder) {
- throw new exceptions_2.InvalidProviderError(b.token);
- }
- else {
- throw new exceptions_2.InvalidProviderError(b);
- }
- });
- return res;
- }
- function _normalizeProvider(b, res) {
- var key = key_1.Key.get(b.token);
- var factory = resolveFactory(b);
- var normalized = new _NormalizedProvider(key, factory);
- if (b.multi) {
- var existingProvider = res.get(key.id);
- if (existingProvider instanceof Array) {
- existingProvider.push(normalized);
- }
- else if (lang_1.isBlank(existingProvider)) {
- res.set(key.id, [normalized]);
- }
- else {
- throw new exceptions_2.MixingMultiProvidersWithRegularProvidersError(existingProvider, b);
- }
- }
- else {
- var existingProvider = res.get(key.id);
- if (existingProvider instanceof Array) {
- throw new exceptions_2.MixingMultiProvidersWithRegularProvidersError(existingProvider, b);
- }
- res.set(key.id, normalized);
- }
- }
- function _constructDependencies(factoryFunction, dependencies) {
- if (lang_1.isBlank(dependencies)) {
- return _dependenciesFor(factoryFunction);
- }
- else {
- var params = dependencies.map(function (t) { return [t]; });
- return dependencies.map(function (t) { return _extractToken(factoryFunction, t, params); });
- }
- }
- function _dependenciesFor(typeOrFunc) {
- var params = reflection_1.reflector.parameters(typeOrFunc);
- if (lang_1.isBlank(params))
- return [];
- if (params.some(lang_1.isBlank)) {
- throw new exceptions_2.NoAnnotationError(typeOrFunc, params);
- }
- return params.map(function (p) { return _extractToken(typeOrFunc, p, params); });
- }
- function _extractToken(typeOrFunc, metadata /*any[] | any*/, params) {
- var depProps = [];
- var token = null;
- var optional = false;
- if (!lang_1.isArray(metadata)) {
- if (metadata instanceof metadata_1.InjectMetadata) {
- return _createDependency(metadata.token, optional, null, null, depProps);
- }
- else {
- return _createDependency(metadata, optional, null, null, depProps);
- }
- }
- var lowerBoundVisibility = null;
- var upperBoundVisibility = null;
- for (var i = 0; i < metadata.length; ++i) {
- var paramMetadata = metadata[i];
- if (paramMetadata instanceof lang_1.Type) {
- token = paramMetadata;
- }
- else if (paramMetadata instanceof metadata_1.InjectMetadata) {
- token = paramMetadata.token;
- }
- else if (paramMetadata instanceof metadata_1.OptionalMetadata) {
- optional = true;
- }
- else if (paramMetadata instanceof metadata_1.SelfMetadata) {
- upperBoundVisibility = paramMetadata;
- }
- else if (paramMetadata instanceof metadata_1.HostMetadata) {
- upperBoundVisibility = paramMetadata;
- }
- else if (paramMetadata instanceof metadata_1.SkipSelfMetadata) {
- lowerBoundVisibility = paramMetadata;
- }
- else if (paramMetadata instanceof metadata_1.DependencyMetadata) {
- if (lang_1.isPresent(paramMetadata.token)) {
- token = paramMetadata.token;
- }
- depProps.push(paramMetadata);
- }
- }
- token = forward_ref_1.resolveForwardRef(token);
- if (lang_1.isPresent(token)) {
- return _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps);
- }
- else {
- throw new exceptions_2.NoAnnotationError(typeOrFunc, params);
- }
- }
- function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps) {
- return new Dependency(key_1.Key.get(token), optional, lowerBoundVisibility, upperBoundVisibility, depProps);
- }
- /***/ },
- /* 14 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var exception_handler_1 = __webpack_require__(15);
- var exception_handler_2 = __webpack_require__(15);
- exports.ExceptionHandler = exception_handler_2.ExceptionHandler;
- var BaseException = (function (_super) {
- __extends(BaseException, _super);
- function BaseException(message) {
- if (message === void 0) { message = "--"; }
- _super.call(this, message);
- this.message = message;
- this.stack = (new Error(message)).stack;
- }
- BaseException.prototype.toString = function () { return this.message; };
- return BaseException;
- })(Error);
- exports.BaseException = BaseException;
- /**
- * Wraps an exception and provides additional context or information.
- */
- var WrappedException = (function (_super) {
- __extends(WrappedException, _super);
- function WrappedException(_wrapperMessage, _originalException, _originalStack, _context) {
- _super.call(this, _wrapperMessage);
- this._wrapperMessage = _wrapperMessage;
- this._originalException = _originalException;
- this._originalStack = _originalStack;
- this._context = _context;
- this._wrapperStack = (new Error(_wrapperMessage)).stack;
- }
- Object.defineProperty(WrappedException.prototype, "wrapperMessage", {
- get: function () { return this._wrapperMessage; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WrappedException.prototype, "wrapperStack", {
- get: function () { return this._wrapperStack; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WrappedException.prototype, "originalException", {
- get: function () { return this._originalException; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WrappedException.prototype, "originalStack", {
- get: function () { return this._originalStack; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WrappedException.prototype, "context", {
- get: function () { return this._context; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(WrappedException.prototype, "message", {
- get: function () { return exception_handler_1.ExceptionHandler.exceptionToString(this); },
- enumerable: true,
- configurable: true
- });
- WrappedException.prototype.toString = function () { return this.message; };
- return WrappedException;
- })(Error);
- exports.WrappedException = WrappedException;
- function makeTypeError(message) {
- return new TypeError(message);
- }
- exports.makeTypeError = makeTypeError;
- function unimplemented() {
- throw new BaseException('unimplemented');
- }
- exports.unimplemented = unimplemented;
- /***/ },
- /* 15 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var _ArrayLogger = (function () {
- function _ArrayLogger() {
- this.res = [];
- }
- _ArrayLogger.prototype.log = function (s) { this.res.push(s); };
- _ArrayLogger.prototype.logError = function (s) { this.res.push(s); };
- _ArrayLogger.prototype.logGroup = function (s) { this.res.push(s); };
- _ArrayLogger.prototype.logGroupEnd = function () { };
- ;
- return _ArrayLogger;
- })();
- /**
- * Provides a hook for centralized exception handling.
- *
- * The default implementation of `ExceptionHandler` prints error messages to the `Console`. To
- * intercept error handling,
- * write a custom exception handler that replaces this default as appropriate for your app.
- *
- * ### Example
- *
- * ```javascript
- *
- * class MyExceptionHandler implements ExceptionHandler {
- * call(error, stackTrace = null, reason = null) {
- * // do something with the exception
- * }
- * }
- *
- * bootstrap(MyApp, [provide(ExceptionHandler, {useClass: MyExceptionHandler})])
- *
- * ```
- */
- var ExceptionHandler = (function () {
- function ExceptionHandler(_logger, _rethrowException) {
- if (_rethrowException === void 0) { _rethrowException = true; }
- this._logger = _logger;
- this._rethrowException = _rethrowException;
- }
- ExceptionHandler.exceptionToString = function (exception, stackTrace, reason) {
- if (stackTrace === void 0) { stackTrace = null; }
- if (reason === void 0) { reason = null; }
- var l = new _ArrayLogger();
- var e = new ExceptionHandler(l, false);
- e.call(exception, stackTrace, reason);
- return l.res.join("\n");
- };
- ExceptionHandler.prototype.call = function (exception, stackTrace, reason) {
- if (stackTrace === void 0) { stackTrace = null; }
- if (reason === void 0) { reason = null; }
- var originalException = this._findOriginalException(exception);
- var originalStack = this._findOriginalStack(exception);
- var context = this._findContext(exception);
- this._logger.logGroup("EXCEPTION: " + this._extractMessage(exception));
- if (lang_1.isPresent(stackTrace) && lang_1.isBlank(originalStack)) {
- this._logger.logError("STACKTRACE:");
- this._logger.logError(this._longStackTrace(stackTrace));
- }
- if (lang_1.isPresent(reason)) {
- this._logger.logError("REASON: " + reason);
- }
- if (lang_1.isPresent(originalException)) {
- this._logger.logError("ORIGINAL EXCEPTION: " + this._extractMessage(originalException));
- }
- if (lang_1.isPresent(originalStack)) {
- this._logger.logError("ORIGINAL STACKTRACE:");
- this._logger.logError(this._longStackTrace(originalStack));
- }
- if (lang_1.isPresent(context)) {
- this._logger.logError("ERROR CONTEXT:");
- this._logger.logError(context);
- }
- this._logger.logGroupEnd();
- // We rethrow exceptions, so operations like 'bootstrap' will result in an error
- // when an exception happens. If we do not rethrow, bootstrap will always succeed.
- if (this._rethrowException)
- throw exception;
- };
- /** @internal */
- ExceptionHandler.prototype._extractMessage = function (exception) {
- return exception instanceof exceptions_1.WrappedException ? exception.wrapperMessage : exception.toString();
- };
- /** @internal */
- ExceptionHandler.prototype._longStackTrace = function (stackTrace) {
- return collection_1.isListLikeIterable(stackTrace) ? stackTrace.join("\n\n-----async gap-----\n") :
- stackTrace.toString();
- };
- /** @internal */
- ExceptionHandler.prototype._findContext = function (exception) {
- try {
- if (!(exception instanceof exceptions_1.WrappedException))
- return null;
- return lang_1.isPresent(exception.context) ? exception.context :
- this._findContext(exception.originalException);
- }
- catch (e) {
- // exception.context can throw an exception. if it happens, we ignore the context.
- return null;
- }
- };
- /** @internal */
- ExceptionHandler.prototype._findOriginalException = function (exception) {
- if (!(exception instanceof exceptions_1.WrappedException))
- return null;
- var e = exception.originalException;
- while (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) {
- e = e.originalException;
- }
- return e;
- };
- /** @internal */
- ExceptionHandler.prototype._findOriginalStack = function (exception) {
- if (!(exception instanceof exceptions_1.WrappedException))
- return null;
- var e = exception;
- var stack = exception.originalStack;
- while (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) {
- e = e.originalException;
- if (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) {
- stack = e.originalStack;
- }
- }
- return stack;
- };
- return ExceptionHandler;
- })();
- exports.ExceptionHandler = ExceptionHandler;
- /***/ },
- /* 16 */
- /***/ function(module, exports, __webpack_require__) {
- var reflector_1 = __webpack_require__(17);
- var reflector_2 = __webpack_require__(17);
- exports.Reflector = reflector_2.Reflector;
- exports.ReflectionInfo = reflector_2.ReflectionInfo;
- var reflection_capabilities_1 = __webpack_require__(18);
- /**
- * The {@link Reflector} used internally in Angular to access metadata
- * about symbols.
- */
- exports.reflector = new reflector_1.Reflector(new reflection_capabilities_1.ReflectionCapabilities());
- /***/ },
- /* 17 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- /**
- * Reflective information about a symbol, including annotations, interfaces, and other metadata.
- */
- var ReflectionInfo = (function () {
- function ReflectionInfo(annotations, parameters, factory, interfaces, propMetadata) {
- this.annotations = annotations;
- this.parameters = parameters;
- this.factory = factory;
- this.interfaces = interfaces;
- this.propMetadata = propMetadata;
- }
- return ReflectionInfo;
- })();
- exports.ReflectionInfo = ReflectionInfo;
- /**
- * Provides access to reflection data about symbols. Used internally by Angular
- * to power dependency injection and compilation.
- */
- var Reflector = (function () {
- function Reflector(reflectionCapabilities) {
- /** @internal */
- this._injectableInfo = new collection_1.Map();
- /** @internal */
- this._getters = new collection_1.Map();
- /** @internal */
- this._setters = new collection_1.Map();
- /** @internal */
- this._methods = new collection_1.Map();
- this._usedKeys = null;
- this.reflectionCapabilities = reflectionCapabilities;
- }
- Reflector.prototype.isReflectionEnabled = function () { return this.reflectionCapabilities.isReflectionEnabled(); };
- /**
- * Causes `this` reflector to track keys used to access
- * {@link ReflectionInfo} objects.
- */
- Reflector.prototype.trackUsage = function () { this._usedKeys = new collection_1.Set(); };
- /**
- * Lists types for which reflection information was not requested since
- * {@link #trackUsage} was called. This list could later be audited as
- * potential dead code.
- */
- Reflector.prototype.listUnusedKeys = function () {
- var _this = this;
- if (this._usedKeys == null) {
- throw new exceptions_1.BaseException('Usage tracking is disabled');
- }
- var allTypes = collection_1.MapWrapper.keys(this._injectableInfo);
- return allTypes.filter(function (key) { return !collection_1.SetWrapper.has(_this._usedKeys, key); });
- };
- Reflector.prototype.registerFunction = function (func, funcInfo) {
- this._injectableInfo.set(func, funcInfo);
- };
- Reflector.prototype.registerType = function (type, typeInfo) {
- this._injectableInfo.set(type, typeInfo);
- };
- Reflector.prototype.registerGetters = function (getters) { _mergeMaps(this._getters, getters); };
- Reflector.prototype.registerSetters = function (setters) { _mergeMaps(this._setters, setters); };
- Reflector.prototype.registerMethods = function (methods) { _mergeMaps(this._methods, methods); };
- Reflector.prototype.factory = function (type) {
- if (this._containsReflectionInfo(type)) {
- var res = this._getReflectionInfo(type).factory;
- return lang_1.isPresent(res) ? res : null;
- }
- else {
- return this.reflectionCapabilities.factory(type);
- }
- };
- Reflector.prototype.parameters = function (typeOrFunc) {
- if (this._injectableInfo.has(typeOrFunc)) {
- var res = this._getReflectionInfo(typeOrFunc).parameters;
- return lang_1.isPresent(res) ? res : [];
- }
- else {
- return this.reflectionCapabilities.parameters(typeOrFunc);
- }
- };
- Reflector.prototype.annotations = function (typeOrFunc) {
- if (this._injectableInfo.has(typeOrFunc)) {
- var res = this._getReflectionInfo(typeOrFunc).annotations;
- return lang_1.isPresent(res) ? res : [];
- }
- else {
- return this.reflectionCapabilities.annotations(typeOrFunc);
- }
- };
- Reflector.prototype.propMetadata = function (typeOrFunc) {
- if (this._injectableInfo.has(typeOrFunc)) {
- var res = this._getReflectionInfo(typeOrFunc).propMetadata;
- return lang_1.isPresent(res) ? res : {};
- }
- else {
- return this.reflectionCapabilities.propMetadata(typeOrFunc);
- }
- };
- Reflector.prototype.interfaces = function (type) {
- if (this._injectableInfo.has(type)) {
- var res = this._getReflectionInfo(type).interfaces;
- return lang_1.isPresent(res) ? res : [];
- }
- else {
- return this.reflectionCapabilities.interfaces(type);
- }
- };
- Reflector.prototype.getter = function (name) {
- if (this._getters.has(name)) {
- return this._getters.get(name);
- }
- else {
- return this.reflectionCapabilities.getter(name);
- }
- };
- Reflector.prototype.setter = function (name) {
- if (this._setters.has(name)) {
- return this._setters.get(name);
- }
- else {
- return this.reflectionCapabilities.setter(name);
- }
- };
- Reflector.prototype.method = function (name) {
- if (this._methods.has(name)) {
- return this._methods.get(name);
- }
- else {
- return this.reflectionCapabilities.method(name);
- }
- };
- /** @internal */
- Reflector.prototype._getReflectionInfo = function (typeOrFunc) {
- if (lang_1.isPresent(this._usedKeys)) {
- this._usedKeys.add(typeOrFunc);
- }
- return this._injectableInfo.get(typeOrFunc);
- };
- /** @internal */
- Reflector.prototype._containsReflectionInfo = function (typeOrFunc) { return this._injectableInfo.has(typeOrFunc); };
- Reflector.prototype.importUri = function (type) { return this.reflectionCapabilities.importUri(type); };
- return Reflector;
- })();
- exports.Reflector = Reflector;
- function _mergeMaps(target, config) {
- collection_1.StringMapWrapper.forEach(config, function (v, k) { return target.set(k, v); });
- }
- /***/ },
- /* 18 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var ReflectionCapabilities = (function () {
- function ReflectionCapabilities(reflect) {
- this._reflect = lang_1.isPresent(reflect) ? reflect : lang_1.global.Reflect;
- }
- ReflectionCapabilities.prototype.isReflectionEnabled = function () { return true; };
- ReflectionCapabilities.prototype.factory = function (t) {
- switch (t.length) {
- case 0:
- return function () { return new t(); };
- case 1:
- return function (a1) { return new t(a1); };
- case 2:
- return function (a1, a2) { return new t(a1, a2); };
- case 3:
- return function (a1, a2, a3) { return new t(a1, a2, a3); };
- case 4:
- return function (a1, a2, a3, a4) { return new t(a1, a2, a3, a4); };
- case 5:
- return function (a1, a2, a3, a4, a5) { return new t(a1, a2, a3, a4, a5); };
- case 6:
- return function (a1, a2, a3, a4, a5, a6) { return new t(a1, a2, a3, a4, a5, a6); };
- case 7:
- return function (a1, a2, a3, a4, a5, a6, a7) { return new t(a1, a2, a3, a4, a5, a6, a7); };
- case 8:
- return function (a1, a2, a3, a4, a5, a6, a7, a8) { return new t(a1, a2, a3, a4, a5, a6, a7, a8); };
- case 9:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9) { return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9); };
- case 10:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
- };
- case 11:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11);
- };
- case 12:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12);
- };
- case 13:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13);
- };
- case 14:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14);
- };
- case 15:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15);
- };
- case 16:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16);
- };
- case 17:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17);
- };
- case 18:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18);
- };
- case 19:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19);
- };
- case 20:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) {
- return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
- };
- }
- ;
- throw new Error("Cannot create a factory for '" + lang_1.stringify(t) + "' because its constructor has more than 20 arguments");
- };
- /** @internal */
- ReflectionCapabilities.prototype._zipTypesAndAnnotaions = function (paramTypes, paramAnnotations) {
- var result;
- if (typeof paramTypes === 'undefined') {
- result = new Array(paramAnnotations.length);
- }
- else {
- result = new Array(paramTypes.length);
- }
- for (var i = 0; i < result.length; i++) {
- // TS outputs Object for parameters without types, while Traceur omits
- // the annotations. For now we preserve the Traceur behavior to aid
- // migration, but this can be revisited.
- if (typeof paramTypes === 'undefined') {
- result[i] = [];
- }
- else if (paramTypes[i] != Object) {
- result[i] = [paramTypes[i]];
- }
- else {
- result[i] = [];
- }
- if (lang_1.isPresent(paramAnnotations) && lang_1.isPresent(paramAnnotations[i])) {
- result[i] = result[i].concat(paramAnnotations[i]);
- }
- }
- return result;
- };
- ReflectionCapabilities.prototype.parameters = function (typeOrFunc) {
- // Prefer the direct API.
- if (lang_1.isPresent(typeOrFunc.parameters)) {
- return typeOrFunc.parameters;
- }
- if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) {
- var paramAnnotations = this._reflect.getMetadata('parameters', typeOrFunc);
- var paramTypes = this._reflect.getMetadata('design:paramtypes', typeOrFunc);
- if (lang_1.isPresent(paramTypes) || lang_1.isPresent(paramAnnotations)) {
- return this._zipTypesAndAnnotaions(paramTypes, paramAnnotations);
- }
- }
- // The array has to be filled with `undefined` because holes would be skipped by `some`
- var parameters = new Array(typeOrFunc.length);
- parameters.fill(undefined);
- return parameters;
- };
- ReflectionCapabilities.prototype.annotations = function (typeOrFunc) {
- // Prefer the direct API.
- if (lang_1.isPresent(typeOrFunc.annotations)) {
- var annotations = typeOrFunc.annotations;
- if (lang_1.isFunction(annotations) && annotations.annotations) {
- annotations = annotations.annotations;
- }
- return annotations;
- }
- if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) {
- var annotations = this._reflect.getMetadata('annotations', typeOrFunc);
- if (lang_1.isPresent(annotations))
- return annotations;
- }
- return [];
- };
- ReflectionCapabilities.prototype.propMetadata = function (typeOrFunc) {
- // Prefer the direct API.
- if (lang_1.isPresent(typeOrFunc.propMetadata)) {
- var propMetadata = typeOrFunc.propMetadata;
- if (lang_1.isFunction(propMetadata) && propMetadata.propMetadata) {
- propMetadata = propMetadata.propMetadata;
- }
- return propMetadata;
- }
- if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) {
- var propMetadata = this._reflect.getMetadata('propMetadata', typeOrFunc);
- if (lang_1.isPresent(propMetadata))
- return propMetadata;
- }
- return {};
- };
- ReflectionCapabilities.prototype.interfaces = function (type) {
- throw new exceptions_1.BaseException("JavaScript does not support interfaces");
- };
- ReflectionCapabilities.prototype.getter = function (name) { return new Function('o', 'return o.' + name + ';'); };
- ReflectionCapabilities.prototype.setter = function (name) {
- return new Function('o', 'v', 'return o.' + name + ' = v;');
- };
- ReflectionCapabilities.prototype.method = function (name) {
- var functionBody = "if (!o." + name + ") throw new Error('\"" + name + "\" is undefined');\n return o." + name + ".apply(o, args);";
- return new Function('o', 'args', functionBody);
- };
- // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
- ReflectionCapabilities.prototype.importUri = function (type) { return './'; };
- return ReflectionCapabilities;
- })();
- exports.ReflectionCapabilities = ReflectionCapabilities;
- /***/ },
- /* 19 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var type_literal_1 = __webpack_require__(20);
- var forward_ref_1 = __webpack_require__(10);
- var type_literal_2 = __webpack_require__(20);
- exports.TypeLiteral = type_literal_2.TypeLiteral;
- /**
- * A unique object used for retrieving items from the {@link Injector}.
- *
- * Keys have:
- * - a system-wide unique `id`.
- * - a `token`.
- *
- * `Key` is used internally by {@link Injector} because its system-wide unique `id` allows the
- * injector to store created objects in a more efficient way.
- *
- * `Key` should not be created directly. {@link Injector} creates keys automatically when resolving
- * providers.
- */
- var Key = (function () {
- /**
- * Private
- */
- function Key(token, id) {
- this.token = token;
- this.id = id;
- if (lang_1.isBlank(token)) {
- throw new exceptions_1.BaseException('Token must be defined!');
- }
- }
- Object.defineProperty(Key.prototype, "displayName", {
- /**
- * Returns a stringified token.
- */
- get: function () { return lang_1.stringify(this.token); },
- enumerable: true,
- configurable: true
- });
- /**
- * Retrieves a `Key` for a token.
- */
- Key.get = function (token) { return _globalKeyRegistry.get(forward_ref_1.resolveForwardRef(token)); };
- Object.defineProperty(Key, "numberOfKeys", {
- /**
- * @returns the number of keys registered in the system.
- */
- get: function () { return _globalKeyRegistry.numberOfKeys; },
- enumerable: true,
- configurable: true
- });
- return Key;
- })();
- exports.Key = Key;
- /**
- * @internal
- */
- var KeyRegistry = (function () {
- function KeyRegistry() {
- this._allKeys = new Map();
- }
- KeyRegistry.prototype.get = function (token) {
- if (token instanceof Key)
- return token;
- // TODO: workaround for https://github.com/Microsoft/TypeScript/issues/3123
- var theToken = token;
- if (token instanceof type_literal_1.TypeLiteral) {
- theToken = token.type;
- }
- token = theToken;
- if (this._allKeys.has(token)) {
- return this._allKeys.get(token);
- }
- var newKey = new Key(token, Key.numberOfKeys);
- this._allKeys.set(token, newKey);
- return newKey;
- };
- Object.defineProperty(KeyRegistry.prototype, "numberOfKeys", {
- get: function () { return this._allKeys.size; },
- enumerable: true,
- configurable: true
- });
- return KeyRegistry;
- })();
- exports.KeyRegistry = KeyRegistry;
- var _globalKeyRegistry = new KeyRegistry();
- /***/ },
- /* 20 */
- /***/ function(module, exports) {
- /**
- * Type literals is a Dart-only feature. This is here only so we can x-compile
- * to multiple languages.
- */
- var TypeLiteral = (function () {
- function TypeLiteral() {
- }
- Object.defineProperty(TypeLiteral.prototype, "type", {
- get: function () { throw new Error("Type literals are only supported in Dart"); },
- enumerable: true,
- configurable: true
- });
- return TypeLiteral;
- })();
- exports.TypeLiteral = TypeLiteral;
- /***/ },
- /* 21 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- function findFirstClosedCycle(keys) {
- var res = [];
- for (var i = 0; i < keys.length; ++i) {
- if (collection_1.ListWrapper.contains(res, keys[i])) {
- res.push(keys[i]);
- return res;
- }
- else {
- res.push(keys[i]);
- }
- }
- return res;
- }
- function constructResolvingPath(keys) {
- if (keys.length > 1) {
- var reversed = findFirstClosedCycle(collection_1.ListWrapper.reversed(keys));
- var tokenStrs = reversed.map(function (k) { return lang_1.stringify(k.token); });
- return " (" + tokenStrs.join(' -> ') + ")";
- }
- else {
- return "";
- }
- }
- /**
- * Base class for all errors arising from misconfigured providers.
- */
- var AbstractProviderError = (function (_super) {
- __extends(AbstractProviderError, _super);
- function AbstractProviderError(injector, key, constructResolvingMessage) {
- _super.call(this, "DI Exception");
- this.keys = [key];
- this.injectors = [injector];
- this.constructResolvingMessage = constructResolvingMessage;
- this.message = this.constructResolvingMessage(this.keys);
- }
- AbstractProviderError.prototype.addKey = function (injector, key) {
- this.injectors.push(injector);
- this.keys.push(key);
- this.message = this.constructResolvingMessage(this.keys);
- };
- Object.defineProperty(AbstractProviderError.prototype, "context", {
- get: function () { return this.injectors[this.injectors.length - 1].debugContext(); },
- enumerable: true,
- configurable: true
- });
- return AbstractProviderError;
- })(exceptions_1.BaseException);
- exports.AbstractProviderError = AbstractProviderError;
- /**
- * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
- * {@link Injector} does not have a {@link Provider} for {@link Key}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
- *
- * ```typescript
- * class A {
- * constructor(b:B) {}
- * }
- *
- * expect(() => Injector.resolveAndCreate([A])).toThrowError();
- * ```
- */
- var NoProviderError = (function (_super) {
- __extends(NoProviderError, _super);
- function NoProviderError(injector, key) {
- _super.call(this, injector, key, function (keys) {
- var first = lang_1.stringify(collection_1.ListWrapper.first(keys).token);
- return "No provider for " + first + "!" + constructResolvingPath(keys);
- });
- }
- return NoProviderError;
- })(AbstractProviderError);
- exports.NoProviderError = NoProviderError;
- /**
- * Thrown when dependencies form a cycle.
- *
- * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
- *
- * ```typescript
- * var injector = Injector.resolveAndCreate([
- * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}),
- * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]})
- * ]);
- *
- * expect(() => injector.get("one")).toThrowError();
- * ```
- *
- * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
- */
- var CyclicDependencyError = (function (_super) {
- __extends(CyclicDependencyError, _super);
- function CyclicDependencyError(injector, key) {
- _super.call(this, injector, key, function (keys) {
- return "Cannot instantiate cyclic dependency!" + constructResolvingPath(keys);
- });
- }
- return CyclicDependencyError;
- })(AbstractProviderError);
- exports.CyclicDependencyError = CyclicDependencyError;
- /**
- * Thrown when a constructing type returns with an Error.
- *
- * The `InstantiationError` class contains the original error plus the dependency graph which caused
- * this object to be instantiated.
- *
- * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
- *
- * ```typescript
- * class A {
- * constructor() {
- * throw new Error('message');
- * }
- * }
- *
- * var injector = Injector.resolveAndCreate([A]);
- * try {
- * injector.get(A);
- * } catch (e) {
- * expect(e instanceof InstantiationError).toBe(true);
- * expect(e.originalException.message).toEqual("message");
- * expect(e.originalStack).toBeDefined();
- * }
- * ```
- */
- var InstantiationError = (function (_super) {
- __extends(InstantiationError, _super);
- function InstantiationError(injector, originalException, originalStack, key) {
- _super.call(this, "DI Exception", originalException, originalStack, null);
- this.keys = [key];
- this.injectors = [injector];
- }
- InstantiationError.prototype.addKey = function (injector, key) {
- this.injectors.push(injector);
- this.keys.push(key);
- };
- Object.defineProperty(InstantiationError.prototype, "wrapperMessage", {
- get: function () {
- var first = lang_1.stringify(collection_1.ListWrapper.first(this.keys).token);
- return "Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + ".";
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstantiationError.prototype, "causeKey", {
- get: function () { return this.keys[0]; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(InstantiationError.prototype, "context", {
- get: function () { return this.injectors[this.injectors.length - 1].debugContext(); },
- enumerable: true,
- configurable: true
- });
- return InstantiationError;
- })(exceptions_1.WrappedException);
- exports.InstantiationError = InstantiationError;
- /**
- * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
- * creation.
- *
- * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
- *
- * ```typescript
- * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
- * ```
- */
- var InvalidProviderError = (function (_super) {
- __extends(InvalidProviderError, _super);
- function InvalidProviderError(provider) {
- _super.call(this, "Invalid provider - only instances of Provider and Type are allowed, got: " +
- provider.toString());
- }
- return InvalidProviderError;
- })(exceptions_1.BaseException);
- exports.InvalidProviderError = InvalidProviderError;
- /**
- * Thrown when the class has no annotation information.
- *
- * Lack of annotation information prevents the {@link Injector} from determining which dependencies
- * need to be injected into the constructor.
- *
- * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
- *
- * ```typescript
- * class A {
- * constructor(b) {}
- * }
- *
- * expect(() => Injector.resolveAndCreate([A])).toThrowError();
- * ```
- *
- * This error is also thrown when the class not marked with {@link Injectable} has parameter types.
- *
- * ```typescript
- * class B {}
- *
- * class A {
- * constructor(b:B) {} // no information about the parameter types of A is available at runtime.
- * }
- *
- * expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
- * ```
- */
- var NoAnnotationError = (function (_super) {
- __extends(NoAnnotationError, _super);
- function NoAnnotationError(typeOrFunc, params) {
- _super.call(this, NoAnnotationError._genMessage(typeOrFunc, params));
- }
- NoAnnotationError._genMessage = function (typeOrFunc, params) {
- var signature = [];
- for (var i = 0, ii = params.length; i < ii; i++) {
- var parameter = params[i];
- if (lang_1.isBlank(parameter) || parameter.length == 0) {
- signature.push('?');
- }
- else {
- signature.push(parameter.map(lang_1.stringify).join(' '));
- }
- }
- return "Cannot resolve all parameters for " + lang_1.stringify(typeOrFunc) + "(" +
- signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.';
- };
- return NoAnnotationError;
- })(exceptions_1.BaseException);
- exports.NoAnnotationError = NoAnnotationError;
- /**
- * Thrown when getting an object by index.
- *
- * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
- *
- * ```typescript
- * class A {}
- *
- * var injector = Injector.resolveAndCreate([A]);
- *
- * expect(() => injector.getAt(100)).toThrowError();
- * ```
- */
- var OutOfBoundsError = (function (_super) {
- __extends(OutOfBoundsError, _super);
- function OutOfBoundsError(index) {
- _super.call(this, "Index " + index + " is out-of-bounds.");
- }
- return OutOfBoundsError;
- })(exceptions_1.BaseException);
- exports.OutOfBoundsError = OutOfBoundsError;
- // TODO: add a working example after alpha38 is released
- /**
- * Thrown when a multi provider and a regular provider are bound to the same token.
- *
- * ### Example
- *
- * ```typescript
- * expect(() => Injector.resolveAndCreate([
- * new Provider("Strings", {useValue: "string1", multi: true}),
- * new Provider("Strings", {useValue: "string2", multi: false})
- * ])).toThrowError();
- * ```
- */
- var MixingMultiProvidersWithRegularProvidersError = (function (_super) {
- __extends(MixingMultiProvidersWithRegularProvidersError, _super);
- function MixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
- _super.call(this, "Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
- provider2.toString());
- }
- return MixingMultiProvidersWithRegularProvidersError;
- })(exceptions_1.BaseException);
- exports.MixingMultiProvidersWithRegularProvidersError = MixingMultiProvidersWithRegularProvidersError;
- /***/ },
- /* 22 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- /**
- * Creates a token that can be used in a DI Provider.
- *
- * ### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
- *
- * ```typescript
- * var t = new OpaqueToken("value");
- *
- * var injector = Injector.resolveAndCreate([
- * provide(t, {useValue: "providedValue"})
- * ]);
- *
- * expect(injector.get(t)).toEqual("bindingValue");
- * ```
- *
- * Using an `OpaqueToken` is preferable to using strings as tokens because of possible collisions
- * caused by multiple providers using the same string as two different tokens.
- *
- * Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
- * error messages.
- */
- var OpaqueToken = (function () {
- function OpaqueToken(_desc) {
- this._desc = _desc;
- }
- OpaqueToken.prototype.toString = function () { return "Token " + this._desc; };
- OpaqueToken = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], OpaqueToken);
- return OpaqueToken;
- })();
- exports.OpaqueToken = OpaqueToken;
- /***/ },
- /* 23 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var metadata_1 = __webpack_require__(7);
- var change_detection_1 = __webpack_require__(24);
- /**
- * Directives allow you to attach behavior to elements in the DOM.
- *
- * {@link DirectiveMetadata}s with an embedded view are called {@link ComponentMetadata}s.
- *
- * A directive consists of a single directive annotation and a controller class. When the
- * directive's `selector` matches
- * elements in the DOM, the following steps occur:
- *
- * 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor
- * arguments.
- * 2. Angular instantiates directives for each matched element using `ElementInjector` in a
- * depth-first order,
- * as declared in the HTML.
- *
- * ## Understanding How Injection Works
- *
- * There are three stages of injection resolution.
- * - *Pre-existing Injectors*:
- * - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if
- * the dependency was
- * specified as `@Optional`, returns `null`.
- * - The platform injector resolves browser singleton resources, such as: cookies, title,
- * location, and others.
- * - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow
- * the same parent-child hierarchy
- * as the component instances in the DOM.
- * - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each
- * element has an `ElementInjector`
- * which follow the same parent-child hierarchy as the DOM elements themselves.
- *
- * When a template is instantiated, it also must instantiate the corresponding directives in a
- * depth-first order. The
- * current `ElementInjector` resolves the constructor dependencies for each directive.
- *
- * Angular then resolves dependencies as follows, according to the order in which they appear in the
- * {@link ViewMetadata}:
- *
- * 1. Dependencies on the current element
- * 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary
- * 3. Dependencies on component injectors and their parents until it encounters the root component
- * 4. Dependencies on pre-existing injectors
- *
- *
- * The `ElementInjector` can inject other directives, element-specific special objects, or it can
- * delegate to the parent
- * injector.
- *
- * To inject other directives, declare the constructor parameter as:
- * - `directive:DirectiveType`: a directive on the current element only
- * - `@Host() directive:DirectiveType`: any directive that matches the type between the current
- * element and the
- * Shadow DOM root.
- * - `@Query(DirectiveType) query:QueryList<DirectiveType>`: A live collection of direct child
- * directives.
- * - `@QueryDescendants(DirectiveType) query:QueryList<DirectiveType>`: A live collection of any
- * child directives.
- *
- * To inject element-specific special objects, declare the constructor parameter as:
- * - `element: ElementRef` to obtain a reference to logical element in the view.
- * - `viewContainer: ViewContainerRef` to control child template instantiation, for
- * {@link DirectiveMetadata} directives only
- * - `bindingPropagation: BindingPropagation` to control change detection in a more granular way.
- *
- * ### Example
- *
- * The following example demonstrates how dependency injection resolves constructor arguments in
- * practice.
- *
- *
- * Assume this HTML template:
- *
- * ```
- * <div dependency="1">
- * <div dependency="2">
- * <div dependency="3" my-directive>
- * <div dependency="4">
- * <div dependency="5"></div>
- * </div>
- * <div dependency="6"></div>
- * </div>
- * </div>
- * </div>
- * ```
- *
- * With the following `dependency` decorator and `SomeService` injectable class.
- *
- * ```
- * @Injectable()
- * class SomeService {
- * }
- *
- * @Directive({
- * selector: '[dependency]',
- * inputs: [
- * 'id: dependency'
- * ]
- * })
- * class Dependency {
- * id:string;
- * }
- * ```
- *
- * Let's step through the different ways in which `MyDirective` could be declared...
- *
- *
- * ### No injection
- *
- * Here the constructor is declared with no arguments, therefore nothing is injected into
- * `MyDirective`.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor() {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with no dependencies.
- *
- *
- * ### Component-level injection
- *
- * Directives can inject any injectable instance from the closest component injector or any of its
- * parents.
- *
- * Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type
- * from the parent
- * component's injector.
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(someService: SomeService) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a dependency on `SomeService`.
- *
- *
- * ### Injecting a directive from the current element
- *
- * Directives can inject other directives declared on the current element.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(dependency: Dependency) {
- * expect(dependency.id).toEqual(3);
- * }
- * }
- * ```
- * This directive would be instantiated with `Dependency` declared at the same element, in this case
- * `dependency="3"`.
- *
- * ### Injecting a directive from any ancestor elements
- *
- * Directives can inject other directives declared on any ancestor element (in the current Shadow
- * DOM), i.e. on the current element, the
- * parent element, or its parents.
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Host() dependency: Dependency) {
- * expect(dependency.id).toEqual(2);
- * }
- * }
- * ```
- *
- * `@Host` checks the current element, the parent, as well as its parents recursively. If
- * `dependency="2"` didn't
- * exist on the direct parent, this injection would
- * have returned
- * `dependency="1"`.
- *
- *
- * ### Injecting a live collection of direct child directives
- *
- *
- * A directive can also query for other child directives. Since parent directives are instantiated
- * before child directives, a directive can't simply inject the list of child directives. Instead,
- * the directive injects a {@link QueryList}, which updates its contents as children are added,
- * removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ngFor`, an
- * `ngIf`, or an `ngSwitch`.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Query(Dependency) dependencies:QueryList<Dependency>) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and
- * `Dependency` 6. Here, `Dependency` 5 would not be included, because it is not a direct child.
- *
- * ### Injecting a live collection of descendant directives
- *
- * By passing the descendant flag to `@Query` above, we can include the children of the child
- * elements.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList<Dependency>) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6.
- *
- * ### Optional injection
- *
- * The normal behavior of directives is to return an error when a specified dependency cannot be
- * resolved. If you
- * would like to inject `null` on unresolved dependency instead, you can annotate that dependency
- * with `@Optional()`.
- * This explicitly permits the author of a template to treat some of the surrounding directives as
- * optional.
- *
- * ```
- * @Directive({ selector: '[my-directive]' })
- * class MyDirective {
- * constructor(@Optional() dependency:Dependency) {
- * }
- * }
- * ```
- *
- * This directive would be instantiated with a `Dependency` directive found on the current element.
- * If none can be
- * found, the injector supplies `null` instead of throwing an error.
- *
- * ### Example
- *
- * Here we use a decorator directive to simply define basic tool-tip behavior.
- *
- * ```
- * @Directive({
- * selector: '[tooltip]',
- * inputs: [
- * 'text: tooltip'
- * ],
- * host: {
- * '(mouseenter)': 'onMouseEnter()',
- * '(mouseleave)': 'onMouseLeave()'
- * }
- * })
- * class Tooltip{
- * text:string;
- * overlay:Overlay; // NOT YET IMPLEMENTED
- * overlayManager:OverlayManager; // NOT YET IMPLEMENTED
- *
- * constructor(overlayManager:OverlayManager) {
- * this.overlay = overlay;
- * }
- *
- * onMouseEnter() {
- * // exact signature to be determined
- * this.overlay = this.overlayManager.open(text, ...);
- * }
- *
- * onMouseLeave() {
- * this.overlay.close();
- * this.overlay = null;
- * }
- * }
- * ```
- * In our HTML template, we can then add this behavior to a `<div>` or any other element with the
- * `tooltip` selector,
- * like so:
- *
- * ```
- * <div tooltip="some text here"></div>
- * ```
- *
- * Directives can also control the instantiation, destruction, and positioning of inline template
- * elements:
- *
- * A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at
- * runtime.
- * The {@link ViewContainerRef} is created as a result of `<template>` element, and represents a
- * location in the current view
- * where these actions are performed.
- *
- * Views are always created as children of the current {@link ViewMetadata}, and as siblings of the
- * `<template>` element. Thus a
- * directive in a child view cannot inject the directive that created it.
- *
- * Since directives that create views via ViewContainers are common in Angular, and using the full
- * `<template>` element syntax is wordy, Angular
- * also supports a shorthand notation: `<li *foo="bar">` and `<li template="foo: bar">` are
- * equivalent.
- *
- * Thus,
- *
- * ```
- * <ul>
- * <li *foo="bar" title="text"></li>
- * </ul>
- * ```
- *
- * Expands in use to:
- *
- * ```
- * <ul>
- * <template [foo]="bar">
- * <li title="text"></li>
- * </template>
- * </ul>
- * ```
- *
- * Notice that although the shorthand places `*foo="bar"` within the `<li>` element, the binding for
- * the directive
- * controller is correctly instantiated on the `<template>` element rather than the `<li>` element.
- *
- * ## Lifecycle hooks
- *
- * When the directive class implements some {@link angular2/lifecycle_hooks} the callbacks are
- * called by the change detection at defined points in time during the life of the directive.
- *
- * ### Example
- *
- * Let's suppose we want to implement the `unless` behavior, to conditionally include a template.
- *
- * Here is a simple directive that triggers on an `unless` selector:
- *
- * ```
- * @Directive({
- * selector: '[unless]',
- * inputs: ['unless']
- * })
- * export class Unless {
- * viewContainer: ViewContainerRef;
- * templateRef: TemplateRef;
- * prevCondition: boolean;
- *
- * constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef) {
- * this.viewContainer = viewContainer;
- * this.templateRef = templateRef;
- * this.prevCondition = null;
- * }
- *
- * set unless(newCondition) {
- * if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) {
- * this.prevCondition = true;
- * this.viewContainer.clear();
- * } else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) {
- * this.prevCondition = false;
- * this.viewContainer.create(this.templateRef);
- * }
- * }
- * }
- * ```
- *
- * We can then use this `unless` selector in a template:
- * ```
- * <ul>
- * <li *unless="expr"></li>
- * </ul>
- * ```
- *
- * Once the directive instantiates the child view, the shorthand notation for the template expands
- * and the result is:
- *
- * ```
- * <ul>
- * <template [unless]="exp">
- * <li></li>
- * </template>
- * <li></li>
- * </ul>
- * ```
- *
- * Note also that although the `<li></li>` template still exists inside the `<template></template>`,
- * the instantiated
- * view occurs on the second `<li></li>` which is a sibling to the `<template>` element.
- */
- var DirectiveMetadata = (function (_super) {
- __extends(DirectiveMetadata, _super);
- function DirectiveMetadata(_a) {
- var _b = _a === void 0 ? {} : _a, selector = _b.selector, inputs = _b.inputs, outputs = _b.outputs, properties = _b.properties, events = _b.events, host = _b.host, bindings = _b.bindings, providers = _b.providers, exportAs = _b.exportAs, queries = _b.queries;
- _super.call(this);
- this.selector = selector;
- this._inputs = inputs;
- this._properties = properties;
- this._outputs = outputs;
- this._events = events;
- this.host = host;
- this.exportAs = exportAs;
- this.queries = queries;
- this._providers = providers;
- this._bindings = bindings;
- }
- Object.defineProperty(DirectiveMetadata.prototype, "inputs", {
- /**
- * Enumerates the set of data-bound input properties for a directive
- *
- * Angular automatically updates input properties during change detection.
- *
- * The `inputs` property defines a set of `directiveProperty` to `bindingProperty`
- * configuration:
- *
- * - `directiveProperty` specifies the component property where the value is written.
- * - `bindingProperty` specifies the DOM property where the value is read from.
- *
- * When `bindingProperty` is not provided, it is assumed to be equal to `directiveProperty`.
- *
- * ### Example ([live demo](http://plnkr.co/edit/ivhfXY?p=preview))
- *
- * The following example creates a component with two data-bound properties.
- *
- * ```typescript
- * @Component({
- * selector: 'bank-account',
- * inputs: ['bankName', 'id: account-id'],
- * template: `
- * Bank Name: {{bankName}}
- * Account Id: {{id}}
- * `
- * })
- * class BankAccount {
- * bankName: string;
- * id: string;
- *
- * // this property is not bound, and won't be automatically updated by Angular
- * normalizedBankName: string;
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <bank-account bank-name="RBC" account-id="4747"></bank-account>
- * `,
- * directives: [BankAccount]
- * })
- * class App {}
- *
- * bootstrap(App);
- * ```
- *
- */
- get: function () {
- return lang_1.isPresent(this._properties) && this._properties.length > 0 ? this._properties :
- this._inputs;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveMetadata.prototype, "properties", {
- get: function () { return this.inputs; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveMetadata.prototype, "outputs", {
- /**
- * Enumerates the set of event-bound output properties.
- *
- * When an output property emits an event, an event handler attached to that event
- * the template is invoked.
- *
- * The `outputs` property defines a set of `directiveProperty` to `bindingProperty`
- * configuration:
- *
- * - `directiveProperty` specifies the component property that emits events.
- * - `bindingProperty` specifies the DOM property the event handler is attached to.
- *
- * ### Example ([live demo](http://plnkr.co/edit/d5CNq7?p=preview))
- *
- * ```typescript
- * @Directive({
- * selector: 'interval-dir',
- * outputs: ['everySecond', 'five5Secs: everyFiveSeconds']
- * })
- * class IntervalDir {
- * everySecond = new EventEmitter();
- * five5Secs = new EventEmitter();
- *
- * constructor() {
- * setInterval(() => this.everySecond.emit("event"), 1000);
- * setInterval(() => this.five5Secs.emit("event"), 5000);
- * }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <interval-dir (every-second)="everySecond()" (every-five-seconds)="everyFiveSeconds()">
- * </interval-dir>
- * `,
- * directives: [IntervalDir]
- * })
- * class App {
- * everySecond() { console.log('second'); }
- * everyFiveSeconds() { console.log('five seconds'); }
- * }
- * bootstrap(App);
- * ```
- *
- */
- get: function () {
- return lang_1.isPresent(this._events) && this._events.length > 0 ? this._events : this._outputs;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveMetadata.prototype, "events", {
- get: function () { return this.outputs; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveMetadata.prototype, "providers", {
- /**
- * Defines the set of injectable objects that are visible to a Directive and its light DOM
- * children.
- *
- * ## Simple Example
- *
- * Here is an example of a class that can be injected:
- *
- * ```
- * class Greeter {
- * greet(name:string) {
- * return 'Hello ' + name + '!';
- * }
- * }
- *
- * @Directive({
- * selector: 'greet',
- * bindings: [
- * Greeter
- * ]
- * })
- * class HelloWorld {
- * greeter:Greeter;
- *
- * constructor(greeter:Greeter) {
- * this.greeter = greeter;
- * }
- * }
- * ```
- */
- get: function () {
- return lang_1.isPresent(this._bindings) && this._bindings.length > 0 ? this._bindings :
- this._providers;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveMetadata.prototype, "bindings", {
- /** @deprecated */
- get: function () { return this.providers; },
- enumerable: true,
- configurable: true
- });
- DirectiveMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], DirectiveMetadata);
- return DirectiveMetadata;
- })(metadata_1.InjectableMetadata);
- exports.DirectiveMetadata = DirectiveMetadata;
- /**
- * Declare reusable UI building blocks for an application.
- *
- * Each Angular component requires a single `@Component` annotation. The
- * `@Component`
- * annotation specifies when a component is instantiated, and which properties and hostListeners it
- * binds to.
- *
- * When a component is instantiated, Angular
- * - creates a shadow DOM for the component.
- * - loads the selected template into the shadow DOM.
- * - creates all the injectable objects configured with `providers` and `viewProviders`.
- *
- * All template expressions and statements are then evaluated against the component instance.
- *
- * For details on the `@View` annotation, see {@link ViewMetadata}.
- *
- * ## Lifecycle hooks
- *
- * When the component class implements some {@link angular2/lifecycle_hooks} the callbacks are
- * called by the change detection at defined points in time during the life of the component.
- *
- * ### Example
- *
- * {@example core/ts/metadata/metadata.ts region='component'}
- */
- var ComponentMetadata = (function (_super) {
- __extends(ComponentMetadata, _super);
- function ComponentMetadata(_a) {
- var _b = _a === void 0 ? {} : _a, selector = _b.selector, inputs = _b.inputs, outputs = _b.outputs, properties = _b.properties, events = _b.events, host = _b.host, exportAs = _b.exportAs, moduleId = _b.moduleId, bindings = _b.bindings, providers = _b.providers, viewBindings = _b.viewBindings, viewProviders = _b.viewProviders, _c = _b.changeDetection, changeDetection = _c === void 0 ? change_detection_1.ChangeDetectionStrategy.Default : _c, queries = _b.queries, templateUrl = _b.templateUrl, template = _b.template, styleUrls = _b.styleUrls, styles = _b.styles, directives = _b.directives, pipes = _b.pipes, encapsulation = _b.encapsulation;
- _super.call(this, {
- selector: selector,
- inputs: inputs,
- outputs: outputs,
- properties: properties,
- events: events,
- host: host,
- exportAs: exportAs,
- bindings: bindings,
- providers: providers,
- queries: queries
- });
- this.changeDetection = changeDetection;
- this._viewProviders = viewProviders;
- this._viewBindings = viewBindings;
- this.templateUrl = templateUrl;
- this.template = template;
- this.styleUrls = styleUrls;
- this.styles = styles;
- this.directives = directives;
- this.pipes = pipes;
- this.encapsulation = encapsulation;
- this.moduleId = moduleId;
- }
- Object.defineProperty(ComponentMetadata.prototype, "viewProviders", {
- /**
- * Defines the set of injectable objects that are visible to its view DOM children.
- *
- * ## Simple Example
- *
- * Here is an example of a class that can be injected:
- *
- * ```
- * class Greeter {
- * greet(name:string) {
- * return 'Hello ' + name + '!';
- * }
- * }
- *
- * @Directive({
- * selector: 'needs-greeter'
- * })
- * class NeedsGreeter {
- * greeter:Greeter;
- *
- * constructor(greeter:Greeter) {
- * this.greeter = greeter;
- * }
- * }
- *
- * @Component({
- * selector: 'greet',
- * viewProviders: [
- * Greeter
- * ],
- * template: `<needs-greeter></needs-greeter>`,
- * directives: [NeedsGreeter]
- * })
- * class HelloWorld {
- * }
- *
- * ```
- */
- get: function () {
- return lang_1.isPresent(this._viewBindings) && this._viewBindings.length > 0 ? this._viewBindings :
- this._viewProviders;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ComponentMetadata.prototype, "viewBindings", {
- get: function () { return this.viewProviders; },
- enumerable: true,
- configurable: true
- });
- ComponentMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], ComponentMetadata);
- return ComponentMetadata;
- })(DirectiveMetadata);
- exports.ComponentMetadata = ComponentMetadata;
- /**
- * Declare reusable pipe function.
- *
- * A "pure" pipe is only re-evaluated when either the input or any of the arguments change.
- *
- * When not specified, pipes default to being pure.
- *
- * ### Example
- *
- * {@example core/ts/metadata/metadata.ts region='pipe'}
- */
- var PipeMetadata = (function (_super) {
- __extends(PipeMetadata, _super);
- function PipeMetadata(_a) {
- var name = _a.name, pure = _a.pure;
- _super.call(this);
- this.name = name;
- this._pure = pure;
- }
- Object.defineProperty(PipeMetadata.prototype, "pure", {
- get: function () { return lang_1.isPresent(this._pure) ? this._pure : true; },
- enumerable: true,
- configurable: true
- });
- PipeMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], PipeMetadata);
- return PipeMetadata;
- })(metadata_1.InjectableMetadata);
- exports.PipeMetadata = PipeMetadata;
- /**
- * Declares a data-bound input property.
- *
- * Angular automatically updates data-bound properties during change detection.
- *
- * `InputMetadata` takes an optional parameter that specifies the name
- * used when instantiating a component in the template. When not provided,
- * the name of the decorated property is used.
- *
- * ### Example
- *
- * The following example creates a component with two input properties.
- *
- * ```typescript
- * @Component({
- * selector: 'bank-account',
- * template: `
- * Bank Name: {{bankName}}
- * Account Id: {{id}}
- * `
- * })
- * class BankAccount {
- * @Input() bankName: string;
- * @Input('account-id') id: string;
- *
- * // this property is not bound, and won't be automatically updated by Angular
- * normalizedBankName: string;
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <bank-account bank-name="RBC" account-id="4747"></bank-account>
- * `,
- * directives: [BankAccount]
- * })
- * class App {}
- *
- * bootstrap(App);
- * ```
- */
- var InputMetadata = (function () {
- function InputMetadata(
- /**
- * Name used when instantiating a component in the temlate.
- */
- bindingPropertyName) {
- this.bindingPropertyName = bindingPropertyName;
- }
- InputMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], InputMetadata);
- return InputMetadata;
- })();
- exports.InputMetadata = InputMetadata;
- /**
- * Declares an event-bound output property.
- *
- * When an output property emits an event, an event handler attached to that event
- * the template is invoked.
- *
- * `OutputMetadata` takes an optional parameter that specifies the name
- * used when instantiating a component in the template. When not provided,
- * the name of the decorated property is used.
- *
- * ### Example
- *
- * ```typescript
- * @Directive({
- * selector: 'interval-dir',
- * })
- * class IntervalDir {
- * @Output() everySecond = new EventEmitter();
- * @Output('everyFiveSeconds') five5Secs = new EventEmitter();
- *
- * constructor() {
- * setInterval(() => this.everySecond.emit("event"), 1000);
- * setInterval(() => this.five5Secs.emit("event"), 5000);
- * }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <interval-dir (every-second)="everySecond()" (every-five-seconds)="everyFiveSeconds()">
- * </interval-dir>
- * `,
- * directives: [IntervalDir]
- * })
- * class App {
- * everySecond() { console.log('second'); }
- * everyFiveSeconds() { console.log('five seconds'); }
- * }
- * bootstrap(App);
- * ```
- */
- var OutputMetadata = (function () {
- function OutputMetadata(bindingPropertyName) {
- this.bindingPropertyName = bindingPropertyName;
- }
- OutputMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], OutputMetadata);
- return OutputMetadata;
- })();
- exports.OutputMetadata = OutputMetadata;
- /**
- * Declares a host property binding.
- *
- * Angular automatically checks host property bindings during change detection.
- * If a binding changes, it will update the host element of the directive.
- *
- * `HostBindingMetadata` takes an optional parameter that specifies the property
- * name of the host element that will be updated. When not provided,
- * the class property name is used.
- *
- * ### Example
- *
- * The following example creates a directive that sets the `valid` and `invalid` classes
- * on the DOM element that has ngModel directive on it.
- *
- * ```typescript
- * @Directive({selector: '[ngModel]'})
- * class NgModelStatus {
- * constructor(public control:NgModel) {}
- * @HostBinding('[class.valid]') get valid { return this.control.valid; }
- * @HostBinding('[class.invalid]') get invalid { return this.control.invalid; }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `<input [(ngModel)]="prop">`,
- * directives: [FORM_DIRECTIVES, NgModelStatus]
- * })
- * class App {
- * prop;
- * }
- *
- * bootstrap(App);
- * ```
- */
- var HostBindingMetadata = (function () {
- function HostBindingMetadata(hostPropertyName) {
- this.hostPropertyName = hostPropertyName;
- }
- HostBindingMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], HostBindingMetadata);
- return HostBindingMetadata;
- })();
- exports.HostBindingMetadata = HostBindingMetadata;
- /**
- * Declares a host listener.
- *
- * Angular will invoke the decorated method when the host element emits the specified event.
- *
- * If the decorated method returns `false`, then `preventDefault` is applied on the DOM
- * event.
- *
- * ### Example
- *
- * The following example declares a directive that attaches a click listener to the button and
- * counts clicks.
- *
- * ```typescript
- * @Directive({selector: 'button[counting]'})
- * class CountClicks {
- * numberOfClicks = 0;
- *
- * @HostListener('click', ['$event.target'])
- * onClick(btn) {
- * console.log("button", btn, "number of clicks:", this.numberOfClicks++);
- * }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `<button counting>Increment</button>`,
- * directives: [CountClicks]
- * })
- * class App {}
- *
- * bootstrap(App);
- * ```
- */
- var HostListenerMetadata = (function () {
- function HostListenerMetadata(eventName, args) {
- this.eventName = eventName;
- this.args = args;
- }
- HostListenerMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String, Array])
- ], HostListenerMetadata);
- return HostListenerMetadata;
- })();
- exports.HostListenerMetadata = HostListenerMetadata;
- /***/ },
- /* 24 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * Change detection enables data binding in Angular.
- */
- var change_detection_1 = __webpack_require__(25);
- exports.ChangeDetectionStrategy = change_detection_1.ChangeDetectionStrategy;
- exports.ExpressionChangedAfterItHasBeenCheckedException = change_detection_1.ExpressionChangedAfterItHasBeenCheckedException;
- exports.ChangeDetectionError = change_detection_1.ChangeDetectionError;
- exports.ChangeDetectorRef = change_detection_1.ChangeDetectorRef;
- exports.WrappedValue = change_detection_1.WrappedValue;
- exports.SimpleChange = change_detection_1.SimpleChange;
- exports.IterableDiffers = change_detection_1.IterableDiffers;
- exports.KeyValueDiffers = change_detection_1.KeyValueDiffers;
- /***/ },
- /* 25 */
- /***/ function(module, exports, __webpack_require__) {
- var iterable_differs_1 = __webpack_require__(26);
- var default_iterable_differ_1 = __webpack_require__(27);
- var keyvalue_differs_1 = __webpack_require__(28);
- var default_keyvalue_differ_1 = __webpack_require__(29);
- var lang_1 = __webpack_require__(5);
- var ast_1 = __webpack_require__(30);
- exports.ASTWithSource = ast_1.ASTWithSource;
- exports.AST = ast_1.AST;
- exports.AstTransformer = ast_1.AstTransformer;
- exports.PropertyRead = ast_1.PropertyRead;
- exports.LiteralArray = ast_1.LiteralArray;
- exports.ImplicitReceiver = ast_1.ImplicitReceiver;
- var lexer_1 = __webpack_require__(31);
- exports.Lexer = lexer_1.Lexer;
- var parser_1 = __webpack_require__(32);
- exports.Parser = parser_1.Parser;
- var locals_1 = __webpack_require__(33);
- exports.Locals = locals_1.Locals;
- var exceptions_1 = __webpack_require__(34);
- exports.DehydratedException = exceptions_1.DehydratedException;
- exports.ExpressionChangedAfterItHasBeenCheckedException = exceptions_1.ExpressionChangedAfterItHasBeenCheckedException;
- exports.ChangeDetectionError = exceptions_1.ChangeDetectionError;
- var interfaces_1 = __webpack_require__(35);
- exports.ChangeDetectorDefinition = interfaces_1.ChangeDetectorDefinition;
- exports.DebugContext = interfaces_1.DebugContext;
- exports.ChangeDetectorGenConfig = interfaces_1.ChangeDetectorGenConfig;
- var constants_1 = __webpack_require__(36);
- exports.ChangeDetectionStrategy = constants_1.ChangeDetectionStrategy;
- exports.CHANGE_DETECTION_STRATEGY_VALUES = constants_1.CHANGE_DETECTION_STRATEGY_VALUES;
- var proto_change_detector_1 = __webpack_require__(37);
- exports.DynamicProtoChangeDetector = proto_change_detector_1.DynamicProtoChangeDetector;
- var jit_proto_change_detector_1 = __webpack_require__(51);
- exports.JitProtoChangeDetector = jit_proto_change_detector_1.JitProtoChangeDetector;
- var binding_record_1 = __webpack_require__(40);
- exports.BindingRecord = binding_record_1.BindingRecord;
- exports.BindingTarget = binding_record_1.BindingTarget;
- var directive_record_1 = __webpack_require__(41);
- exports.DirectiveIndex = directive_record_1.DirectiveIndex;
- exports.DirectiveRecord = directive_record_1.DirectiveRecord;
- var dynamic_change_detector_1 = __webpack_require__(42);
- exports.DynamicChangeDetector = dynamic_change_detector_1.DynamicChangeDetector;
- var change_detector_ref_1 = __webpack_require__(44);
- exports.ChangeDetectorRef = change_detector_ref_1.ChangeDetectorRef;
- var iterable_differs_2 = __webpack_require__(26);
- exports.IterableDiffers = iterable_differs_2.IterableDiffers;
- var keyvalue_differs_2 = __webpack_require__(28);
- exports.KeyValueDiffers = keyvalue_differs_2.KeyValueDiffers;
- var change_detection_util_1 = __webpack_require__(38);
- exports.WrappedValue = change_detection_util_1.WrappedValue;
- exports.SimpleChange = change_detection_util_1.SimpleChange;
- /**
- * Structural diffing for `Object`s and `Map`s.
- */
- exports.keyValDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_keyvalue_differ_1.DefaultKeyValueDifferFactory())]);
- /**
- * Structural diffing for `Iterable` types such as `Array`s.
- */
- exports.iterableDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_iterable_differ_1.DefaultIterableDifferFactory())]);
- exports.defaultIterableDiffers = lang_1.CONST_EXPR(new iterable_differs_1.IterableDiffers(exports.iterableDiff));
- exports.defaultKeyValueDiffers = lang_1.CONST_EXPR(new keyvalue_differs_1.KeyValueDiffers(exports.keyValDiff));
- /***/ },
- /* 26 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var di_1 = __webpack_require__(6);
- /**
- * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
- */
- var IterableDiffers = (function () {
- function IterableDiffers(factories) {
- this.factories = factories;
- }
- IterableDiffers.create = function (factories, parent) {
- if (lang_1.isPresent(parent)) {
- var copied = collection_1.ListWrapper.clone(parent.factories);
- factories = factories.concat(copied);
- return new IterableDiffers(factories);
- }
- else {
- return new IterableDiffers(factories);
- }
- };
- /**
- * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
- * inherited {@link IterableDiffers} instance with the provided factories and return a new
- * {@link IterableDiffers} instance.
- *
- * The following example shows how to extend an existing list of factories,
- * which will only be applied to the injector for this component and its children.
- * This step is all that's required to make a new {@link IterableDiffer} available.
- *
- * ### Example
- *
- * ```
- * @Component({
- * viewProviders: [
- * IterableDiffers.extend([new ImmutableListDiffer()])
- * ]
- * })
- * ```
- */
- IterableDiffers.extend = function (factories) {
- return new di_1.Provider(IterableDiffers, {
- useFactory: function (parent) {
- if (lang_1.isBlank(parent)) {
- // Typically would occur when calling IterableDiffers.extend inside of dependencies passed
- // to
- // bootstrap(), which would override default pipes instead of extending them.
- throw new exceptions_1.BaseException('Cannot extend IterableDiffers without a parent injector');
- }
- return IterableDiffers.create(factories, parent);
- },
- // Dependency technically isn't optional, but we can provide a better error message this way.
- deps: [[IterableDiffers, new di_1.SkipSelfMetadata(), new di_1.OptionalMetadata()]]
- });
- };
- IterableDiffers.prototype.find = function (iterable) {
- var factory = this.factories.find(function (f) { return f.supports(iterable); });
- if (lang_1.isPresent(factory)) {
- return factory;
- }
- else {
- throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + iterable + "'");
- }
- };
- IterableDiffers = __decorate([
- di_1.Injectable(),
- lang_1.CONST(),
- __metadata('design:paramtypes', [Array])
- ], IterableDiffers);
- return IterableDiffers;
- })();
- exports.IterableDiffers = IterableDiffers;
- /***/ },
- /* 27 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var lang_2 = __webpack_require__(5);
- var DefaultIterableDifferFactory = (function () {
- function DefaultIterableDifferFactory() {
- }
- DefaultIterableDifferFactory.prototype.supports = function (obj) { return collection_1.isListLikeIterable(obj); };
- DefaultIterableDifferFactory.prototype.create = function (cdRef) { return new DefaultIterableDiffer(); };
- DefaultIterableDifferFactory = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], DefaultIterableDifferFactory);
- return DefaultIterableDifferFactory;
- })();
- exports.DefaultIterableDifferFactory = DefaultIterableDifferFactory;
- var DefaultIterableDiffer = (function () {
- function DefaultIterableDiffer() {
- this._collection = null;
- this._length = null;
- // Keeps track of the used records at any point in time (during & across `_check()` calls)
- this._linkedRecords = null;
- // Keeps track of the removed records at any point in time during `_check()` calls.
- this._unlinkedRecords = null;
- this._previousItHead = null;
- this._itHead = null;
- this._itTail = null;
- this._additionsHead = null;
- this._additionsTail = null;
- this._movesHead = null;
- this._movesTail = null;
- this._removalsHead = null;
- this._removalsTail = null;
- }
- Object.defineProperty(DefaultIterableDiffer.prototype, "collection", {
- get: function () { return this._collection; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DefaultIterableDiffer.prototype, "length", {
- get: function () { return this._length; },
- enumerable: true,
- configurable: true
- });
- DefaultIterableDiffer.prototype.forEachItem = function (fn) {
- var record;
- for (record = this._itHead; record !== null; record = record._next) {
- fn(record);
- }
- };
- DefaultIterableDiffer.prototype.forEachPreviousItem = function (fn) {
- var record;
- for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
- fn(record);
- }
- };
- DefaultIterableDiffer.prototype.forEachAddedItem = function (fn) {
- var record;
- for (record = this._additionsHead; record !== null; record = record._nextAdded) {
- fn(record);
- }
- };
- DefaultIterableDiffer.prototype.forEachMovedItem = function (fn) {
- var record;
- for (record = this._movesHead; record !== null; record = record._nextMoved) {
- fn(record);
- }
- };
- DefaultIterableDiffer.prototype.forEachRemovedItem = function (fn) {
- var record;
- for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
- fn(record);
- }
- };
- DefaultIterableDiffer.prototype.diff = function (collection) {
- if (lang_2.isBlank(collection))
- collection = [];
- if (!collection_1.isListLikeIterable(collection)) {
- throw new exceptions_1.BaseException("Error trying to diff '" + collection + "'");
- }
- if (this.check(collection)) {
- return this;
- }
- else {
- return null;
- }
- };
- DefaultIterableDiffer.prototype.onDestroy = function () { };
- // todo(vicb): optim for UnmodifiableListView (frozen arrays)
- DefaultIterableDiffer.prototype.check = function (collection) {
- var _this = this;
- this._reset();
- var record = this._itHead;
- var mayBeDirty = false;
- var index;
- var item;
- if (lang_2.isArray(collection)) {
- var list = collection;
- this._length = collection.length;
- for (index = 0; index < this._length; index++) {
- item = list[index];
- if (record === null || !lang_2.looseIdentical(record.item, item)) {
- record = this._mismatch(record, item, index);
- mayBeDirty = true;
- }
- else if (mayBeDirty) {
- // TODO(misko): can we limit this to duplicates only?
- record = this._verifyReinsertion(record, item, index);
- }
- record = record._next;
- }
- }
- else {
- index = 0;
- collection_1.iterateListLike(collection, function (item) {
- if (record === null || !lang_2.looseIdentical(record.item, item)) {
- record = _this._mismatch(record, item, index);
- mayBeDirty = true;
- }
- else if (mayBeDirty) {
- // TODO(misko): can we limit this to duplicates only?
- record = _this._verifyReinsertion(record, item, index);
- }
- record = record._next;
- index++;
- });
- this._length = index;
- }
- this._truncate(record);
- this._collection = collection;
- return this.isDirty;
- };
- Object.defineProperty(DefaultIterableDiffer.prototype, "isDirty", {
- // CollectionChanges is considered dirty if it has any additions, moves or removals.
- get: function () {
- return this._additionsHead !== null || this._movesHead !== null || this._removalsHead !== null;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * Reset the state of the change objects to show no changes. This means set previousKey to
- * currentKey, and clear all of the queues (additions, moves, removals).
- * Set the previousIndexes of moved and added items to their currentIndexes
- * Reset the list of additions, moves and removals
- *
- * @internal
- */
- DefaultIterableDiffer.prototype._reset = function () {
- if (this.isDirty) {
- var record;
- var nextRecord;
- for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
- record._nextPrevious = record._next;
- }
- for (record = this._additionsHead; record !== null; record = record._nextAdded) {
- record.previousIndex = record.currentIndex;
- }
- this._additionsHead = this._additionsTail = null;
- for (record = this._movesHead; record !== null; record = nextRecord) {
- record.previousIndex = record.currentIndex;
- nextRecord = record._nextMoved;
- }
- this._movesHead = this._movesTail = null;
- this._removalsHead = this._removalsTail = null;
- }
- };
- /**
- * This is the core function which handles differences between collections.
- *
- * - `record` is the record which we saw at this position last time. If null then it is a new
- * item.
- * - `item` is the current item in the collection
- * - `index` is the position of the item in the collection
- *
- * @internal
- */
- DefaultIterableDiffer.prototype._mismatch = function (record, item, index) {
- // The previous record after which we will append the current one.
- var previousRecord;
- if (record === null) {
- previousRecord = this._itTail;
- }
- else {
- previousRecord = record._prev;
- // Remove the record from the collection since we know it does not match the item.
- this._remove(record);
- }
- // Attempt to see if we have seen the item before.
- record = this._linkedRecords === null ? null : this._linkedRecords.get(item, index);
- if (record !== null) {
- // We have seen this before, we need to move it forward in the collection.
- this._moveAfter(record, previousRecord, index);
- }
- else {
- // Never seen it, check evicted list.
- record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(item);
- if (record !== null) {
- // It is an item which we have evicted earlier: reinsert it back into the list.
- this._reinsertAfter(record, previousRecord, index);
- }
- else {
- // It is a new item: add it.
- record = this._addAfter(new CollectionChangeRecord(item), previousRecord, index);
- }
- }
- return record;
- };
- /**
- * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
- *
- * Use case: `[a, a]` => `[b, a, a]`
- *
- * If we did not have this check then the insertion of `b` would:
- * 1) evict first `a`
- * 2) insert `b` at `0` index.
- * 3) leave `a` at index `1` as is. <-- this is wrong!
- * 3) reinsert `a` at index 2. <-- this is wrong!
- *
- * The correct behavior is:
- * 1) evict first `a`
- * 2) insert `b` at `0` index.
- * 3) reinsert `a` at index 1.
- * 3) move `a` at from `1` to `2`.
- *
- *
- * Double check that we have not evicted a duplicate item. We need to check if the item type may
- * have already been removed:
- * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
- * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
- * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
- * at the end.
- *
- * @internal
- */
- DefaultIterableDiffer.prototype._verifyReinsertion = function (record, item, index) {
- var reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(item);
- if (reinsertRecord !== null) {
- record = this._reinsertAfter(reinsertRecord, record._prev, index);
- }
- else if (record.currentIndex != index) {
- record.currentIndex = index;
- this._addToMoves(record, index);
- }
- return record;
- };
- /**
- * Get rid of any excess {@link CollectionChangeRecord}s from the previous collection
- *
- * - `record` The first excess {@link CollectionChangeRecord}.
- *
- * @internal
- */
- DefaultIterableDiffer.prototype._truncate = function (record) {
- // Anything after that needs to be removed;
- while (record !== null) {
- var nextRecord = record._next;
- this._addToRemovals(this._unlink(record));
- record = nextRecord;
- }
- if (this._unlinkedRecords !== null) {
- this._unlinkedRecords.clear();
- }
- if (this._additionsTail !== null) {
- this._additionsTail._nextAdded = null;
- }
- if (this._movesTail !== null) {
- this._movesTail._nextMoved = null;
- }
- if (this._itTail !== null) {
- this._itTail._next = null;
- }
- if (this._removalsTail !== null) {
- this._removalsTail._nextRemoved = null;
- }
- };
- /** @internal */
- DefaultIterableDiffer.prototype._reinsertAfter = function (record, prevRecord, index) {
- if (this._unlinkedRecords !== null) {
- this._unlinkedRecords.remove(record);
- }
- var prev = record._prevRemoved;
- var next = record._nextRemoved;
- if (prev === null) {
- this._removalsHead = next;
- }
- else {
- prev._nextRemoved = next;
- }
- if (next === null) {
- this._removalsTail = prev;
- }
- else {
- next._prevRemoved = prev;
- }
- this._insertAfter(record, prevRecord, index);
- this._addToMoves(record, index);
- return record;
- };
- /** @internal */
- DefaultIterableDiffer.prototype._moveAfter = function (record, prevRecord, index) {
- this._unlink(record);
- this._insertAfter(record, prevRecord, index);
- this._addToMoves(record, index);
- return record;
- };
- /** @internal */
- DefaultIterableDiffer.prototype._addAfter = function (record, prevRecord, index) {
- this._insertAfter(record, prevRecord, index);
- if (this._additionsTail === null) {
- // todo(vicb)
- // assert(this._additionsHead === null);
- this._additionsTail = this._additionsHead = record;
- }
- else {
- // todo(vicb)
- // assert(_additionsTail._nextAdded === null);
- // assert(record._nextAdded === null);
- this._additionsTail = this._additionsTail._nextAdded = record;
- }
- return record;
- };
- /** @internal */
- DefaultIterableDiffer.prototype._insertAfter = function (record, prevRecord, index) {
- // todo(vicb)
- // assert(record != prevRecord);
- // assert(record._next === null);
- // assert(record._prev === null);
- var next = prevRecord === null ? this._itHead : prevRecord._next;
- // todo(vicb)
- // assert(next != record);
- // assert(prevRecord != record);
- record._next = next;
- record._prev = prevRecord;
- if (next === null) {
- this._itTail = record;
- }
- else {
- next._prev = record;
- }
- if (prevRecord === null) {
- this._itHead = record;
- }
- else {
- prevRecord._next = record;
- }
- if (this._linkedRecords === null) {
- this._linkedRecords = new _DuplicateMap();
- }
- this._linkedRecords.put(record);
- record.currentIndex = index;
- return record;
- };
- /** @internal */
- DefaultIterableDiffer.prototype._remove = function (record) {
- return this._addToRemovals(this._unlink(record));
- };
- /** @internal */
- DefaultIterableDiffer.prototype._unlink = function (record) {
- if (this._linkedRecords !== null) {
- this._linkedRecords.remove(record);
- }
- var prev = record._prev;
- var next = record._next;
- // todo(vicb)
- // assert((record._prev = null) === null);
- // assert((record._next = null) === null);
- if (prev === null) {
- this._itHead = next;
- }
- else {
- prev._next = next;
- }
- if (next === null) {
- this._itTail = prev;
- }
- else {
- next._prev = prev;
- }
- return record;
- };
- /** @internal */
- DefaultIterableDiffer.prototype._addToMoves = function (record, toIndex) {
- // todo(vicb)
- // assert(record._nextMoved === null);
- if (record.previousIndex === toIndex) {
- return record;
- }
- if (this._movesTail === null) {
- // todo(vicb)
- // assert(_movesHead === null);
- this._movesTail = this._movesHead = record;
- }
- else {
- // todo(vicb)
- // assert(_movesTail._nextMoved === null);
- this._movesTail = this._movesTail._nextMoved = record;
- }
- return record;
- };
- /** @internal */
- DefaultIterableDiffer.prototype._addToRemovals = function (record) {
- if (this._unlinkedRecords === null) {
- this._unlinkedRecords = new _DuplicateMap();
- }
- this._unlinkedRecords.put(record);
- record.currentIndex = null;
- record._nextRemoved = null;
- if (this._removalsTail === null) {
- // todo(vicb)
- // assert(_removalsHead === null);
- this._removalsTail = this._removalsHead = record;
- record._prevRemoved = null;
- }
- else {
- // todo(vicb)
- // assert(_removalsTail._nextRemoved === null);
- // assert(record._nextRemoved === null);
- record._prevRemoved = this._removalsTail;
- this._removalsTail = this._removalsTail._nextRemoved = record;
- }
- return record;
- };
- DefaultIterableDiffer.prototype.toString = function () {
- var record;
- var list = [];
- for (record = this._itHead; record !== null; record = record._next) {
- list.push(record);
- }
- var previous = [];
- for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
- previous.push(record);
- }
- var additions = [];
- for (record = this._additionsHead; record !== null; record = record._nextAdded) {
- additions.push(record);
- }
- var moves = [];
- for (record = this._movesHead; record !== null; record = record._nextMoved) {
- moves.push(record);
- }
- var removals = [];
- for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
- removals.push(record);
- }
- return "collection: " + list.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" +
- "additions: " + additions.join(', ') + "\n" + "moves: " + moves.join(', ') + "\n" +
- "removals: " + removals.join(', ') + "\n";
- };
- return DefaultIterableDiffer;
- })();
- exports.DefaultIterableDiffer = DefaultIterableDiffer;
- var CollectionChangeRecord = (function () {
- function CollectionChangeRecord(item) {
- this.item = item;
- this.currentIndex = null;
- this.previousIndex = null;
- /** @internal */
- this._nextPrevious = null;
- /** @internal */
- this._prev = null;
- /** @internal */
- this._next = null;
- /** @internal */
- this._prevDup = null;
- /** @internal */
- this._nextDup = null;
- /** @internal */
- this._prevRemoved = null;
- /** @internal */
- this._nextRemoved = null;
- /** @internal */
- this._nextAdded = null;
- /** @internal */
- this._nextMoved = null;
- }
- CollectionChangeRecord.prototype.toString = function () {
- return this.previousIndex === this.currentIndex ?
- lang_2.stringify(this.item) :
- lang_2.stringify(this.item) + '[' + lang_2.stringify(this.previousIndex) + '->' +
- lang_2.stringify(this.currentIndex) + ']';
- };
- return CollectionChangeRecord;
- })();
- exports.CollectionChangeRecord = CollectionChangeRecord;
- // A linked list of CollectionChangeRecords with the same CollectionChangeRecord.item
- var _DuplicateItemRecordList = (function () {
- function _DuplicateItemRecordList() {
- /** @internal */
- this._head = null;
- /** @internal */
- this._tail = null;
- }
- /**
- * Append the record to the list of duplicates.
- *
- * Note: by design all records in the list of duplicates hold the same value in record.item.
- */
- _DuplicateItemRecordList.prototype.add = function (record) {
- if (this._head === null) {
- this._head = this._tail = record;
- record._nextDup = null;
- record._prevDup = null;
- }
- else {
- // todo(vicb)
- // assert(record.item == _head.item ||
- // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
- this._tail._nextDup = record;
- record._prevDup = this._tail;
- record._nextDup = null;
- this._tail = record;
- }
- };
- // Returns a CollectionChangeRecord having CollectionChangeRecord.item == item and
- // CollectionChangeRecord.currentIndex >= afterIndex
- _DuplicateItemRecordList.prototype.get = function (item, afterIndex) {
- var record;
- for (record = this._head; record !== null; record = record._nextDup) {
- if ((afterIndex === null || afterIndex < record.currentIndex) &&
- lang_2.looseIdentical(record.item, item)) {
- return record;
- }
- }
- return null;
- };
- /**
- * Remove one {@link CollectionChangeRecord} from the list of duplicates.
- *
- * Returns whether the list of duplicates is empty.
- */
- _DuplicateItemRecordList.prototype.remove = function (record) {
- // todo(vicb)
- // assert(() {
- // // verify that the record being removed is in the list.
- // for (CollectionChangeRecord cursor = _head; cursor != null; cursor = cursor._nextDup) {
- // if (identical(cursor, record)) return true;
- // }
- // return false;
- //});
- var prev = record._prevDup;
- var next = record._nextDup;
- if (prev === null) {
- this._head = next;
- }
- else {
- prev._nextDup = next;
- }
- if (next === null) {
- this._tail = prev;
- }
- else {
- next._prevDup = prev;
- }
- return this._head === null;
- };
- return _DuplicateItemRecordList;
- })();
- var _DuplicateMap = (function () {
- function _DuplicateMap() {
- this.map = new Map();
- }
- _DuplicateMap.prototype.put = function (record) {
- // todo(vicb) handle corner cases
- var key = lang_2.getMapKey(record.item);
- var duplicates = this.map.get(key);
- if (!lang_2.isPresent(duplicates)) {
- duplicates = new _DuplicateItemRecordList();
- this.map.set(key, duplicates);
- }
- duplicates.add(record);
- };
- /**
- * Retrieve the `value` using key. Because the CollectionChangeRecord value maybe one which we
- * have already iterated over, we use the afterIndex to pretend it is not there.
- *
- * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
- * have any more `a`s needs to return the last `a` not the first or second.
- */
- _DuplicateMap.prototype.get = function (value, afterIndex) {
- if (afterIndex === void 0) { afterIndex = null; }
- var key = lang_2.getMapKey(value);
- var recordList = this.map.get(key);
- return lang_2.isBlank(recordList) ? null : recordList.get(value, afterIndex);
- };
- /**
- * Removes a {@link CollectionChangeRecord} from the list of duplicates.
- *
- * The list of duplicates also is removed from the map if it gets empty.
- */
- _DuplicateMap.prototype.remove = function (record) {
- var key = lang_2.getMapKey(record.item);
- // todo(vicb)
- // assert(this.map.containsKey(key));
- var recordList = this.map.get(key);
- // Remove the list of duplicates when it gets empty
- if (recordList.remove(record)) {
- this.map.delete(key);
- }
- return record;
- };
- Object.defineProperty(_DuplicateMap.prototype, "isEmpty", {
- get: function () { return this.map.size === 0; },
- enumerable: true,
- configurable: true
- });
- _DuplicateMap.prototype.clear = function () { this.map.clear(); };
- _DuplicateMap.prototype.toString = function () { return '_DuplicateMap(' + lang_2.stringify(this.map) + ')'; };
- return _DuplicateMap;
- })();
- /***/ },
- /* 28 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var di_1 = __webpack_require__(6);
- /**
- * A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
- */
- var KeyValueDiffers = (function () {
- function KeyValueDiffers(factories) {
- this.factories = factories;
- }
- KeyValueDiffers.create = function (factories, parent) {
- if (lang_1.isPresent(parent)) {
- var copied = collection_1.ListWrapper.clone(parent.factories);
- factories = factories.concat(copied);
- return new KeyValueDiffers(factories);
- }
- else {
- return new KeyValueDiffers(factories);
- }
- };
- /**
- * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
- * inherited {@link KeyValueDiffers} instance with the provided factories and return a new
- * {@link KeyValueDiffers} instance.
- *
- * The following example shows how to extend an existing list of factories,
- * which will only be applied to the injector for this component and its children.
- * This step is all that's required to make a new {@link KeyValueDiffer} available.
- *
- * ### Example
- *
- * ```
- * @Component({
- * viewProviders: [
- * KeyValueDiffers.extend([new ImmutableMapDiffer()])
- * ]
- * })
- * ```
- */
- KeyValueDiffers.extend = function (factories) {
- return new di_1.Provider(KeyValueDiffers, {
- useFactory: function (parent) {
- if (lang_1.isBlank(parent)) {
- // Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
- // to
- // bootstrap(), which would override default pipes instead of extending them.
- throw new exceptions_1.BaseException('Cannot extend KeyValueDiffers without a parent injector');
- }
- return KeyValueDiffers.create(factories, parent);
- },
- // Dependency technically isn't optional, but we can provide a better error message this way.
- deps: [[KeyValueDiffers, new di_1.SkipSelfMetadata(), new di_1.OptionalMetadata()]]
- });
- };
- KeyValueDiffers.prototype.find = function (kv) {
- var factory = this.factories.find(function (f) { return f.supports(kv); });
- if (lang_1.isPresent(factory)) {
- return factory;
- }
- else {
- throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + kv + "'");
- }
- };
- KeyValueDiffers = __decorate([
- di_1.Injectable(),
- lang_1.CONST(),
- __metadata('design:paramtypes', [Array])
- ], KeyValueDiffers);
- return KeyValueDiffers;
- })();
- exports.KeyValueDiffers = KeyValueDiffers;
- /***/ },
- /* 29 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var DefaultKeyValueDifferFactory = (function () {
- function DefaultKeyValueDifferFactory() {
- }
- DefaultKeyValueDifferFactory.prototype.supports = function (obj) { return obj instanceof Map || lang_1.isJsObject(obj); };
- DefaultKeyValueDifferFactory.prototype.create = function (cdRef) { return new DefaultKeyValueDiffer(); };
- DefaultKeyValueDifferFactory = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], DefaultKeyValueDifferFactory);
- return DefaultKeyValueDifferFactory;
- })();
- exports.DefaultKeyValueDifferFactory = DefaultKeyValueDifferFactory;
- var DefaultKeyValueDiffer = (function () {
- function DefaultKeyValueDiffer() {
- this._records = new Map();
- this._mapHead = null;
- this._previousMapHead = null;
- this._changesHead = null;
- this._changesTail = null;
- this._additionsHead = null;
- this._additionsTail = null;
- this._removalsHead = null;
- this._removalsTail = null;
- }
- Object.defineProperty(DefaultKeyValueDiffer.prototype, "isDirty", {
- get: function () {
- return this._additionsHead !== null || this._changesHead !== null ||
- this._removalsHead !== null;
- },
- enumerable: true,
- configurable: true
- });
- DefaultKeyValueDiffer.prototype.forEachItem = function (fn) {
- var record;
- for (record = this._mapHead; record !== null; record = record._next) {
- fn(record);
- }
- };
- DefaultKeyValueDiffer.prototype.forEachPreviousItem = function (fn) {
- var record;
- for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
- fn(record);
- }
- };
- DefaultKeyValueDiffer.prototype.forEachChangedItem = function (fn) {
- var record;
- for (record = this._changesHead; record !== null; record = record._nextChanged) {
- fn(record);
- }
- };
- DefaultKeyValueDiffer.prototype.forEachAddedItem = function (fn) {
- var record;
- for (record = this._additionsHead; record !== null; record = record._nextAdded) {
- fn(record);
- }
- };
- DefaultKeyValueDiffer.prototype.forEachRemovedItem = function (fn) {
- var record;
- for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
- fn(record);
- }
- };
- DefaultKeyValueDiffer.prototype.diff = function (map) {
- if (lang_1.isBlank(map))
- map = collection_1.MapWrapper.createFromPairs([]);
- if (!(map instanceof Map || lang_1.isJsObject(map))) {
- throw new exceptions_1.BaseException("Error trying to diff '" + map + "'");
- }
- if (this.check(map)) {
- return this;
- }
- else {
- return null;
- }
- };
- DefaultKeyValueDiffer.prototype.onDestroy = function () { };
- DefaultKeyValueDiffer.prototype.check = function (map) {
- var _this = this;
- this._reset();
- var records = this._records;
- var oldSeqRecord = this._mapHead;
- var lastOldSeqRecord = null;
- var lastNewSeqRecord = null;
- var seqChanged = false;
- this._forEach(map, function (value, key) {
- var newSeqRecord;
- if (oldSeqRecord !== null && key === oldSeqRecord.key) {
- newSeqRecord = oldSeqRecord;
- if (!lang_1.looseIdentical(value, oldSeqRecord.currentValue)) {
- oldSeqRecord.previousValue = oldSeqRecord.currentValue;
- oldSeqRecord.currentValue = value;
- _this._addToChanges(oldSeqRecord);
- }
- }
- else {
- seqChanged = true;
- if (oldSeqRecord !== null) {
- oldSeqRecord._next = null;
- _this._removeFromSeq(lastOldSeqRecord, oldSeqRecord);
- _this._addToRemovals(oldSeqRecord);
- }
- if (records.has(key)) {
- newSeqRecord = records.get(key);
- }
- else {
- newSeqRecord = new KVChangeRecord(key);
- records.set(key, newSeqRecord);
- newSeqRecord.currentValue = value;
- _this._addToAdditions(newSeqRecord);
- }
- }
- if (seqChanged) {
- if (_this._isInRemovals(newSeqRecord)) {
- _this._removeFromRemovals(newSeqRecord);
- }
- if (lastNewSeqRecord == null) {
- _this._mapHead = newSeqRecord;
- }
- else {
- lastNewSeqRecord._next = newSeqRecord;
- }
- }
- lastOldSeqRecord = oldSeqRecord;
- lastNewSeqRecord = newSeqRecord;
- oldSeqRecord = oldSeqRecord === null ? null : oldSeqRecord._next;
- });
- this._truncate(lastOldSeqRecord, oldSeqRecord);
- return this.isDirty;
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._reset = function () {
- if (this.isDirty) {
- var record;
- // Record the state of the mapping
- for (record = this._previousMapHead = this._mapHead; record !== null; record = record._next) {
- record._nextPrevious = record._next;
- }
- for (record = this._changesHead; record !== null; record = record._nextChanged) {
- record.previousValue = record.currentValue;
- }
- for (record = this._additionsHead; record != null; record = record._nextAdded) {
- record.previousValue = record.currentValue;
- }
- // todo(vicb) once assert is supported
- // assert(() {
- // var r = _changesHead;
- // while (r != null) {
- // var nextRecord = r._nextChanged;
- // r._nextChanged = null;
- // r = nextRecord;
- // }
- //
- // r = _additionsHead;
- // while (r != null) {
- // var nextRecord = r._nextAdded;
- // r._nextAdded = null;
- // r = nextRecord;
- // }
- //
- // r = _removalsHead;
- // while (r != null) {
- // var nextRecord = r._nextRemoved;
- // r._nextRemoved = null;
- // r = nextRecord;
- // }
- //
- // return true;
- //});
- this._changesHead = this._changesTail = null;
- this._additionsHead = this._additionsTail = null;
- this._removalsHead = this._removalsTail = null;
- }
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._truncate = function (lastRecord, record) {
- while (record !== null) {
- if (lastRecord === null) {
- this._mapHead = null;
- }
- else {
- lastRecord._next = null;
- }
- var nextRecord = record._next;
- // todo(vicb) assert
- // assert((() {
- // record._next = null;
- // return true;
- //}));
- this._addToRemovals(record);
- lastRecord = record;
- record = nextRecord;
- }
- for (var rec = this._removalsHead; rec !== null; rec = rec._nextRemoved) {
- rec.previousValue = rec.currentValue;
- rec.currentValue = null;
- this._records.delete(rec.key);
- }
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._isInRemovals = function (record) {
- return record === this._removalsHead || record._nextRemoved !== null ||
- record._prevRemoved !== null;
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._addToRemovals = function (record) {
- // todo(vicb) assert
- // assert(record._next == null);
- // assert(record._nextAdded == null);
- // assert(record._nextChanged == null);
- // assert(record._nextRemoved == null);
- // assert(record._prevRemoved == null);
- if (this._removalsHead === null) {
- this._removalsHead = this._removalsTail = record;
- }
- else {
- this._removalsTail._nextRemoved = record;
- record._prevRemoved = this._removalsTail;
- this._removalsTail = record;
- }
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._removeFromSeq = function (prev, record) {
- var next = record._next;
- if (prev === null) {
- this._mapHead = next;
- }
- else {
- prev._next = next;
- }
- // todo(vicb) assert
- // assert((() {
- // record._next = null;
- // return true;
- //})());
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._removeFromRemovals = function (record) {
- // todo(vicb) assert
- // assert(record._next == null);
- // assert(record._nextAdded == null);
- // assert(record._nextChanged == null);
- var prev = record._prevRemoved;
- var next = record._nextRemoved;
- if (prev === null) {
- this._removalsHead = next;
- }
- else {
- prev._nextRemoved = next;
- }
- if (next === null) {
- this._removalsTail = prev;
- }
- else {
- next._prevRemoved = prev;
- }
- record._prevRemoved = record._nextRemoved = null;
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._addToAdditions = function (record) {
- // todo(vicb): assert
- // assert(record._next == null);
- // assert(record._nextAdded == null);
- // assert(record._nextChanged == null);
- // assert(record._nextRemoved == null);
- // assert(record._prevRemoved == null);
- if (this._additionsHead === null) {
- this._additionsHead = this._additionsTail = record;
- }
- else {
- this._additionsTail._nextAdded = record;
- this._additionsTail = record;
- }
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._addToChanges = function (record) {
- // todo(vicb) assert
- // assert(record._nextAdded == null);
- // assert(record._nextChanged == null);
- // assert(record._nextRemoved == null);
- // assert(record._prevRemoved == null);
- if (this._changesHead === null) {
- this._changesHead = this._changesTail = record;
- }
- else {
- this._changesTail._nextChanged = record;
- this._changesTail = record;
- }
- };
- DefaultKeyValueDiffer.prototype.toString = function () {
- var items = [];
- var previous = [];
- var changes = [];
- var additions = [];
- var removals = [];
- var record;
- for (record = this._mapHead; record !== null; record = record._next) {
- items.push(lang_1.stringify(record));
- }
- for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
- previous.push(lang_1.stringify(record));
- }
- for (record = this._changesHead; record !== null; record = record._nextChanged) {
- changes.push(lang_1.stringify(record));
- }
- for (record = this._additionsHead; record !== null; record = record._nextAdded) {
- additions.push(lang_1.stringify(record));
- }
- for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
- removals.push(lang_1.stringify(record));
- }
- return "map: " + items.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" +
- "additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" +
- "removals: " + removals.join(', ') + "\n";
- };
- /** @internal */
- DefaultKeyValueDiffer.prototype._forEach = function (obj, fn) {
- if (obj instanceof Map) {
- obj.forEach(fn);
- }
- else {
- collection_1.StringMapWrapper.forEach(obj, fn);
- }
- };
- return DefaultKeyValueDiffer;
- })();
- exports.DefaultKeyValueDiffer = DefaultKeyValueDiffer;
- var KVChangeRecord = (function () {
- function KVChangeRecord(key) {
- this.key = key;
- this.previousValue = null;
- this.currentValue = null;
- /** @internal */
- this._nextPrevious = null;
- /** @internal */
- this._next = null;
- /** @internal */
- this._nextAdded = null;
- /** @internal */
- this._nextRemoved = null;
- /** @internal */
- this._prevRemoved = null;
- /** @internal */
- this._nextChanged = null;
- }
- KVChangeRecord.prototype.toString = function () {
- return lang_1.looseIdentical(this.previousValue, this.currentValue) ?
- lang_1.stringify(this.key) :
- (lang_1.stringify(this.key) + '[' + lang_1.stringify(this.previousValue) + '->' +
- lang_1.stringify(this.currentValue) + ']');
- };
- return KVChangeRecord;
- })();
- exports.KVChangeRecord = KVChangeRecord;
- /***/ },
- /* 30 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var AST = (function () {
- function AST() {
- }
- AST.prototype.visit = function (visitor) { return null; };
- AST.prototype.toString = function () { return "AST"; };
- return AST;
- })();
- exports.AST = AST;
- /**
- * Represents a quoted expression of the form:
- *
- * quote = prefix `:` uninterpretedExpression
- * prefix = identifier
- * uninterpretedExpression = arbitrary string
- *
- * A quoted expression is meant to be pre-processed by an AST transformer that
- * converts it into another AST that no longer contains quoted expressions.
- * It is meant to allow third-party developers to extend Angular template
- * expression language. The `uninterpretedExpression` part of the quote is
- * therefore not interpreted by the Angular's own expression parser.
- */
- var Quote = (function (_super) {
- __extends(Quote, _super);
- function Quote(prefix, uninterpretedExpression, location) {
- _super.call(this);
- this.prefix = prefix;
- this.uninterpretedExpression = uninterpretedExpression;
- this.location = location;
- }
- Quote.prototype.visit = function (visitor) { return visitor.visitQuote(this); };
- Quote.prototype.toString = function () { return "Quote"; };
- return Quote;
- })(AST);
- exports.Quote = Quote;
- var EmptyExpr = (function (_super) {
- __extends(EmptyExpr, _super);
- function EmptyExpr() {
- _super.apply(this, arguments);
- }
- EmptyExpr.prototype.visit = function (visitor) {
- // do nothing
- };
- return EmptyExpr;
- })(AST);
- exports.EmptyExpr = EmptyExpr;
- var ImplicitReceiver = (function (_super) {
- __extends(ImplicitReceiver, _super);
- function ImplicitReceiver() {
- _super.apply(this, arguments);
- }
- ImplicitReceiver.prototype.visit = function (visitor) { return visitor.visitImplicitReceiver(this); };
- return ImplicitReceiver;
- })(AST);
- exports.ImplicitReceiver = ImplicitReceiver;
- /**
- * Multiple expressions separated by a semicolon.
- */
- var Chain = (function (_super) {
- __extends(Chain, _super);
- function Chain(expressions) {
- _super.call(this);
- this.expressions = expressions;
- }
- Chain.prototype.visit = function (visitor) { return visitor.visitChain(this); };
- return Chain;
- })(AST);
- exports.Chain = Chain;
- var Conditional = (function (_super) {
- __extends(Conditional, _super);
- function Conditional(condition, trueExp, falseExp) {
- _super.call(this);
- this.condition = condition;
- this.trueExp = trueExp;
- this.falseExp = falseExp;
- }
- Conditional.prototype.visit = function (visitor) { return visitor.visitConditional(this); };
- return Conditional;
- })(AST);
- exports.Conditional = Conditional;
- var PropertyRead = (function (_super) {
- __extends(PropertyRead, _super);
- function PropertyRead(receiver, name, getter) {
- _super.call(this);
- this.receiver = receiver;
- this.name = name;
- this.getter = getter;
- }
- PropertyRead.prototype.visit = function (visitor) { return visitor.visitPropertyRead(this); };
- return PropertyRead;
- })(AST);
- exports.PropertyRead = PropertyRead;
- var PropertyWrite = (function (_super) {
- __extends(PropertyWrite, _super);
- function PropertyWrite(receiver, name, setter, value) {
- _super.call(this);
- this.receiver = receiver;
- this.name = name;
- this.setter = setter;
- this.value = value;
- }
- PropertyWrite.prototype.visit = function (visitor) { return visitor.visitPropertyWrite(this); };
- return PropertyWrite;
- })(AST);
- exports.PropertyWrite = PropertyWrite;
- var SafePropertyRead = (function (_super) {
- __extends(SafePropertyRead, _super);
- function SafePropertyRead(receiver, name, getter) {
- _super.call(this);
- this.receiver = receiver;
- this.name = name;
- this.getter = getter;
- }
- SafePropertyRead.prototype.visit = function (visitor) { return visitor.visitSafePropertyRead(this); };
- return SafePropertyRead;
- })(AST);
- exports.SafePropertyRead = SafePropertyRead;
- var KeyedRead = (function (_super) {
- __extends(KeyedRead, _super);
- function KeyedRead(obj, key) {
- _super.call(this);
- this.obj = obj;
- this.key = key;
- }
- KeyedRead.prototype.visit = function (visitor) { return visitor.visitKeyedRead(this); };
- return KeyedRead;
- })(AST);
- exports.KeyedRead = KeyedRead;
- var KeyedWrite = (function (_super) {
- __extends(KeyedWrite, _super);
- function KeyedWrite(obj, key, value) {
- _super.call(this);
- this.obj = obj;
- this.key = key;
- this.value = value;
- }
- KeyedWrite.prototype.visit = function (visitor) { return visitor.visitKeyedWrite(this); };
- return KeyedWrite;
- })(AST);
- exports.KeyedWrite = KeyedWrite;
- var BindingPipe = (function (_super) {
- __extends(BindingPipe, _super);
- function BindingPipe(exp, name, args) {
- _super.call(this);
- this.exp = exp;
- this.name = name;
- this.args = args;
- }
- BindingPipe.prototype.visit = function (visitor) { return visitor.visitPipe(this); };
- return BindingPipe;
- })(AST);
- exports.BindingPipe = BindingPipe;
- var LiteralPrimitive = (function (_super) {
- __extends(LiteralPrimitive, _super);
- function LiteralPrimitive(value) {
- _super.call(this);
- this.value = value;
- }
- LiteralPrimitive.prototype.visit = function (visitor) { return visitor.visitLiteralPrimitive(this); };
- return LiteralPrimitive;
- })(AST);
- exports.LiteralPrimitive = LiteralPrimitive;
- var LiteralArray = (function (_super) {
- __extends(LiteralArray, _super);
- function LiteralArray(expressions) {
- _super.call(this);
- this.expressions = expressions;
- }
- LiteralArray.prototype.visit = function (visitor) { return visitor.visitLiteralArray(this); };
- return LiteralArray;
- })(AST);
- exports.LiteralArray = LiteralArray;
- var LiteralMap = (function (_super) {
- __extends(LiteralMap, _super);
- function LiteralMap(keys, values) {
- _super.call(this);
- this.keys = keys;
- this.values = values;
- }
- LiteralMap.prototype.visit = function (visitor) { return visitor.visitLiteralMap(this); };
- return LiteralMap;
- })(AST);
- exports.LiteralMap = LiteralMap;
- var Interpolation = (function (_super) {
- __extends(Interpolation, _super);
- function Interpolation(strings, expressions) {
- _super.call(this);
- this.strings = strings;
- this.expressions = expressions;
- }
- Interpolation.prototype.visit = function (visitor) { return visitor.visitInterpolation(this); };
- return Interpolation;
- })(AST);
- exports.Interpolation = Interpolation;
- var Binary = (function (_super) {
- __extends(Binary, _super);
- function Binary(operation, left, right) {
- _super.call(this);
- this.operation = operation;
- this.left = left;
- this.right = right;
- }
- Binary.prototype.visit = function (visitor) { return visitor.visitBinary(this); };
- return Binary;
- })(AST);
- exports.Binary = Binary;
- var PrefixNot = (function (_super) {
- __extends(PrefixNot, _super);
- function PrefixNot(expression) {
- _super.call(this);
- this.expression = expression;
- }
- PrefixNot.prototype.visit = function (visitor) { return visitor.visitPrefixNot(this); };
- return PrefixNot;
- })(AST);
- exports.PrefixNot = PrefixNot;
- var MethodCall = (function (_super) {
- __extends(MethodCall, _super);
- function MethodCall(receiver, name, fn, args) {
- _super.call(this);
- this.receiver = receiver;
- this.name = name;
- this.fn = fn;
- this.args = args;
- }
- MethodCall.prototype.visit = function (visitor) { return visitor.visitMethodCall(this); };
- return MethodCall;
- })(AST);
- exports.MethodCall = MethodCall;
- var SafeMethodCall = (function (_super) {
- __extends(SafeMethodCall, _super);
- function SafeMethodCall(receiver, name, fn, args) {
- _super.call(this);
- this.receiver = receiver;
- this.name = name;
- this.fn = fn;
- this.args = args;
- }
- SafeMethodCall.prototype.visit = function (visitor) { return visitor.visitSafeMethodCall(this); };
- return SafeMethodCall;
- })(AST);
- exports.SafeMethodCall = SafeMethodCall;
- var FunctionCall = (function (_super) {
- __extends(FunctionCall, _super);
- function FunctionCall(target, args) {
- _super.call(this);
- this.target = target;
- this.args = args;
- }
- FunctionCall.prototype.visit = function (visitor) { return visitor.visitFunctionCall(this); };
- return FunctionCall;
- })(AST);
- exports.FunctionCall = FunctionCall;
- var ASTWithSource = (function (_super) {
- __extends(ASTWithSource, _super);
- function ASTWithSource(ast, source, location) {
- _super.call(this);
- this.ast = ast;
- this.source = source;
- this.location = location;
- }
- ASTWithSource.prototype.visit = function (visitor) { return this.ast.visit(visitor); };
- ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; };
- return ASTWithSource;
- })(AST);
- exports.ASTWithSource = ASTWithSource;
- var TemplateBinding = (function () {
- function TemplateBinding(key, keyIsVar, name, expression) {
- this.key = key;
- this.keyIsVar = keyIsVar;
- this.name = name;
- this.expression = expression;
- }
- return TemplateBinding;
- })();
- exports.TemplateBinding = TemplateBinding;
- var RecursiveAstVisitor = (function () {
- function RecursiveAstVisitor() {
- }
- RecursiveAstVisitor.prototype.visitBinary = function (ast) {
- ast.left.visit(this);
- ast.right.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitChain = function (ast) { return this.visitAll(ast.expressions); };
- RecursiveAstVisitor.prototype.visitConditional = function (ast) {
- ast.condition.visit(this);
- ast.trueExp.visit(this);
- ast.falseExp.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitPipe = function (ast) {
- ast.exp.visit(this);
- this.visitAll(ast.args);
- return null;
- };
- RecursiveAstVisitor.prototype.visitFunctionCall = function (ast) {
- ast.target.visit(this);
- this.visitAll(ast.args);
- return null;
- };
- RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast) { return null; };
- RecursiveAstVisitor.prototype.visitInterpolation = function (ast) { return this.visitAll(ast.expressions); };
- RecursiveAstVisitor.prototype.visitKeyedRead = function (ast) {
- ast.obj.visit(this);
- ast.key.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast) {
- ast.obj.visit(this);
- ast.key.visit(this);
- ast.value.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitLiteralArray = function (ast) { return this.visitAll(ast.expressions); };
- RecursiveAstVisitor.prototype.visitLiteralMap = function (ast) { return this.visitAll(ast.values); };
- RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast) { return null; };
- RecursiveAstVisitor.prototype.visitMethodCall = function (ast) {
- ast.receiver.visit(this);
- return this.visitAll(ast.args);
- };
- RecursiveAstVisitor.prototype.visitPrefixNot = function (ast) {
- ast.expression.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitPropertyRead = function (ast) {
- ast.receiver.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast) {
- ast.receiver.visit(this);
- ast.value.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast) {
- ast.receiver.visit(this);
- return null;
- };
- RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast) {
- ast.receiver.visit(this);
- return this.visitAll(ast.args);
- };
- RecursiveAstVisitor.prototype.visitAll = function (asts) {
- var _this = this;
- asts.forEach(function (ast) { return ast.visit(_this); });
- return null;
- };
- RecursiveAstVisitor.prototype.visitQuote = function (ast) { return null; };
- return RecursiveAstVisitor;
- })();
- exports.RecursiveAstVisitor = RecursiveAstVisitor;
- var AstTransformer = (function () {
- function AstTransformer() {
- }
- AstTransformer.prototype.visitImplicitReceiver = function (ast) { return ast; };
- AstTransformer.prototype.visitInterpolation = function (ast) {
- return new Interpolation(ast.strings, this.visitAll(ast.expressions));
- };
- AstTransformer.prototype.visitLiteralPrimitive = function (ast) { return new LiteralPrimitive(ast.value); };
- AstTransformer.prototype.visitPropertyRead = function (ast) {
- return new PropertyRead(ast.receiver.visit(this), ast.name, ast.getter);
- };
- AstTransformer.prototype.visitPropertyWrite = function (ast) {
- return new PropertyWrite(ast.receiver.visit(this), ast.name, ast.setter, ast.value);
- };
- AstTransformer.prototype.visitSafePropertyRead = function (ast) {
- return new SafePropertyRead(ast.receiver.visit(this), ast.name, ast.getter);
- };
- AstTransformer.prototype.visitMethodCall = function (ast) {
- return new MethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args));
- };
- AstTransformer.prototype.visitSafeMethodCall = function (ast) {
- return new SafeMethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args));
- };
- AstTransformer.prototype.visitFunctionCall = function (ast) {
- return new FunctionCall(ast.target.visit(this), this.visitAll(ast.args));
- };
- AstTransformer.prototype.visitLiteralArray = function (ast) {
- return new LiteralArray(this.visitAll(ast.expressions));
- };
- AstTransformer.prototype.visitLiteralMap = function (ast) {
- return new LiteralMap(ast.keys, this.visitAll(ast.values));
- };
- AstTransformer.prototype.visitBinary = function (ast) {
- return new Binary(ast.operation, ast.left.visit(this), ast.right.visit(this));
- };
- AstTransformer.prototype.visitPrefixNot = function (ast) { return new PrefixNot(ast.expression.visit(this)); };
- AstTransformer.prototype.visitConditional = function (ast) {
- return new Conditional(ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
- };
- AstTransformer.prototype.visitPipe = function (ast) {
- return new BindingPipe(ast.exp.visit(this), ast.name, this.visitAll(ast.args));
- };
- AstTransformer.prototype.visitKeyedRead = function (ast) {
- return new KeyedRead(ast.obj.visit(this), ast.key.visit(this));
- };
- AstTransformer.prototype.visitKeyedWrite = function (ast) {
- return new KeyedWrite(ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
- };
- AstTransformer.prototype.visitAll = function (asts) {
- var res = collection_1.ListWrapper.createFixedSize(asts.length);
- for (var i = 0; i < asts.length; ++i) {
- res[i] = asts[i].visit(this);
- }
- return res;
- };
- AstTransformer.prototype.visitChain = function (ast) { return new Chain(this.visitAll(ast.expressions)); };
- AstTransformer.prototype.visitQuote = function (ast) {
- return new Quote(ast.prefix, ast.uninterpretedExpression, ast.location);
- };
- return AstTransformer;
- })();
- exports.AstTransformer = AstTransformer;
- /***/ },
- /* 31 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var decorators_1 = __webpack_require__(8);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- (function (TokenType) {
- TokenType[TokenType["Character"] = 0] = "Character";
- TokenType[TokenType["Identifier"] = 1] = "Identifier";
- TokenType[TokenType["Keyword"] = 2] = "Keyword";
- TokenType[TokenType["String"] = 3] = "String";
- TokenType[TokenType["Operator"] = 4] = "Operator";
- TokenType[TokenType["Number"] = 5] = "Number";
- })(exports.TokenType || (exports.TokenType = {}));
- var TokenType = exports.TokenType;
- var Lexer = (function () {
- function Lexer() {
- }
- Lexer.prototype.tokenize = function (text) {
- var scanner = new _Scanner(text);
- var tokens = [];
- var token = scanner.scanToken();
- while (token != null) {
- tokens.push(token);
- token = scanner.scanToken();
- }
- return tokens;
- };
- Lexer = __decorate([
- decorators_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], Lexer);
- return Lexer;
- })();
- exports.Lexer = Lexer;
- var Token = (function () {
- function Token(index, type, numValue, strValue) {
- this.index = index;
- this.type = type;
- this.numValue = numValue;
- this.strValue = strValue;
- }
- Token.prototype.isCharacter = function (code) {
- return (this.type == TokenType.Character && this.numValue == code);
- };
- Token.prototype.isNumber = function () { return (this.type == TokenType.Number); };
- Token.prototype.isString = function () { return (this.type == TokenType.String); };
- Token.prototype.isOperator = function (operater) {
- return (this.type == TokenType.Operator && this.strValue == operater);
- };
- Token.prototype.isIdentifier = function () { return (this.type == TokenType.Identifier); };
- Token.prototype.isKeyword = function () { return (this.type == TokenType.Keyword); };
- Token.prototype.isKeywordVar = function () { return (this.type == TokenType.Keyword && this.strValue == "var"); };
- Token.prototype.isKeywordNull = function () { return (this.type == TokenType.Keyword && this.strValue == "null"); };
- Token.prototype.isKeywordUndefined = function () {
- return (this.type == TokenType.Keyword && this.strValue == "undefined");
- };
- Token.prototype.isKeywordTrue = function () { return (this.type == TokenType.Keyword && this.strValue == "true"); };
- Token.prototype.isKeywordFalse = function () { return (this.type == TokenType.Keyword && this.strValue == "false"); };
- Token.prototype.toNumber = function () {
- // -1 instead of NULL ok?
- return (this.type == TokenType.Number) ? this.numValue : -1;
- };
- Token.prototype.toString = function () {
- switch (this.type) {
- case TokenType.Character:
- case TokenType.Identifier:
- case TokenType.Keyword:
- case TokenType.Operator:
- case TokenType.String:
- return this.strValue;
- case TokenType.Number:
- return this.numValue.toString();
- default:
- return null;
- }
- };
- return Token;
- })();
- exports.Token = Token;
- function newCharacterToken(index, code) {
- return new Token(index, TokenType.Character, code, lang_1.StringWrapper.fromCharCode(code));
- }
- function newIdentifierToken(index, text) {
- return new Token(index, TokenType.Identifier, 0, text);
- }
- function newKeywordToken(index, text) {
- return new Token(index, TokenType.Keyword, 0, text);
- }
- function newOperatorToken(index, text) {
- return new Token(index, TokenType.Operator, 0, text);
- }
- function newStringToken(index, text) {
- return new Token(index, TokenType.String, 0, text);
- }
- function newNumberToken(index, n) {
- return new Token(index, TokenType.Number, n, "");
- }
- exports.EOF = new Token(-1, TokenType.Character, 0, "");
- exports.$EOF = 0;
- exports.$TAB = 9;
- exports.$LF = 10;
- exports.$VTAB = 11;
- exports.$FF = 12;
- exports.$CR = 13;
- exports.$SPACE = 32;
- exports.$BANG = 33;
- exports.$DQ = 34;
- exports.$HASH = 35;
- exports.$$ = 36;
- exports.$PERCENT = 37;
- exports.$AMPERSAND = 38;
- exports.$SQ = 39;
- exports.$LPAREN = 40;
- exports.$RPAREN = 41;
- exports.$STAR = 42;
- exports.$PLUS = 43;
- exports.$COMMA = 44;
- exports.$MINUS = 45;
- exports.$PERIOD = 46;
- exports.$SLASH = 47;
- exports.$COLON = 58;
- exports.$SEMICOLON = 59;
- exports.$LT = 60;
- exports.$EQ = 61;
- exports.$GT = 62;
- exports.$QUESTION = 63;
- var $0 = 48;
- var $9 = 57;
- var $A = 65, $E = 69, $Z = 90;
- exports.$LBRACKET = 91;
- exports.$BACKSLASH = 92;
- exports.$RBRACKET = 93;
- var $CARET = 94;
- var $_ = 95;
- var $a = 97, $e = 101, $f = 102, $n = 110, $r = 114, $t = 116, $u = 117, $v = 118, $z = 122;
- exports.$LBRACE = 123;
- exports.$BAR = 124;
- exports.$RBRACE = 125;
- var $NBSP = 160;
- var ScannerError = (function (_super) {
- __extends(ScannerError, _super);
- function ScannerError(message) {
- _super.call(this);
- this.message = message;
- }
- ScannerError.prototype.toString = function () { return this.message; };
- return ScannerError;
- })(exceptions_1.BaseException);
- exports.ScannerError = ScannerError;
- var _Scanner = (function () {
- function _Scanner(input) {
- this.input = input;
- this.peek = 0;
- this.index = -1;
- this.length = input.length;
- this.advance();
- }
- _Scanner.prototype.advance = function () {
- this.peek =
- ++this.index >= this.length ? exports.$EOF : lang_1.StringWrapper.charCodeAt(this.input, this.index);
- };
- _Scanner.prototype.scanToken = function () {
- var input = this.input, length = this.length, peek = this.peek, index = this.index;
- // Skip whitespace.
- while (peek <= exports.$SPACE) {
- if (++index >= length) {
- peek = exports.$EOF;
- break;
- }
- else {
- peek = lang_1.StringWrapper.charCodeAt(input, index);
- }
- }
- this.peek = peek;
- this.index = index;
- if (index >= length) {
- return null;
- }
- // Handle identifiers and numbers.
- if (isIdentifierStart(peek))
- return this.scanIdentifier();
- if (isDigit(peek))
- return this.scanNumber(index);
- var start = index;
- switch (peek) {
- case exports.$PERIOD:
- this.advance();
- return isDigit(this.peek) ? this.scanNumber(start) : newCharacterToken(start, exports.$PERIOD);
- case exports.$LPAREN:
- case exports.$RPAREN:
- case exports.$LBRACE:
- case exports.$RBRACE:
- case exports.$LBRACKET:
- case exports.$RBRACKET:
- case exports.$COMMA:
- case exports.$COLON:
- case exports.$SEMICOLON:
- return this.scanCharacter(start, peek);
- case exports.$SQ:
- case exports.$DQ:
- return this.scanString();
- case exports.$HASH:
- case exports.$PLUS:
- case exports.$MINUS:
- case exports.$STAR:
- case exports.$SLASH:
- case exports.$PERCENT:
- case $CARET:
- return this.scanOperator(start, lang_1.StringWrapper.fromCharCode(peek));
- case exports.$QUESTION:
- return this.scanComplexOperator(start, '?', exports.$PERIOD, '.');
- case exports.$LT:
- case exports.$GT:
- return this.scanComplexOperator(start, lang_1.StringWrapper.fromCharCode(peek), exports.$EQ, '=');
- case exports.$BANG:
- case exports.$EQ:
- return this.scanComplexOperator(start, lang_1.StringWrapper.fromCharCode(peek), exports.$EQ, '=', exports.$EQ, '=');
- case exports.$AMPERSAND:
- return this.scanComplexOperator(start, '&', exports.$AMPERSAND, '&');
- case exports.$BAR:
- return this.scanComplexOperator(start, '|', exports.$BAR, '|');
- case $NBSP:
- while (isWhitespace(this.peek))
- this.advance();
- return this.scanToken();
- }
- this.error("Unexpected character [" + lang_1.StringWrapper.fromCharCode(peek) + "]", 0);
- return null;
- };
- _Scanner.prototype.scanCharacter = function (start, code) {
- assert(this.peek == code);
- this.advance();
- return newCharacterToken(start, code);
- };
- _Scanner.prototype.scanOperator = function (start, str) {
- assert(this.peek == lang_1.StringWrapper.charCodeAt(str, 0));
- assert(collection_1.SetWrapper.has(OPERATORS, str));
- this.advance();
- return newOperatorToken(start, str);
- };
- /**
- * Tokenize a 2/3 char long operator
- *
- * @param start start index in the expression
- * @param one first symbol (always part of the operator)
- * @param twoCode code point for the second symbol
- * @param two second symbol (part of the operator when the second code point matches)
- * @param threeCode code point for the third symbol
- * @param three third symbol (part of the operator when provided and matches source expression)
- * @returns {Token}
- */
- _Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
- assert(this.peek == lang_1.StringWrapper.charCodeAt(one, 0));
- this.advance();
- var str = one;
- if (this.peek == twoCode) {
- this.advance();
- str += two;
- }
- if (lang_1.isPresent(threeCode) && this.peek == threeCode) {
- this.advance();
- str += three;
- }
- assert(collection_1.SetWrapper.has(OPERATORS, str));
- return newOperatorToken(start, str);
- };
- _Scanner.prototype.scanIdentifier = function () {
- assert(isIdentifierStart(this.peek));
- var start = this.index;
- this.advance();
- while (isIdentifierPart(this.peek))
- this.advance();
- var str = this.input.substring(start, this.index);
- if (collection_1.SetWrapper.has(KEYWORDS, str)) {
- return newKeywordToken(start, str);
- }
- else {
- return newIdentifierToken(start, str);
- }
- };
- _Scanner.prototype.scanNumber = function (start) {
- assert(isDigit(this.peek));
- var simple = (this.index === start);
- this.advance(); // Skip initial digit.
- while (true) {
- if (isDigit(this.peek)) {
- }
- else if (this.peek == exports.$PERIOD) {
- simple = false;
- }
- else if (isExponentStart(this.peek)) {
- this.advance();
- if (isExponentSign(this.peek))
- this.advance();
- if (!isDigit(this.peek))
- this.error('Invalid exponent', -1);
- simple = false;
- }
- else {
- break;
- }
- this.advance();
- }
- var str = this.input.substring(start, this.index);
- // TODO
- var value = simple ? lang_1.NumberWrapper.parseIntAutoRadix(str) : lang_1.NumberWrapper.parseFloat(str);
- return newNumberToken(start, value);
- };
- _Scanner.prototype.scanString = function () {
- assert(this.peek == exports.$SQ || this.peek == exports.$DQ);
- var start = this.index;
- var quote = this.peek;
- this.advance(); // Skip initial quote.
- var buffer;
- var marker = this.index;
- var input = this.input;
- while (this.peek != quote) {
- if (this.peek == exports.$BACKSLASH) {
- if (buffer == null)
- buffer = new lang_1.StringJoiner();
- buffer.add(input.substring(marker, this.index));
- this.advance();
- var unescapedCode;
- if (this.peek == $u) {
- // 4 character hex code for unicode character.
- var hex = input.substring(this.index + 1, this.index + 5);
- try {
- unescapedCode = lang_1.NumberWrapper.parseInt(hex, 16);
- }
- catch (e) {
- this.error("Invalid unicode escape [\\u" + hex + "]", 0);
- }
- for (var i = 0; i < 5; i++) {
- this.advance();
- }
- }
- else {
- unescapedCode = unescape(this.peek);
- this.advance();
- }
- buffer.add(lang_1.StringWrapper.fromCharCode(unescapedCode));
- marker = this.index;
- }
- else if (this.peek == exports.$EOF) {
- this.error('Unterminated quote', 0);
- }
- else {
- this.advance();
- }
- }
- var last = input.substring(marker, this.index);
- this.advance(); // Skip terminating quote.
- // Compute the unescaped string value.
- var unescaped = last;
- if (buffer != null) {
- buffer.add(last);
- unescaped = buffer.toString();
- }
- return newStringToken(start, unescaped);
- };
- _Scanner.prototype.error = function (message, offset) {
- var position = this.index + offset;
- throw new ScannerError("Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
- };
- return _Scanner;
- })();
- function isWhitespace(code) {
- return (code >= exports.$TAB && code <= exports.$SPACE) || (code == $NBSP);
- }
- function isIdentifierStart(code) {
- return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == exports.$$);
- }
- function isIdentifier(input) {
- if (input.length == 0)
- return false;
- var scanner = new _Scanner(input);
- if (!isIdentifierStart(scanner.peek))
- return false;
- scanner.advance();
- while (scanner.peek !== exports.$EOF) {
- if (!isIdentifierPart(scanner.peek))
- return false;
- scanner.advance();
- }
- return true;
- }
- exports.isIdentifier = isIdentifier;
- function isIdentifierPart(code) {
- return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) ||
- (code == $_) || (code == exports.$$);
- }
- function isDigit(code) {
- return $0 <= code && code <= $9;
- }
- function isExponentStart(code) {
- return code == $e || code == $E;
- }
- function isExponentSign(code) {
- return code == exports.$MINUS || code == exports.$PLUS;
- }
- function unescape(code) {
- switch (code) {
- case $n:
- return exports.$LF;
- case $f:
- return exports.$FF;
- case $r:
- return exports.$CR;
- case $t:
- return exports.$TAB;
- case $v:
- return exports.$VTAB;
- default:
- return code;
- }
- }
- var OPERATORS = collection_1.SetWrapper.createFromList([
- '+',
- '-',
- '*',
- '/',
- '%',
- '^',
- '=',
- '==',
- '!=',
- '===',
- '!==',
- '<',
- '>',
- '<=',
- '>=',
- '&&',
- '||',
- '&',
- '|',
- '!',
- '?',
- '#',
- '?.'
- ]);
- var KEYWORDS = collection_1.SetWrapper.createFromList(['var', 'null', 'undefined', 'true', 'false', 'if', 'else']);
- /***/ },
- /* 32 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var decorators_1 = __webpack_require__(8);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var lexer_1 = __webpack_require__(31);
- var reflection_1 = __webpack_require__(16);
- var ast_1 = __webpack_require__(30);
- var _implicitReceiver = new ast_1.ImplicitReceiver();
- // TODO(tbosch): Cannot make this const/final right now because of the transpiler...
- var INTERPOLATION_REGEXP = /\{\{(.*?)\}\}/g;
- var ParseException = (function (_super) {
- __extends(ParseException, _super);
- function ParseException(message, input, errLocation, ctxLocation) {
- _super.call(this, "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation);
- }
- return ParseException;
- })(exceptions_1.BaseException);
- var Parser = (function () {
- function Parser(/** @internal */ _lexer, providedReflector) {
- if (providedReflector === void 0) { providedReflector = null; }
- this._lexer = _lexer;
- this._reflector = lang_1.isPresent(providedReflector) ? providedReflector : reflection_1.reflector;
- }
- Parser.prototype.parseAction = function (input, location) {
- this._checkNoInterpolation(input, location);
- var tokens = this._lexer.tokenize(input);
- var ast = new _ParseAST(input, location, tokens, this._reflector, true).parseChain();
- return new ast_1.ASTWithSource(ast, input, location);
- };
- Parser.prototype.parseBinding = function (input, location) {
- var ast = this._parseBindingAst(input, location);
- return new ast_1.ASTWithSource(ast, input, location);
- };
- Parser.prototype.parseSimpleBinding = function (input, location) {
- var ast = this._parseBindingAst(input, location);
- if (!SimpleExpressionChecker.check(ast)) {
- throw new ParseException('Host binding expression can only contain field access and constants', input, location);
- }
- return new ast_1.ASTWithSource(ast, input, location);
- };
- Parser.prototype._parseBindingAst = function (input, location) {
- // Quotes expressions use 3rd-party expression language. We don't want to use
- // our lexer or parser for that, so we check for that ahead of time.
- var quote = this._parseQuote(input, location);
- if (lang_1.isPresent(quote)) {
- return quote;
- }
- this._checkNoInterpolation(input, location);
- var tokens = this._lexer.tokenize(input);
- return new _ParseAST(input, location, tokens, this._reflector, false).parseChain();
- };
- Parser.prototype._parseQuote = function (input, location) {
- if (lang_1.isBlank(input))
- return null;
- var prefixSeparatorIndex = input.indexOf(':');
- if (prefixSeparatorIndex == -1)
- return null;
- var prefix = input.substring(0, prefixSeparatorIndex).trim();
- if (!lexer_1.isIdentifier(prefix))
- return null;
- var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
- return new ast_1.Quote(prefix, uninterpretedExpression, location);
- };
- Parser.prototype.parseTemplateBindings = function (input, location) {
- var tokens = this._lexer.tokenize(input);
- return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings();
- };
- Parser.prototype.parseInterpolation = function (input, location) {
- var parts = lang_1.StringWrapper.split(input, INTERPOLATION_REGEXP);
- if (parts.length <= 1) {
- return null;
- }
- var strings = [];
- var expressions = [];
- for (var i = 0; i < parts.length; i++) {
- var part = parts[i];
- if (i % 2 === 0) {
- // fixed string
- strings.push(part);
- }
- else if (part.trim().length > 0) {
- var tokens = this._lexer.tokenize(part);
- var ast = new _ParseAST(input, location, tokens, this._reflector, false).parseChain();
- expressions.push(ast);
- }
- else {
- throw new ParseException('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i) + " in", location);
- }
- }
- return new ast_1.ASTWithSource(new ast_1.Interpolation(strings, expressions), input, location);
- };
- Parser.prototype.wrapLiteralPrimitive = function (input, location) {
- return new ast_1.ASTWithSource(new ast_1.LiteralPrimitive(input), input, location);
- };
- Parser.prototype._checkNoInterpolation = function (input, location) {
- var parts = lang_1.StringWrapper.split(input, INTERPOLATION_REGEXP);
- if (parts.length > 1) {
- throw new ParseException('Got interpolation ({{}}) where expression was expected', input, "at column " + this._findInterpolationErrorColumn(parts, 1) + " in", location);
- }
- };
- Parser.prototype._findInterpolationErrorColumn = function (parts, partInErrIdx) {
- var errLocation = '';
- for (var j = 0; j < partInErrIdx; j++) {
- errLocation += j % 2 === 0 ? parts[j] : "{{" + parts[j] + "}}";
- }
- return errLocation.length;
- };
- Parser = __decorate([
- decorators_1.Injectable(),
- __metadata('design:paramtypes', [lexer_1.Lexer, reflection_1.Reflector])
- ], Parser);
- return Parser;
- })();
- exports.Parser = Parser;
- var _ParseAST = (function () {
- function _ParseAST(input, location, tokens, reflector, parseAction) {
- this.input = input;
- this.location = location;
- this.tokens = tokens;
- this.reflector = reflector;
- this.parseAction = parseAction;
- this.index = 0;
- }
- _ParseAST.prototype.peek = function (offset) {
- var i = this.index + offset;
- return i < this.tokens.length ? this.tokens[i] : lexer_1.EOF;
- };
- Object.defineProperty(_ParseAST.prototype, "next", {
- get: function () { return this.peek(0); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(_ParseAST.prototype, "inputIndex", {
- get: function () {
- return (this.index < this.tokens.length) ? this.next.index : this.input.length;
- },
- enumerable: true,
- configurable: true
- });
- _ParseAST.prototype.advance = function () { this.index++; };
- _ParseAST.prototype.optionalCharacter = function (code) {
- if (this.next.isCharacter(code)) {
- this.advance();
- return true;
- }
- else {
- return false;
- }
- };
- _ParseAST.prototype.optionalKeywordVar = function () {
- if (this.peekKeywordVar()) {
- this.advance();
- return true;
- }
- else {
- return false;
- }
- };
- _ParseAST.prototype.peekKeywordVar = function () { return this.next.isKeywordVar() || this.next.isOperator('#'); };
- _ParseAST.prototype.expectCharacter = function (code) {
- if (this.optionalCharacter(code))
- return;
- this.error("Missing expected " + lang_1.StringWrapper.fromCharCode(code));
- };
- _ParseAST.prototype.optionalOperator = function (op) {
- if (this.next.isOperator(op)) {
- this.advance();
- return true;
- }
- else {
- return false;
- }
- };
- _ParseAST.prototype.expectOperator = function (operator) {
- if (this.optionalOperator(operator))
- return;
- this.error("Missing expected operator " + operator);
- };
- _ParseAST.prototype.expectIdentifierOrKeyword = function () {
- var n = this.next;
- if (!n.isIdentifier() && !n.isKeyword()) {
- this.error("Unexpected token " + n + ", expected identifier or keyword");
- }
- this.advance();
- return n.toString();
- };
- _ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
- var n = this.next;
- if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
- this.error("Unexpected token " + n + ", expected identifier, keyword, or string");
- }
- this.advance();
- return n.toString();
- };
- _ParseAST.prototype.parseChain = function () {
- var exprs = [];
- while (this.index < this.tokens.length) {
- var expr = this.parsePipe();
- exprs.push(expr);
- if (this.optionalCharacter(lexer_1.$SEMICOLON)) {
- if (!this.parseAction) {
- this.error("Binding expression cannot contain chained expression");
- }
- while (this.optionalCharacter(lexer_1.$SEMICOLON)) {
- } // read all semicolons
- }
- else if (this.index < this.tokens.length) {
- this.error("Unexpected token '" + this.next + "'");
- }
- }
- if (exprs.length == 0)
- return new ast_1.EmptyExpr();
- if (exprs.length == 1)
- return exprs[0];
- return new ast_1.Chain(exprs);
- };
- _ParseAST.prototype.parsePipe = function () {
- var result = this.parseExpression();
- if (this.optionalOperator("|")) {
- if (this.parseAction) {
- this.error("Cannot have a pipe in an action expression");
- }
- do {
- var name = this.expectIdentifierOrKeyword();
- var args = [];
- while (this.optionalCharacter(lexer_1.$COLON)) {
- args.push(this.parseExpression());
- }
- result = new ast_1.BindingPipe(result, name, args);
- } while (this.optionalOperator("|"));
- }
- return result;
- };
- _ParseAST.prototype.parseExpression = function () { return this.parseConditional(); };
- _ParseAST.prototype.parseConditional = function () {
- var start = this.inputIndex;
- var result = this.parseLogicalOr();
- if (this.optionalOperator('?')) {
- var yes = this.parsePipe();
- if (!this.optionalCharacter(lexer_1.$COLON)) {
- var end = this.inputIndex;
- var expression = this.input.substring(start, end);
- this.error("Conditional expression " + expression + " requires all 3 expressions");
- }
- var no = this.parsePipe();
- return new ast_1.Conditional(result, yes, no);
- }
- else {
- return result;
- }
- };
- _ParseAST.prototype.parseLogicalOr = function () {
- // '||'
- var result = this.parseLogicalAnd();
- while (this.optionalOperator('||')) {
- result = new ast_1.Binary('||', result, this.parseLogicalAnd());
- }
- return result;
- };
- _ParseAST.prototype.parseLogicalAnd = function () {
- // '&&'
- var result = this.parseEquality();
- while (this.optionalOperator('&&')) {
- result = new ast_1.Binary('&&', result, this.parseEquality());
- }
- return result;
- };
- _ParseAST.prototype.parseEquality = function () {
- // '==','!=','===','!=='
- var result = this.parseRelational();
- while (true) {
- if (this.optionalOperator('==')) {
- result = new ast_1.Binary('==', result, this.parseRelational());
- }
- else if (this.optionalOperator('===')) {
- result = new ast_1.Binary('===', result, this.parseRelational());
- }
- else if (this.optionalOperator('!=')) {
- result = new ast_1.Binary('!=', result, this.parseRelational());
- }
- else if (this.optionalOperator('!==')) {
- result = new ast_1.Binary('!==', result, this.parseRelational());
- }
- else {
- return result;
- }
- }
- };
- _ParseAST.prototype.parseRelational = function () {
- // '<', '>', '<=', '>='
- var result = this.parseAdditive();
- while (true) {
- if (this.optionalOperator('<')) {
- result = new ast_1.Binary('<', result, this.parseAdditive());
- }
- else if (this.optionalOperator('>')) {
- result = new ast_1.Binary('>', result, this.parseAdditive());
- }
- else if (this.optionalOperator('<=')) {
- result = new ast_1.Binary('<=', result, this.parseAdditive());
- }
- else if (this.optionalOperator('>=')) {
- result = new ast_1.Binary('>=', result, this.parseAdditive());
- }
- else {
- return result;
- }
- }
- };
- _ParseAST.prototype.parseAdditive = function () {
- // '+', '-'
- var result = this.parseMultiplicative();
- while (true) {
- if (this.optionalOperator('+')) {
- result = new ast_1.Binary('+', result, this.parseMultiplicative());
- }
- else if (this.optionalOperator('-')) {
- result = new ast_1.Binary('-', result, this.parseMultiplicative());
- }
- else {
- return result;
- }
- }
- };
- _ParseAST.prototype.parseMultiplicative = function () {
- // '*', '%', '/'
- var result = this.parsePrefix();
- while (true) {
- if (this.optionalOperator('*')) {
- result = new ast_1.Binary('*', result, this.parsePrefix());
- }
- else if (this.optionalOperator('%')) {
- result = new ast_1.Binary('%', result, this.parsePrefix());
- }
- else if (this.optionalOperator('/')) {
- result = new ast_1.Binary('/', result, this.parsePrefix());
- }
- else {
- return result;
- }
- }
- };
- _ParseAST.prototype.parsePrefix = function () {
- if (this.optionalOperator('+')) {
- return this.parsePrefix();
- }
- else if (this.optionalOperator('-')) {
- return new ast_1.Binary('-', new ast_1.LiteralPrimitive(0), this.parsePrefix());
- }
- else if (this.optionalOperator('!')) {
- return new ast_1.PrefixNot(this.parsePrefix());
- }
- else {
- return this.parseCallChain();
- }
- };
- _ParseAST.prototype.parseCallChain = function () {
- var result = this.parsePrimary();
- while (true) {
- if (this.optionalCharacter(lexer_1.$PERIOD)) {
- result = this.parseAccessMemberOrMethodCall(result, false);
- }
- else if (this.optionalOperator('?.')) {
- result = this.parseAccessMemberOrMethodCall(result, true);
- }
- else if (this.optionalCharacter(lexer_1.$LBRACKET)) {
- var key = this.parsePipe();
- this.expectCharacter(lexer_1.$RBRACKET);
- if (this.optionalOperator("=")) {
- var value = this.parseConditional();
- result = new ast_1.KeyedWrite(result, key, value);
- }
- else {
- result = new ast_1.KeyedRead(result, key);
- }
- }
- else if (this.optionalCharacter(lexer_1.$LPAREN)) {
- var args = this.parseCallArguments();
- this.expectCharacter(lexer_1.$RPAREN);
- result = new ast_1.FunctionCall(result, args);
- }
- else {
- return result;
- }
- }
- };
- _ParseAST.prototype.parsePrimary = function () {
- if (this.optionalCharacter(lexer_1.$LPAREN)) {
- var result = this.parsePipe();
- this.expectCharacter(lexer_1.$RPAREN);
- return result;
- }
- else if (this.next.isKeywordNull() || this.next.isKeywordUndefined()) {
- this.advance();
- return new ast_1.LiteralPrimitive(null);
- }
- else if (this.next.isKeywordTrue()) {
- this.advance();
- return new ast_1.LiteralPrimitive(true);
- }
- else if (this.next.isKeywordFalse()) {
- this.advance();
- return new ast_1.LiteralPrimitive(false);
- }
- else if (this.optionalCharacter(lexer_1.$LBRACKET)) {
- var elements = this.parseExpressionList(lexer_1.$RBRACKET);
- this.expectCharacter(lexer_1.$RBRACKET);
- return new ast_1.LiteralArray(elements);
- }
- else if (this.next.isCharacter(lexer_1.$LBRACE)) {
- return this.parseLiteralMap();
- }
- else if (this.next.isIdentifier()) {
- return this.parseAccessMemberOrMethodCall(_implicitReceiver, false);
- }
- else if (this.next.isNumber()) {
- var value = this.next.toNumber();
- this.advance();
- return new ast_1.LiteralPrimitive(value);
- }
- else if (this.next.isString()) {
- var literalValue = this.next.toString();
- this.advance();
- return new ast_1.LiteralPrimitive(literalValue);
- }
- else if (this.index >= this.tokens.length) {
- this.error("Unexpected end of expression: " + this.input);
- }
- else {
- this.error("Unexpected token " + this.next);
- }
- // error() throws, so we don't reach here.
- throw new exceptions_1.BaseException("Fell through all cases in parsePrimary");
- };
- _ParseAST.prototype.parseExpressionList = function (terminator) {
- var result = [];
- if (!this.next.isCharacter(terminator)) {
- do {
- result.push(this.parsePipe());
- } while (this.optionalCharacter(lexer_1.$COMMA));
- }
- return result;
- };
- _ParseAST.prototype.parseLiteralMap = function () {
- var keys = [];
- var values = [];
- this.expectCharacter(lexer_1.$LBRACE);
- if (!this.optionalCharacter(lexer_1.$RBRACE)) {
- do {
- var key = this.expectIdentifierOrKeywordOrString();
- keys.push(key);
- this.expectCharacter(lexer_1.$COLON);
- values.push(this.parsePipe());
- } while (this.optionalCharacter(lexer_1.$COMMA));
- this.expectCharacter(lexer_1.$RBRACE);
- }
- return new ast_1.LiteralMap(keys, values);
- };
- _ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, isSafe) {
- if (isSafe === void 0) { isSafe = false; }
- var id = this.expectIdentifierOrKeyword();
- if (this.optionalCharacter(lexer_1.$LPAREN)) {
- var args = this.parseCallArguments();
- this.expectCharacter(lexer_1.$RPAREN);
- var fn = this.reflector.method(id);
- return isSafe ? new ast_1.SafeMethodCall(receiver, id, fn, args) :
- new ast_1.MethodCall(receiver, id, fn, args);
- }
- else {
- if (isSafe) {
- if (this.optionalOperator("=")) {
- this.error("The '?.' operator cannot be used in the assignment");
- }
- else {
- return new ast_1.SafePropertyRead(receiver, id, this.reflector.getter(id));
- }
- }
- else {
- if (this.optionalOperator("=")) {
- if (!this.parseAction) {
- this.error("Bindings cannot contain assignments");
- }
- var value = this.parseConditional();
- return new ast_1.PropertyWrite(receiver, id, this.reflector.setter(id), value);
- }
- else {
- return new ast_1.PropertyRead(receiver, id, this.reflector.getter(id));
- }
- }
- }
- return null;
- };
- _ParseAST.prototype.parseCallArguments = function () {
- if (this.next.isCharacter(lexer_1.$RPAREN))
- return [];
- var positionals = [];
- do {
- positionals.push(this.parsePipe());
- } while (this.optionalCharacter(lexer_1.$COMMA));
- return positionals;
- };
- _ParseAST.prototype.parseBlockContent = function () {
- if (!this.parseAction) {
- this.error("Binding expression cannot contain chained expression");
- }
- var exprs = [];
- while (this.index < this.tokens.length && !this.next.isCharacter(lexer_1.$RBRACE)) {
- var expr = this.parseExpression();
- exprs.push(expr);
- if (this.optionalCharacter(lexer_1.$SEMICOLON)) {
- while (this.optionalCharacter(lexer_1.$SEMICOLON)) {
- } // read all semicolons
- }
- }
- if (exprs.length == 0)
- return new ast_1.EmptyExpr();
- if (exprs.length == 1)
- return exprs[0];
- return new ast_1.Chain(exprs);
- };
- /**
- * An identifier, a keyword, a string with an optional `-` inbetween.
- */
- _ParseAST.prototype.expectTemplateBindingKey = function () {
- var result = '';
- var operatorFound = false;
- do {
- result += this.expectIdentifierOrKeywordOrString();
- operatorFound = this.optionalOperator('-');
- if (operatorFound) {
- result += '-';
- }
- } while (operatorFound);
- return result.toString();
- };
- _ParseAST.prototype.parseTemplateBindings = function () {
- var bindings = [];
- var prefix = null;
- while (this.index < this.tokens.length) {
- var keyIsVar = this.optionalKeywordVar();
- var key = this.expectTemplateBindingKey();
- if (!keyIsVar) {
- if (prefix == null) {
- prefix = key;
- }
- else {
- key = prefix + key[0].toUpperCase() + key.substring(1);
- }
- }
- this.optionalCharacter(lexer_1.$COLON);
- var name = null;
- var expression = null;
- if (keyIsVar) {
- if (this.optionalOperator("=")) {
- name = this.expectTemplateBindingKey();
- }
- else {
- name = '\$implicit';
- }
- }
- else if (this.next !== lexer_1.EOF && !this.peekKeywordVar()) {
- var start = this.inputIndex;
- var ast = this.parsePipe();
- var source = this.input.substring(start, this.inputIndex);
- expression = new ast_1.ASTWithSource(ast, source, this.location);
- }
- bindings.push(new ast_1.TemplateBinding(key, keyIsVar, name, expression));
- if (!this.optionalCharacter(lexer_1.$SEMICOLON)) {
- this.optionalCharacter(lexer_1.$COMMA);
- }
- }
- return bindings;
- };
- _ParseAST.prototype.error = function (message, index) {
- if (index === void 0) { index = null; }
- if (lang_1.isBlank(index))
- index = this.index;
- var location = (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
- "at the end of the expression";
- throw new ParseException(message, this.input, location, this.location);
- };
- return _ParseAST;
- })();
- exports._ParseAST = _ParseAST;
- var SimpleExpressionChecker = (function () {
- function SimpleExpressionChecker() {
- this.simple = true;
- }
- SimpleExpressionChecker.check = function (ast) {
- var s = new SimpleExpressionChecker();
- ast.visit(s);
- return s.simple;
- };
- SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast) { };
- SimpleExpressionChecker.prototype.visitInterpolation = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast) { };
- SimpleExpressionChecker.prototype.visitPropertyRead = function (ast) { };
- SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitMethodCall = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitFunctionCall = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitLiteralArray = function (ast) { this.visitAll(ast.expressions); };
- SimpleExpressionChecker.prototype.visitLiteralMap = function (ast) { this.visitAll(ast.values); };
- SimpleExpressionChecker.prototype.visitBinary = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitPrefixNot = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitConditional = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitPipe = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitKeyedRead = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitAll = function (asts) {
- var res = collection_1.ListWrapper.createFixedSize(asts.length);
- for (var i = 0; i < asts.length; ++i) {
- res[i] = asts[i].visit(this);
- }
- return res;
- };
- SimpleExpressionChecker.prototype.visitChain = function (ast) { this.simple = false; };
- SimpleExpressionChecker.prototype.visitQuote = function (ast) { this.simple = false; };
- return SimpleExpressionChecker;
- })();
- /***/ },
- /* 33 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var Locals = (function () {
- function Locals(parent, current) {
- this.parent = parent;
- this.current = current;
- }
- Locals.prototype.contains = function (name) {
- if (this.current.has(name)) {
- return true;
- }
- if (lang_1.isPresent(this.parent)) {
- return this.parent.contains(name);
- }
- return false;
- };
- Locals.prototype.get = function (name) {
- if (this.current.has(name)) {
- return this.current.get(name);
- }
- if (lang_1.isPresent(this.parent)) {
- return this.parent.get(name);
- }
- throw new exceptions_1.BaseException("Cannot find '" + name + "'");
- };
- Locals.prototype.set = function (name, value) {
- // TODO(rado): consider removing this check if we can guarantee this is not
- // exposed to the public API.
- // TODO: vsavkin maybe it should check only the local map
- if (this.current.has(name)) {
- this.current.set(name, value);
- }
- else {
- throw new exceptions_1.BaseException("Setting of new keys post-construction is not supported. Key: " + name + ".");
- }
- };
- Locals.prototype.clearValues = function () { collection_1.MapWrapper.clearValues(this.current); };
- return Locals;
- })();
- exports.Locals = Locals;
- /***/ },
- /* 34 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var exceptions_1 = __webpack_require__(14);
- /**
- * An error thrown if application changes model breaking the top-down data flow.
- *
- * This exception is only thrown in dev mode.
- *
- * <!-- TODO: Add a link once the dev mode option is configurable -->
- *
- * ### Example
- *
- * ```typescript
- * @Component({
- * selector: 'parent',
- * template: `
- * <child [prop]="parentProp"></child>
- * `,
- * directives: [forwardRef(() => Child)]
- * })
- * class Parent {
- * parentProp = "init";
- * }
- *
- * @Directive({selector: 'child', inputs: ['prop']})
- * class Child {
- * constructor(public parent: Parent) {}
- *
- * set prop(v) {
- * // this updates the parent property, which is disallowed during change detection
- * // this will result in ExpressionChangedAfterItHasBeenCheckedException
- * this.parent.parentProp = "updated";
- * }
- * }
- * ```
- */
- var ExpressionChangedAfterItHasBeenCheckedException = (function (_super) {
- __extends(ExpressionChangedAfterItHasBeenCheckedException, _super);
- function ExpressionChangedAfterItHasBeenCheckedException(exp, oldValue, currValue, context) {
- _super.call(this, ("Expression '" + exp + "' has changed after it was checked. ") +
- ("Previous value: '" + oldValue + "'. Current value: '" + currValue + "'"));
- }
- return ExpressionChangedAfterItHasBeenCheckedException;
- })(exceptions_1.BaseException);
- exports.ExpressionChangedAfterItHasBeenCheckedException = ExpressionChangedAfterItHasBeenCheckedException;
- /**
- * Thrown when an expression evaluation raises an exception.
- *
- * This error wraps the original exception to attach additional contextual information that can
- * be useful for debugging.
- *
- * ### Example ([live demo](http://plnkr.co/edit/2Kywoz?p=preview))
- *
- * ```typescript
- * @Directive({selector: 'child', inputs: ['prop']})
- * class Child {
- * prop;
- * }
- *
- * @Component({
- * selector: 'app',
- * template: `
- * <child [prop]="field.first"></child>
- * `,
- * directives: [Child]
- * })
- * class App {
- * field = null;
- * }
- *
- * bootstrap(App);
- * ```
- *
- * You can access the original exception and stack through the `originalException` and
- * `originalStack` properties.
- */
- var ChangeDetectionError = (function (_super) {
- __extends(ChangeDetectionError, _super);
- function ChangeDetectionError(exp, originalException, originalStack, context) {
- _super.call(this, originalException + " in [" + exp + "]", originalException, originalStack, context);
- this.location = exp;
- }
- return ChangeDetectionError;
- })(exceptions_1.WrappedException);
- exports.ChangeDetectionError = ChangeDetectionError;
- /**
- * Thrown when change detector executes on dehydrated view.
- *
- * This error indicates a bug in the framework.
- *
- * This is an internal Angular error.
- */
- var DehydratedException = (function (_super) {
- __extends(DehydratedException, _super);
- function DehydratedException() {
- _super.call(this, 'Attempt to detect changes on a dehydrated detector.');
- }
- return DehydratedException;
- })(exceptions_1.BaseException);
- exports.DehydratedException = DehydratedException;
- /***/ },
- /* 35 */
- /***/ function(module, exports) {
- var DebugContext = (function () {
- function DebugContext(element, componentElement, directive, context, locals, injector) {
- this.element = element;
- this.componentElement = componentElement;
- this.directive = directive;
- this.context = context;
- this.locals = locals;
- this.injector = injector;
- }
- return DebugContext;
- })();
- exports.DebugContext = DebugContext;
- var ChangeDetectorGenConfig = (function () {
- function ChangeDetectorGenConfig(genDebugInfo, logBindingUpdate, useJit) {
- this.genDebugInfo = genDebugInfo;
- this.logBindingUpdate = logBindingUpdate;
- this.useJit = useJit;
- }
- return ChangeDetectorGenConfig;
- })();
- exports.ChangeDetectorGenConfig = ChangeDetectorGenConfig;
- var ChangeDetectorDefinition = (function () {
- function ChangeDetectorDefinition(id, strategy, variableNames, bindingRecords, eventRecords, directiveRecords, genConfig) {
- this.id = id;
- this.strategy = strategy;
- this.variableNames = variableNames;
- this.bindingRecords = bindingRecords;
- this.eventRecords = eventRecords;
- this.directiveRecords = directiveRecords;
- this.genConfig = genConfig;
- }
- return ChangeDetectorDefinition;
- })();
- exports.ChangeDetectorDefinition = ChangeDetectorDefinition;
- /***/ },
- /* 36 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- /**
- * Describes the current state of the change detector.
- */
- (function (ChangeDetectorState) {
- /**
- * `NeverChecked` means that the change detector has not been checked yet, and
- * initialization methods should be called during detection.
- */
- ChangeDetectorState[ChangeDetectorState["NeverChecked"] = 0] = "NeverChecked";
- /**
- * `CheckedBefore` means that the change detector has successfully completed at least
- * one detection previously.
- */
- ChangeDetectorState[ChangeDetectorState["CheckedBefore"] = 1] = "CheckedBefore";
- /**
- * `Errored` means that the change detector encountered an error checking a binding
- * or calling a directive lifecycle method and is now in an inconsistent state. Change
- * detectors in this state will no longer detect changes.
- */
- ChangeDetectorState[ChangeDetectorState["Errored"] = 2] = "Errored";
- })(exports.ChangeDetectorState || (exports.ChangeDetectorState = {}));
- var ChangeDetectorState = exports.ChangeDetectorState;
- /**
- * Describes within the change detector which strategy will be used the next time change
- * detection is triggered.
- */
- (function (ChangeDetectionStrategy) {
- /**
- * `CheckedOnce` means that after calling detectChanges the mode of the change detector
- * will become `Checked`.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["CheckOnce"] = 0] = "CheckOnce";
- /**
- * `Checked` means that the change detector should be skipped until its mode changes to
- * `CheckOnce`.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["Checked"] = 1] = "Checked";
- /**
- * `CheckAlways` means that after calling detectChanges the mode of the change detector
- * will remain `CheckAlways`.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["CheckAlways"] = 2] = "CheckAlways";
- /**
- * `Detached` means that the change detector sub tree is not a part of the main tree and
- * should be skipped.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["Detached"] = 3] = "Detached";
- /**
- * `OnPush` means that the change detector's mode will be set to `CheckOnce` during hydration.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 4] = "OnPush";
- /**
- * `Default` means that the change detector's mode will be set to `CheckAlways` during hydration.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 5] = "Default";
- /**
- * This is an experimental feature. Works only in Dart.
- */
- ChangeDetectionStrategy[ChangeDetectionStrategy["OnPushObserve"] = 6] = "OnPushObserve";
- })(exports.ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = {}));
- var ChangeDetectionStrategy = exports.ChangeDetectionStrategy;
- /**
- * List of possible {@link ChangeDetectionStrategy} values.
- */
- exports.CHANGE_DETECTION_STRATEGY_VALUES = [
- ChangeDetectionStrategy.CheckOnce,
- ChangeDetectionStrategy.Checked,
- ChangeDetectionStrategy.CheckAlways,
- ChangeDetectionStrategy.Detached,
- ChangeDetectionStrategy.OnPush,
- ChangeDetectionStrategy.Default,
- ChangeDetectionStrategy.OnPushObserve
- ];
- /**
- * List of possible {@link ChangeDetectorState} values.
- */
- exports.CHANGE_DETECTOR_STATE_VALUES = [
- ChangeDetectorState.NeverChecked,
- ChangeDetectorState.CheckedBefore,
- ChangeDetectorState.Errored
- ];
- function isDefaultChangeDetectionStrategy(changeDetectionStrategy) {
- return lang_1.isBlank(changeDetectionStrategy) ||
- changeDetectionStrategy === ChangeDetectionStrategy.Default;
- }
- exports.isDefaultChangeDetectionStrategy = isDefaultChangeDetectionStrategy;
- /***/ },
- /* 37 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var ast_1 = __webpack_require__(30);
- var change_detection_util_1 = __webpack_require__(38);
- var dynamic_change_detector_1 = __webpack_require__(42);
- var directive_record_1 = __webpack_require__(41);
- var event_binding_1 = __webpack_require__(49);
- var coalesce_1 = __webpack_require__(50);
- var proto_record_1 = __webpack_require__(48);
- var DynamicProtoChangeDetector = (function () {
- function DynamicProtoChangeDetector(_definition) {
- this._definition = _definition;
- this._propertyBindingRecords = createPropertyRecords(_definition);
- this._eventBindingRecords = createEventRecords(_definition);
- this._propertyBindingTargets = this._definition.bindingRecords.map(function (b) { return b.target; });
- this._directiveIndices = this._definition.directiveRecords.map(function (d) { return d.directiveIndex; });
- }
- DynamicProtoChangeDetector.prototype.instantiate = function (dispatcher) {
- return new dynamic_change_detector_1.DynamicChangeDetector(this._definition.id, dispatcher, this._propertyBindingRecords.length, this._propertyBindingTargets, this._directiveIndices, this._definition.strategy, this._propertyBindingRecords, this._eventBindingRecords, this._definition.directiveRecords, this._definition.genConfig);
- };
- return DynamicProtoChangeDetector;
- })();
- exports.DynamicProtoChangeDetector = DynamicProtoChangeDetector;
- function createPropertyRecords(definition) {
- var recordBuilder = new ProtoRecordBuilder();
- collection_1.ListWrapper.forEachWithIndex(definition.bindingRecords, function (b, index) { return recordBuilder.add(b, definition.variableNames, index); });
- return coalesce_1.coalesce(recordBuilder.records);
- }
- exports.createPropertyRecords = createPropertyRecords;
- function createEventRecords(definition) {
- // TODO: vsavkin: remove $event when the compiler handles render-side variables properly
- var varNames = collection_1.ListWrapper.concat(['$event'], definition.variableNames);
- return definition.eventRecords.map(function (er) {
- var records = _ConvertAstIntoProtoRecords.create(er, varNames);
- var dirIndex = er.implicitReceiver instanceof directive_record_1.DirectiveIndex ? er.implicitReceiver : null;
- return new event_binding_1.EventBinding(er.target.name, er.target.elementIndex, dirIndex, records);
- });
- }
- exports.createEventRecords = createEventRecords;
- var ProtoRecordBuilder = (function () {
- function ProtoRecordBuilder() {
- this.records = [];
- }
- ProtoRecordBuilder.prototype.add = function (b, variableNames, bindingIndex) {
- var oldLast = collection_1.ListWrapper.last(this.records);
- if (lang_1.isPresent(oldLast) && oldLast.bindingRecord.directiveRecord == b.directiveRecord) {
- oldLast.lastInDirective = false;
- }
- var numberOfRecordsBefore = this.records.length;
- this._appendRecords(b, variableNames, bindingIndex);
- var newLast = collection_1.ListWrapper.last(this.records);
- if (lang_1.isPresent(newLast) && newLast !== oldLast) {
- newLast.lastInBinding = true;
- newLast.lastInDirective = true;
- this._setArgumentToPureFunction(numberOfRecordsBefore);
- }
- };
- /** @internal */
- ProtoRecordBuilder.prototype._setArgumentToPureFunction = function (startIndex) {
- var _this = this;
- for (var i = startIndex; i < this.records.length; ++i) {
- var rec = this.records[i];
- if (rec.isPureFunction()) {
- rec.args.forEach(function (recordIndex) { return _this.records[recordIndex - 1].argumentToPureFunction =
- true; });
- }
- if (rec.mode === proto_record_1.RecordType.Pipe) {
- rec.args.forEach(function (recordIndex) { return _this.records[recordIndex - 1].argumentToPureFunction =
- true; });
- this.records[rec.contextIndex - 1].argumentToPureFunction = true;
- }
- }
- };
- /** @internal */
- ProtoRecordBuilder.prototype._appendRecords = function (b, variableNames, bindingIndex) {
- if (b.isDirectiveLifecycle()) {
- this.records.push(new proto_record_1.ProtoRecord(proto_record_1.RecordType.DirectiveLifecycle, b.lifecycleEvent, null, [], [], -1, null, this.records.length + 1, b, false, false, false, false, null));
- }
- else {
- _ConvertAstIntoProtoRecords.append(this.records, b, variableNames, bindingIndex);
- }
- };
- return ProtoRecordBuilder;
- })();
- exports.ProtoRecordBuilder = ProtoRecordBuilder;
- var _ConvertAstIntoProtoRecords = (function () {
- function _ConvertAstIntoProtoRecords(_records, _bindingRecord, _variableNames, _bindingIndex) {
- this._records = _records;
- this._bindingRecord = _bindingRecord;
- this._variableNames = _variableNames;
- this._bindingIndex = _bindingIndex;
- }
- _ConvertAstIntoProtoRecords.append = function (records, b, variableNames, bindingIndex) {
- var c = new _ConvertAstIntoProtoRecords(records, b, variableNames, bindingIndex);
- b.ast.visit(c);
- };
- _ConvertAstIntoProtoRecords.create = function (b, variableNames) {
- var rec = [];
- _ConvertAstIntoProtoRecords.append(rec, b, variableNames, null);
- rec[rec.length - 1].lastInBinding = true;
- return rec;
- };
- _ConvertAstIntoProtoRecords.prototype.visitImplicitReceiver = function (ast) { return this._bindingRecord.implicitReceiver; };
- _ConvertAstIntoProtoRecords.prototype.visitInterpolation = function (ast) {
- var args = this._visitAll(ast.expressions);
- return this._addRecord(proto_record_1.RecordType.Interpolate, "interpolate", _interpolationFn(ast.strings), args, ast.strings, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitLiteralPrimitive = function (ast) {
- return this._addRecord(proto_record_1.RecordType.Const, "literal", ast.value, [], null, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitPropertyRead = function (ast) {
- var receiver = ast.receiver.visit(this);
- if (lang_1.isPresent(this._variableNames) && collection_1.ListWrapper.contains(this._variableNames, ast.name) &&
- ast.receiver instanceof ast_1.ImplicitReceiver) {
- return this._addRecord(proto_record_1.RecordType.Local, ast.name, ast.name, [], null, receiver);
- }
- else {
- return this._addRecord(proto_record_1.RecordType.PropertyRead, ast.name, ast.getter, [], null, receiver);
- }
- };
- _ConvertAstIntoProtoRecords.prototype.visitPropertyWrite = function (ast) {
- if (lang_1.isPresent(this._variableNames) && collection_1.ListWrapper.contains(this._variableNames, ast.name) &&
- ast.receiver instanceof ast_1.ImplicitReceiver) {
- throw new exceptions_1.BaseException("Cannot reassign a variable binding " + ast.name);
- }
- else {
- var receiver = ast.receiver.visit(this);
- var value = ast.value.visit(this);
- return this._addRecord(proto_record_1.RecordType.PropertyWrite, ast.name, ast.setter, [value], null, receiver);
- }
- };
- _ConvertAstIntoProtoRecords.prototype.visitKeyedWrite = function (ast) {
- var obj = ast.obj.visit(this);
- var key = ast.key.visit(this);
- var value = ast.value.visit(this);
- return this._addRecord(proto_record_1.RecordType.KeyedWrite, null, null, [key, value], null, obj);
- };
- _ConvertAstIntoProtoRecords.prototype.visitSafePropertyRead = function (ast) {
- var receiver = ast.receiver.visit(this);
- return this._addRecord(proto_record_1.RecordType.SafeProperty, ast.name, ast.getter, [], null, receiver);
- };
- _ConvertAstIntoProtoRecords.prototype.visitMethodCall = function (ast) {
- var receiver = ast.receiver.visit(this);
- var args = this._visitAll(ast.args);
- if (lang_1.isPresent(this._variableNames) && collection_1.ListWrapper.contains(this._variableNames, ast.name)) {
- var target = this._addRecord(proto_record_1.RecordType.Local, ast.name, ast.name, [], null, receiver);
- return this._addRecord(proto_record_1.RecordType.InvokeClosure, "closure", null, args, null, target);
- }
- else {
- return this._addRecord(proto_record_1.RecordType.InvokeMethod, ast.name, ast.fn, args, null, receiver);
- }
- };
- _ConvertAstIntoProtoRecords.prototype.visitSafeMethodCall = function (ast) {
- var receiver = ast.receiver.visit(this);
- var args = this._visitAll(ast.args);
- return this._addRecord(proto_record_1.RecordType.SafeMethodInvoke, ast.name, ast.fn, args, null, receiver);
- };
- _ConvertAstIntoProtoRecords.prototype.visitFunctionCall = function (ast) {
- var target = ast.target.visit(this);
- var args = this._visitAll(ast.args);
- return this._addRecord(proto_record_1.RecordType.InvokeClosure, "closure", null, args, null, target);
- };
- _ConvertAstIntoProtoRecords.prototype.visitLiteralArray = function (ast) {
- var primitiveName = "arrayFn" + ast.expressions.length;
- return this._addRecord(proto_record_1.RecordType.CollectionLiteral, primitiveName, _arrayFn(ast.expressions.length), this._visitAll(ast.expressions), null, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitLiteralMap = function (ast) {
- return this._addRecord(proto_record_1.RecordType.CollectionLiteral, _mapPrimitiveName(ast.keys), change_detection_util_1.ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitBinary = function (ast) {
- var left = ast.left.visit(this);
- switch (ast.operation) {
- case '&&':
- var branchEnd = [null];
- this._addRecord(proto_record_1.RecordType.SkipRecordsIfNot, "SkipRecordsIfNot", null, [], branchEnd, left);
- var right = ast.right.visit(this);
- branchEnd[0] = right;
- return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "cond", change_detection_util_1.ChangeDetectionUtil.cond, [left, right, left], null, 0);
- case '||':
- var branchEnd = [null];
- this._addRecord(proto_record_1.RecordType.SkipRecordsIf, "SkipRecordsIf", null, [], branchEnd, left);
- var right = ast.right.visit(this);
- branchEnd[0] = right;
- return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "cond", change_detection_util_1.ChangeDetectionUtil.cond, [left, left, right], null, 0);
- default:
- var right = ast.right.visit(this);
- return this._addRecord(proto_record_1.RecordType.PrimitiveOp, _operationToPrimitiveName(ast.operation), _operationToFunction(ast.operation), [left, right], null, 0);
- }
- };
- _ConvertAstIntoProtoRecords.prototype.visitPrefixNot = function (ast) {
- var exp = ast.expression.visit(this);
- return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "operation_negate", change_detection_util_1.ChangeDetectionUtil.operation_negate, [exp], null, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitConditional = function (ast) {
- var condition = ast.condition.visit(this);
- var startOfFalseBranch = [null];
- var endOfFalseBranch = [null];
- this._addRecord(proto_record_1.RecordType.SkipRecordsIfNot, "SkipRecordsIfNot", null, [], startOfFalseBranch, condition);
- var whenTrue = ast.trueExp.visit(this);
- var skip = this._addRecord(proto_record_1.RecordType.SkipRecords, "SkipRecords", null, [], endOfFalseBranch, 0);
- var whenFalse = ast.falseExp.visit(this);
- startOfFalseBranch[0] = skip;
- endOfFalseBranch[0] = whenFalse;
- return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "cond", change_detection_util_1.ChangeDetectionUtil.cond, [condition, whenTrue, whenFalse], null, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitPipe = function (ast) {
- var value = ast.exp.visit(this);
- var args = this._visitAll(ast.args);
- return this._addRecord(proto_record_1.RecordType.Pipe, ast.name, ast.name, args, null, value);
- };
- _ConvertAstIntoProtoRecords.prototype.visitKeyedRead = function (ast) {
- var obj = ast.obj.visit(this);
- var key = ast.key.visit(this);
- return this._addRecord(proto_record_1.RecordType.KeyedRead, "keyedAccess", change_detection_util_1.ChangeDetectionUtil.keyedAccess, [key], null, obj);
- };
- _ConvertAstIntoProtoRecords.prototype.visitChain = function (ast) {
- var _this = this;
- var args = ast.expressions.map(function (e) { return e.visit(_this); });
- return this._addRecord(proto_record_1.RecordType.Chain, "chain", null, args, null, 0);
- };
- _ConvertAstIntoProtoRecords.prototype.visitQuote = function (ast) {
- throw new exceptions_1.BaseException(("Caught uninterpreted expression at " + ast.location + ": " + ast.uninterpretedExpression + ". ") +
- ("Expression prefix " + ast.prefix + " did not match a template transformer to interpret the expression."));
- };
- _ConvertAstIntoProtoRecords.prototype._visitAll = function (asts) {
- var res = collection_1.ListWrapper.createFixedSize(asts.length);
- for (var i = 0; i < asts.length; ++i) {
- res[i] = asts[i].visit(this);
- }
- return res;
- };
- /**
- * Adds a `ProtoRecord` and returns its selfIndex.
- */
- _ConvertAstIntoProtoRecords.prototype._addRecord = function (type, name, funcOrValue, args, fixedArgs, context) {
- var selfIndex = this._records.length + 1;
- if (context instanceof directive_record_1.DirectiveIndex) {
- this._records.push(new proto_record_1.ProtoRecord(type, name, funcOrValue, args, fixedArgs, -1, context, selfIndex, this._bindingRecord, false, false, false, false, this._bindingIndex));
- }
- else {
- this._records.push(new proto_record_1.ProtoRecord(type, name, funcOrValue, args, fixedArgs, context, null, selfIndex, this._bindingRecord, false, false, false, false, this._bindingIndex));
- }
- return selfIndex;
- };
- return _ConvertAstIntoProtoRecords;
- })();
- function _arrayFn(length) {
- switch (length) {
- case 0:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn0;
- case 1:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn1;
- case 2:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn2;
- case 3:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn3;
- case 4:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn4;
- case 5:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn5;
- case 6:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn6;
- case 7:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn7;
- case 8:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn8;
- case 9:
- return change_detection_util_1.ChangeDetectionUtil.arrayFn9;
- default:
- throw new exceptions_1.BaseException("Does not support literal maps with more than 9 elements");
- }
- }
- function _mapPrimitiveName(keys) {
- var stringifiedKeys = keys.map(function (k) { return lang_1.isString(k) ? "\"" + k + "\"" : "" + k; }).join(', ');
- return "mapFn([" + stringifiedKeys + "])";
- }
- function _operationToPrimitiveName(operation) {
- switch (operation) {
- case '+':
- return "operation_add";
- case '-':
- return "operation_subtract";
- case '*':
- return "operation_multiply";
- case '/':
- return "operation_divide";
- case '%':
- return "operation_remainder";
- case '==':
- return "operation_equals";
- case '!=':
- return "operation_not_equals";
- case '===':
- return "operation_identical";
- case '!==':
- return "operation_not_identical";
- case '<':
- return "operation_less_then";
- case '>':
- return "operation_greater_then";
- case '<=':
- return "operation_less_or_equals_then";
- case '>=':
- return "operation_greater_or_equals_then";
- default:
- throw new exceptions_1.BaseException("Unsupported operation " + operation);
- }
- }
- function _operationToFunction(operation) {
- switch (operation) {
- case '+':
- return change_detection_util_1.ChangeDetectionUtil.operation_add;
- case '-':
- return change_detection_util_1.ChangeDetectionUtil.operation_subtract;
- case '*':
- return change_detection_util_1.ChangeDetectionUtil.operation_multiply;
- case '/':
- return change_detection_util_1.ChangeDetectionUtil.operation_divide;
- case '%':
- return change_detection_util_1.ChangeDetectionUtil.operation_remainder;
- case '==':
- return change_detection_util_1.ChangeDetectionUtil.operation_equals;
- case '!=':
- return change_detection_util_1.ChangeDetectionUtil.operation_not_equals;
- case '===':
- return change_detection_util_1.ChangeDetectionUtil.operation_identical;
- case '!==':
- return change_detection_util_1.ChangeDetectionUtil.operation_not_identical;
- case '<':
- return change_detection_util_1.ChangeDetectionUtil.operation_less_then;
- case '>':
- return change_detection_util_1.ChangeDetectionUtil.operation_greater_then;
- case '<=':
- return change_detection_util_1.ChangeDetectionUtil.operation_less_or_equals_then;
- case '>=':
- return change_detection_util_1.ChangeDetectionUtil.operation_greater_or_equals_then;
- default:
- throw new exceptions_1.BaseException("Unsupported operation " + operation);
- }
- }
- function s(v) {
- return lang_1.isPresent(v) ? "" + v : '';
- }
- function _interpolationFn(strings) {
- var length = strings.length;
- var c0 = length > 0 ? strings[0] : null;
- var c1 = length > 1 ? strings[1] : null;
- var c2 = length > 2 ? strings[2] : null;
- var c3 = length > 3 ? strings[3] : null;
- var c4 = length > 4 ? strings[4] : null;
- var c5 = length > 5 ? strings[5] : null;
- var c6 = length > 6 ? strings[6] : null;
- var c7 = length > 7 ? strings[7] : null;
- var c8 = length > 8 ? strings[8] : null;
- var c9 = length > 9 ? strings[9] : null;
- switch (length - 1) {
- case 1:
- return function (a1) { return c0 + s(a1) + c1; };
- case 2:
- return function (a1, a2) { return c0 + s(a1) + c1 + s(a2) + c2; };
- case 3:
- return function (a1, a2, a3) { return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3; };
- case 4:
- return function (a1, a2, a3, a4) { return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4; };
- case 5:
- return function (a1, a2, a3, a4, a5) {
- return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5;
- };
- case 6:
- return function (a1, a2, a3, a4, a5, a6) {
- return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6;
- };
- case 7:
- return function (a1, a2, a3, a4, a5, a6, a7) { return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) +
- c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7; };
- case 8:
- return function (a1, a2, a3, a4, a5, a6, a7, a8) { return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) +
- c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) +
- c8; };
- case 9:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9) { return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 +
- s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) +
- c7 + s(a8) + c8 + s(a9) + c9; };
- default:
- throw new exceptions_1.BaseException("Does not support more than 9 expressions");
- }
- }
- /***/ },
- /* 38 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var constants_1 = __webpack_require__(36);
- var pipe_lifecycle_reflector_1 = __webpack_require__(39);
- var binding_record_1 = __webpack_require__(40);
- var directive_record_1 = __webpack_require__(41);
- /**
- * Indicates that the result of a {@link PipeMetadata} transformation has changed even though the
- * reference
- * has not changed.
- *
- * The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored.
- *
- * Example:
- *
- * ```
- * if (this._latestValue === this._latestReturnedValue) {
- * return this._latestReturnedValue;
- * } else {
- * this._latestReturnedValue = this._latestValue;
- * return WrappedValue.wrap(this._latestValue); // this will force update
- * }
- * ```
- */
- var WrappedValue = (function () {
- function WrappedValue(wrapped) {
- this.wrapped = wrapped;
- }
- WrappedValue.wrap = function (value) {
- var w = _wrappedValues[_wrappedIndex++ % 5];
- w.wrapped = value;
- return w;
- };
- return WrappedValue;
- })();
- exports.WrappedValue = WrappedValue;
- var _wrappedValues = [
- new WrappedValue(null),
- new WrappedValue(null),
- new WrappedValue(null),
- new WrappedValue(null),
- new WrappedValue(null)
- ];
- var _wrappedIndex = 0;
- /**
- * Represents a basic change from a previous to a new value.
- */
- var SimpleChange = (function () {
- function SimpleChange(previousValue, currentValue) {
- this.previousValue = previousValue;
- this.currentValue = currentValue;
- }
- /**
- * Check whether the new value is the first value assigned.
- */
- SimpleChange.prototype.isFirstChange = function () { return this.previousValue === ChangeDetectionUtil.uninitialized; };
- return SimpleChange;
- })();
- exports.SimpleChange = SimpleChange;
- var _simpleChangesIndex = 0;
- var _simpleChanges = [
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null),
- new SimpleChange(null, null)
- ];
- function _simpleChange(previousValue, currentValue) {
- var index = _simpleChangesIndex++ % 20;
- var s = _simpleChanges[index];
- s.previousValue = previousValue;
- s.currentValue = currentValue;
- return s;
- }
- /* tslint:disable:requireParameterType */
- var ChangeDetectionUtil = (function () {
- function ChangeDetectionUtil() {
- }
- ChangeDetectionUtil.arrayFn0 = function () { return []; };
- ChangeDetectionUtil.arrayFn1 = function (a1) { return [a1]; };
- ChangeDetectionUtil.arrayFn2 = function (a1, a2) { return [a1, a2]; };
- ChangeDetectionUtil.arrayFn3 = function (a1, a2, a3) { return [a1, a2, a3]; };
- ChangeDetectionUtil.arrayFn4 = function (a1, a2, a3, a4) { return [a1, a2, a3, a4]; };
- ChangeDetectionUtil.arrayFn5 = function (a1, a2, a3, a4, a5) { return [a1, a2, a3, a4, a5]; };
- ChangeDetectionUtil.arrayFn6 = function (a1, a2, a3, a4, a5, a6) { return [a1, a2, a3, a4, a5, a6]; };
- ChangeDetectionUtil.arrayFn7 = function (a1, a2, a3, a4, a5, a6, a7) { return [a1, a2, a3, a4, a5, a6, a7]; };
- ChangeDetectionUtil.arrayFn8 = function (a1, a2, a3, a4, a5, a6, a7, a8) {
- return [a1, a2, a3, a4, a5, a6, a7, a8];
- };
- ChangeDetectionUtil.arrayFn9 = function (a1, a2, a3, a4, a5, a6, a7, a8, a9) {
- return [a1, a2, a3, a4, a5, a6, a7, a8, a9];
- };
- ChangeDetectionUtil.operation_negate = function (value) { return !value; };
- ChangeDetectionUtil.operation_add = function (left, right) { return left + right; };
- ChangeDetectionUtil.operation_subtract = function (left, right) { return left - right; };
- ChangeDetectionUtil.operation_multiply = function (left, right) { return left * right; };
- ChangeDetectionUtil.operation_divide = function (left, right) { return left / right; };
- ChangeDetectionUtil.operation_remainder = function (left, right) { return left % right; };
- ChangeDetectionUtil.operation_equals = function (left, right) { return left == right; };
- ChangeDetectionUtil.operation_not_equals = function (left, right) { return left != right; };
- ChangeDetectionUtil.operation_identical = function (left, right) { return left === right; };
- ChangeDetectionUtil.operation_not_identical = function (left, right) { return left !== right; };
- ChangeDetectionUtil.operation_less_then = function (left, right) { return left < right; };
- ChangeDetectionUtil.operation_greater_then = function (left, right) { return left > right; };
- ChangeDetectionUtil.operation_less_or_equals_then = function (left, right) { return left <= right; };
- ChangeDetectionUtil.operation_greater_or_equals_then = function (left, right) { return left >= right; };
- ChangeDetectionUtil.cond = function (cond, trueVal, falseVal) { return cond ? trueVal : falseVal; };
- ChangeDetectionUtil.mapFn = function (keys) {
- function buildMap(values) {
- var res = collection_1.StringMapWrapper.create();
- for (var i = 0; i < keys.length; ++i) {
- collection_1.StringMapWrapper.set(res, keys[i], values[i]);
- }
- return res;
- }
- switch (keys.length) {
- case 0:
- return function () { return []; };
- case 1:
- return function (a1) { return buildMap([a1]); };
- case 2:
- return function (a1, a2) { return buildMap([a1, a2]); };
- case 3:
- return function (a1, a2, a3) { return buildMap([a1, a2, a3]); };
- case 4:
- return function (a1, a2, a3, a4) { return buildMap([a1, a2, a3, a4]); };
- case 5:
- return function (a1, a2, a3, a4, a5) { return buildMap([a1, a2, a3, a4, a5]); };
- case 6:
- return function (a1, a2, a3, a4, a5, a6) { return buildMap([a1, a2, a3, a4, a5, a6]); };
- case 7:
- return function (a1, a2, a3, a4, a5, a6, a7) { return buildMap([a1, a2, a3, a4, a5, a6, a7]); };
- case 8:
- return function (a1, a2, a3, a4, a5, a6, a7, a8) { return buildMap([a1, a2, a3, a4, a5, a6, a7, a8]); };
- case 9:
- return function (a1, a2, a3, a4, a5, a6, a7, a8, a9) {
- return buildMap([a1, a2, a3, a4, a5, a6, a7, a8, a9]);
- };
- default:
- throw new exceptions_1.BaseException("Does not support literal maps with more than 9 elements");
- }
- };
- ChangeDetectionUtil.keyedAccess = function (obj, args) { return obj[args[0]]; };
- ChangeDetectionUtil.unwrapValue = function (value) {
- if (value instanceof WrappedValue) {
- return value.wrapped;
- }
- else {
- return value;
- }
- };
- ChangeDetectionUtil.changeDetectionMode = function (strategy) {
- return constants_1.isDefaultChangeDetectionStrategy(strategy) ? constants_1.ChangeDetectionStrategy.CheckAlways :
- constants_1.ChangeDetectionStrategy.CheckOnce;
- };
- ChangeDetectionUtil.simpleChange = function (previousValue, currentValue) {
- return _simpleChange(previousValue, currentValue);
- };
- ChangeDetectionUtil.isValueBlank = function (value) { return lang_1.isBlank(value); };
- ChangeDetectionUtil.s = function (value) { return lang_1.isPresent(value) ? "" + value : ''; };
- ChangeDetectionUtil.protoByIndex = function (protos, selfIndex) {
- return selfIndex < 1 ?
- null :
- protos[selfIndex - 1]; // self index is shifted by one because of context
- };
- ChangeDetectionUtil.callPipeOnDestroy = function (selectedPipe) {
- if (pipe_lifecycle_reflector_1.implementsOnDestroy(selectedPipe.pipe)) {
- selectedPipe.pipe.ngOnDestroy();
- }
- };
- ChangeDetectionUtil.bindingTarget = function (mode, elementIndex, name, unit, debug) {
- return new binding_record_1.BindingTarget(mode, elementIndex, name, unit, debug);
- };
- ChangeDetectionUtil.directiveIndex = function (elementIndex, directiveIndex) {
- return new directive_record_1.DirectiveIndex(elementIndex, directiveIndex);
- };
- ChangeDetectionUtil.looseNotIdentical = function (a, b) { return !lang_1.looseIdentical(a, b); };
- ChangeDetectionUtil.uninitialized = lang_1.CONST_EXPR(new Object());
- return ChangeDetectionUtil;
- })();
- exports.ChangeDetectionUtil = ChangeDetectionUtil;
- /***/ },
- /* 39 */
- /***/ function(module, exports) {
- function implementsOnDestroy(pipe) {
- return pipe.constructor.prototype.ngOnDestroy;
- }
- exports.implementsOnDestroy = implementsOnDestroy;
- /***/ },
- /* 40 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var DIRECTIVE_LIFECYCLE = "directiveLifecycle";
- var BINDING = "native";
- var DIRECTIVE = "directive";
- var ELEMENT_PROPERTY = "elementProperty";
- var ELEMENT_ATTRIBUTE = "elementAttribute";
- var ELEMENT_CLASS = "elementClass";
- var ELEMENT_STYLE = "elementStyle";
- var TEXT_NODE = "textNode";
- var EVENT = "event";
- var HOST_EVENT = "hostEvent";
- var BindingTarget = (function () {
- function BindingTarget(mode, elementIndex, name, unit, debug) {
- this.mode = mode;
- this.elementIndex = elementIndex;
- this.name = name;
- this.unit = unit;
- this.debug = debug;
- }
- BindingTarget.prototype.isDirective = function () { return this.mode === DIRECTIVE; };
- BindingTarget.prototype.isElementProperty = function () { return this.mode === ELEMENT_PROPERTY; };
- BindingTarget.prototype.isElementAttribute = function () { return this.mode === ELEMENT_ATTRIBUTE; };
- BindingTarget.prototype.isElementClass = function () { return this.mode === ELEMENT_CLASS; };
- BindingTarget.prototype.isElementStyle = function () { return this.mode === ELEMENT_STYLE; };
- BindingTarget.prototype.isTextNode = function () { return this.mode === TEXT_NODE; };
- return BindingTarget;
- })();
- exports.BindingTarget = BindingTarget;
- var BindingRecord = (function () {
- function BindingRecord(mode, target, implicitReceiver, ast, setter, lifecycleEvent, directiveRecord) {
- this.mode = mode;
- this.target = target;
- this.implicitReceiver = implicitReceiver;
- this.ast = ast;
- this.setter = setter;
- this.lifecycleEvent = lifecycleEvent;
- this.directiveRecord = directiveRecord;
- }
- BindingRecord.prototype.isDirectiveLifecycle = function () { return this.mode === DIRECTIVE_LIFECYCLE; };
- BindingRecord.prototype.callOnChanges = function () {
- return lang_1.isPresent(this.directiveRecord) && this.directiveRecord.callOnChanges;
- };
- BindingRecord.prototype.isDefaultChangeDetection = function () {
- return lang_1.isBlank(this.directiveRecord) || this.directiveRecord.isDefaultChangeDetection();
- };
- BindingRecord.createDirectiveDoCheck = function (directiveRecord) {
- return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "DoCheck", directiveRecord);
- };
- BindingRecord.createDirectiveOnInit = function (directiveRecord) {
- return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "OnInit", directiveRecord);
- };
- BindingRecord.createDirectiveOnChanges = function (directiveRecord) {
- return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "OnChanges", directiveRecord);
- };
- BindingRecord.createForDirective = function (ast, propertyName, setter, directiveRecord) {
- var elementIndex = directiveRecord.directiveIndex.elementIndex;
- var t = new BindingTarget(DIRECTIVE, elementIndex, propertyName, null, ast.toString());
- return new BindingRecord(DIRECTIVE, t, 0, ast, setter, null, directiveRecord);
- };
- BindingRecord.createForElementProperty = function (ast, elementIndex, propertyName) {
- var t = new BindingTarget(ELEMENT_PROPERTY, elementIndex, propertyName, null, ast.toString());
- return new BindingRecord(BINDING, t, 0, ast, null, null, null);
- };
- BindingRecord.createForElementAttribute = function (ast, elementIndex, attributeName) {
- var t = new BindingTarget(ELEMENT_ATTRIBUTE, elementIndex, attributeName, null, ast.toString());
- return new BindingRecord(BINDING, t, 0, ast, null, null, null);
- };
- BindingRecord.createForElementClass = function (ast, elementIndex, className) {
- var t = new BindingTarget(ELEMENT_CLASS, elementIndex, className, null, ast.toString());
- return new BindingRecord(BINDING, t, 0, ast, null, null, null);
- };
- BindingRecord.createForElementStyle = function (ast, elementIndex, styleName, unit) {
- var t = new BindingTarget(ELEMENT_STYLE, elementIndex, styleName, unit, ast.toString());
- return new BindingRecord(BINDING, t, 0, ast, null, null, null);
- };
- BindingRecord.createForHostProperty = function (directiveIndex, ast, propertyName) {
- var t = new BindingTarget(ELEMENT_PROPERTY, directiveIndex.elementIndex, propertyName, null, ast.toString());
- return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null);
- };
- BindingRecord.createForHostAttribute = function (directiveIndex, ast, attributeName) {
- var t = new BindingTarget(ELEMENT_ATTRIBUTE, directiveIndex.elementIndex, attributeName, null, ast.toString());
- return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null);
- };
- BindingRecord.createForHostClass = function (directiveIndex, ast, className) {
- var t = new BindingTarget(ELEMENT_CLASS, directiveIndex.elementIndex, className, null, ast.toString());
- return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null);
- };
- BindingRecord.createForHostStyle = function (directiveIndex, ast, styleName, unit) {
- var t = new BindingTarget(ELEMENT_STYLE, directiveIndex.elementIndex, styleName, unit, ast.toString());
- return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null);
- };
- BindingRecord.createForTextNode = function (ast, elementIndex) {
- var t = new BindingTarget(TEXT_NODE, elementIndex, null, null, ast.toString());
- return new BindingRecord(BINDING, t, 0, ast, null, null, null);
- };
- BindingRecord.createForEvent = function (ast, eventName, elementIndex) {
- var t = new BindingTarget(EVENT, elementIndex, eventName, null, ast.toString());
- return new BindingRecord(EVENT, t, 0, ast, null, null, null);
- };
- BindingRecord.createForHostEvent = function (ast, eventName, directiveRecord) {
- var directiveIndex = directiveRecord.directiveIndex;
- var t = new BindingTarget(HOST_EVENT, directiveIndex.elementIndex, eventName, null, ast.toString());
- return new BindingRecord(HOST_EVENT, t, directiveIndex, ast, null, null, directiveRecord);
- };
- return BindingRecord;
- })();
- exports.BindingRecord = BindingRecord;
- /***/ },
- /* 41 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var constants_1 = __webpack_require__(36);
- var DirectiveIndex = (function () {
- function DirectiveIndex(elementIndex, directiveIndex) {
- this.elementIndex = elementIndex;
- this.directiveIndex = directiveIndex;
- }
- Object.defineProperty(DirectiveIndex.prototype, "name", {
- get: function () { return this.elementIndex + "_" + this.directiveIndex; },
- enumerable: true,
- configurable: true
- });
- return DirectiveIndex;
- })();
- exports.DirectiveIndex = DirectiveIndex;
- var DirectiveRecord = (function () {
- function DirectiveRecord(_a) {
- var _b = _a === void 0 ? {} : _a, directiveIndex = _b.directiveIndex, callAfterContentInit = _b.callAfterContentInit, callAfterContentChecked = _b.callAfterContentChecked, callAfterViewInit = _b.callAfterViewInit, callAfterViewChecked = _b.callAfterViewChecked, callOnChanges = _b.callOnChanges, callDoCheck = _b.callDoCheck, callOnInit = _b.callOnInit, changeDetection = _b.changeDetection;
- this.directiveIndex = directiveIndex;
- this.callAfterContentInit = lang_1.normalizeBool(callAfterContentInit);
- this.callAfterContentChecked = lang_1.normalizeBool(callAfterContentChecked);
- this.callOnChanges = lang_1.normalizeBool(callOnChanges);
- this.callAfterViewInit = lang_1.normalizeBool(callAfterViewInit);
- this.callAfterViewChecked = lang_1.normalizeBool(callAfterViewChecked);
- this.callDoCheck = lang_1.normalizeBool(callDoCheck);
- this.callOnInit = lang_1.normalizeBool(callOnInit);
- this.changeDetection = changeDetection;
- }
- DirectiveRecord.prototype.isDefaultChangeDetection = function () {
- return constants_1.isDefaultChangeDetectionStrategy(this.changeDetection);
- };
- return DirectiveRecord;
- })();
- exports.DirectiveRecord = DirectiveRecord;
- /***/ },
- /* 42 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var abstract_change_detector_1 = __webpack_require__(43);
- var change_detection_util_1 = __webpack_require__(38);
- var constants_1 = __webpack_require__(36);
- var proto_record_1 = __webpack_require__(48);
- var DynamicChangeDetector = (function (_super) {
- __extends(DynamicChangeDetector, _super);
- function DynamicChangeDetector(id, dispatcher, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy, _records, _eventBindings, _directiveRecords, _genConfig) {
- _super.call(this, id, dispatcher, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy);
- this._records = _records;
- this._eventBindings = _eventBindings;
- this._directiveRecords = _directiveRecords;
- this._genConfig = _genConfig;
- this.directives = null;
- var len = _records.length + 1;
- this.values = collection_1.ListWrapper.createFixedSize(len);
- this.localPipes = collection_1.ListWrapper.createFixedSize(len);
- this.prevContexts = collection_1.ListWrapper.createFixedSize(len);
- this.changes = collection_1.ListWrapper.createFixedSize(len);
- this.dehydrateDirectives(false);
- }
- DynamicChangeDetector.prototype.handleEventInternal = function (eventName, elIndex, locals) {
- var _this = this;
- var preventDefault = false;
- this._matchingEventBindings(eventName, elIndex)
- .forEach(function (rec) {
- var res = _this._processEventBinding(rec, locals);
- if (res === false) {
- preventDefault = true;
- }
- });
- return preventDefault;
- };
- /** @internal */
- DynamicChangeDetector.prototype._processEventBinding = function (eb, locals) {
- var values = collection_1.ListWrapper.createFixedSize(eb.records.length);
- values[0] = this.values[0];
- for (var protoIdx = 0; protoIdx < eb.records.length; ++protoIdx) {
- var proto = eb.records[protoIdx];
- if (proto.isSkipRecord()) {
- protoIdx += this._computeSkipLength(protoIdx, proto, values);
- }
- else {
- var res = this._calculateCurrValue(proto, values, locals);
- if (proto.lastInBinding) {
- this._markPathAsCheckOnce(proto);
- return res;
- }
- else {
- this._writeSelf(proto, res, values);
- }
- }
- }
- throw new exceptions_1.BaseException("Cannot be reached");
- };
- DynamicChangeDetector.prototype._computeSkipLength = function (protoIndex, proto, values) {
- if (proto.mode === proto_record_1.RecordType.SkipRecords) {
- return proto.fixedArgs[0] - protoIndex - 1;
- }
- if (proto.mode === proto_record_1.RecordType.SkipRecordsIf) {
- var condition = this._readContext(proto, values);
- return condition ? proto.fixedArgs[0] - protoIndex - 1 : 0;
- }
- if (proto.mode === proto_record_1.RecordType.SkipRecordsIfNot) {
- var condition = this._readContext(proto, values);
- return condition ? 0 : proto.fixedArgs[0] - protoIndex - 1;
- }
- throw new exceptions_1.BaseException("Cannot be reached");
- };
- /** @internal */
- DynamicChangeDetector.prototype._markPathAsCheckOnce = function (proto) {
- if (!proto.bindingRecord.isDefaultChangeDetection()) {
- var dir = proto.bindingRecord.directiveRecord;
- this._getDetectorFor(dir.directiveIndex).markPathToRootAsCheckOnce();
- }
- };
- /** @internal */
- DynamicChangeDetector.prototype._matchingEventBindings = function (eventName, elIndex) {
- return this._eventBindings.filter(function (eb) { return eb.eventName == eventName && eb.elIndex === elIndex; });
- };
- DynamicChangeDetector.prototype.hydrateDirectives = function (directives) {
- this.values[0] = this.context;
- this.directives = directives;
- if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) {
- for (var i = 0; i < this.directiveIndices.length; ++i) {
- var index = this.directiveIndices[i];
- _super.prototype.observeDirective.call(this, directives.getDirectiveFor(index), i);
- }
- }
- };
- DynamicChangeDetector.prototype.dehydrateDirectives = function (destroyPipes) {
- if (destroyPipes) {
- this._destroyPipes();
- }
- this.values[0] = null;
- this.directives = null;
- collection_1.ListWrapper.fill(this.values, change_detection_util_1.ChangeDetectionUtil.uninitialized, 1);
- collection_1.ListWrapper.fill(this.changes, false);
- collection_1.ListWrapper.fill(this.localPipes, null);
- collection_1.ListWrapper.fill(this.prevContexts, change_detection_util_1.ChangeDetectionUtil.uninitialized);
- };
- /** @internal */
- DynamicChangeDetector.prototype._destroyPipes = function () {
- for (var i = 0; i < this.localPipes.length; ++i) {
- if (lang_1.isPresent(this.localPipes[i])) {
- change_detection_util_1.ChangeDetectionUtil.callPipeOnDestroy(this.localPipes[i]);
- }
- }
- };
- DynamicChangeDetector.prototype.checkNoChanges = function () { this.runDetectChanges(true); };
- DynamicChangeDetector.prototype.detectChangesInRecordsInternal = function (throwOnChange) {
- var protos = this._records;
- var changes = null;
- var isChanged = false;
- for (var protoIdx = 0; protoIdx < protos.length; ++protoIdx) {
- var proto = protos[protoIdx];
- var bindingRecord = proto.bindingRecord;
- var directiveRecord = bindingRecord.directiveRecord;
- if (this._firstInBinding(proto)) {
- this.propertyBindingIndex = proto.propertyBindingIndex;
- }
- if (proto.isLifeCycleRecord()) {
- if (proto.name === "DoCheck" && !throwOnChange) {
- this._getDirectiveFor(directiveRecord.directiveIndex).ngDoCheck();
- }
- else if (proto.name === "OnInit" && !throwOnChange &&
- this.state == constants_1.ChangeDetectorState.NeverChecked) {
- this._getDirectiveFor(directiveRecord.directiveIndex).ngOnInit();
- }
- else if (proto.name === "OnChanges" && lang_1.isPresent(changes) && !throwOnChange) {
- this._getDirectiveFor(directiveRecord.directiveIndex).ngOnChanges(changes);
- }
- }
- else if (proto.isSkipRecord()) {
- protoIdx += this._computeSkipLength(protoIdx, proto, this.values);
- }
- else {
- var change = this._check(proto, throwOnChange, this.values, this.locals);
- if (lang_1.isPresent(change)) {
- this._updateDirectiveOrElement(change, bindingRecord);
- isChanged = true;
- changes = this._addChange(bindingRecord, change, changes);
- }
- }
- if (proto.lastInDirective) {
- changes = null;
- if (isChanged && !bindingRecord.isDefaultChangeDetection()) {
- this._getDetectorFor(directiveRecord.directiveIndex).markAsCheckOnce();
- }
- isChanged = false;
- }
- }
- };
- /** @internal */
- DynamicChangeDetector.prototype._firstInBinding = function (r) {
- var prev = change_detection_util_1.ChangeDetectionUtil.protoByIndex(this._records, r.selfIndex - 1);
- return lang_1.isBlank(prev) || prev.bindingRecord !== r.bindingRecord;
- };
- DynamicChangeDetector.prototype.afterContentLifecycleCallbacksInternal = function () {
- var dirs = this._directiveRecords;
- for (var i = dirs.length - 1; i >= 0; --i) {
- var dir = dirs[i];
- if (dir.callAfterContentInit && this.state == constants_1.ChangeDetectorState.NeverChecked) {
- this._getDirectiveFor(dir.directiveIndex).ngAfterContentInit();
- }
- if (dir.callAfterContentChecked) {
- this._getDirectiveFor(dir.directiveIndex).ngAfterContentChecked();
- }
- }
- };
- DynamicChangeDetector.prototype.afterViewLifecycleCallbacksInternal = function () {
- var dirs = this._directiveRecords;
- for (var i = dirs.length - 1; i >= 0; --i) {
- var dir = dirs[i];
- if (dir.callAfterViewInit && this.state == constants_1.ChangeDetectorState.NeverChecked) {
- this._getDirectiveFor(dir.directiveIndex).ngAfterViewInit();
- }
- if (dir.callAfterViewChecked) {
- this._getDirectiveFor(dir.directiveIndex).ngAfterViewChecked();
- }
- }
- };
- /** @internal */
- DynamicChangeDetector.prototype._updateDirectiveOrElement = function (change, bindingRecord) {
- if (lang_1.isBlank(bindingRecord.directiveRecord)) {
- _super.prototype.notifyDispatcher.call(this, change.currentValue);
- }
- else {
- var directiveIndex = bindingRecord.directiveRecord.directiveIndex;
- bindingRecord.setter(this._getDirectiveFor(directiveIndex), change.currentValue);
- }
- if (this._genConfig.logBindingUpdate) {
- _super.prototype.logBindingUpdate.call(this, change.currentValue);
- }
- };
- /** @internal */
- DynamicChangeDetector.prototype._addChange = function (bindingRecord, change, changes) {
- if (bindingRecord.callOnChanges()) {
- return _super.prototype.addChange.call(this, changes, change.previousValue, change.currentValue);
- }
- else {
- return changes;
- }
- };
- /** @internal */
- DynamicChangeDetector.prototype._getDirectiveFor = function (directiveIndex) {
- return this.directives.getDirectiveFor(directiveIndex);
- };
- /** @internal */
- DynamicChangeDetector.prototype._getDetectorFor = function (directiveIndex) { return this.directives.getDetectorFor(directiveIndex); };
- /** @internal */
- DynamicChangeDetector.prototype._check = function (proto, throwOnChange, values, locals) {
- if (proto.isPipeRecord()) {
- return this._pipeCheck(proto, throwOnChange, values);
- }
- else {
- return this._referenceCheck(proto, throwOnChange, values, locals);
- }
- };
- /** @internal */
- DynamicChangeDetector.prototype._referenceCheck = function (proto, throwOnChange, values, locals) {
- if (this._pureFuncAndArgsDidNotChange(proto)) {
- this._setChanged(proto, false);
- return null;
- }
- var currValue = this._calculateCurrValue(proto, values, locals);
- if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) {
- _super.prototype.observeValue.call(this, currValue, proto.selfIndex);
- }
- if (proto.shouldBeChecked()) {
- var prevValue = this._readSelf(proto, values);
- if (change_detection_util_1.ChangeDetectionUtil.looseNotIdentical(prevValue, currValue)) {
- if (proto.lastInBinding) {
- var change = change_detection_util_1.ChangeDetectionUtil.simpleChange(prevValue, currValue);
- if (throwOnChange)
- this.throwOnChangeError(prevValue, currValue);
- this._writeSelf(proto, currValue, values);
- this._setChanged(proto, true);
- return change;
- }
- else {
- this._writeSelf(proto, currValue, values);
- this._setChanged(proto, true);
- return null;
- }
- }
- else {
- this._setChanged(proto, false);
- return null;
- }
- }
- else {
- this._writeSelf(proto, currValue, values);
- this._setChanged(proto, true);
- return null;
- }
- };
- DynamicChangeDetector.prototype._calculateCurrValue = function (proto, values, locals) {
- switch (proto.mode) {
- case proto_record_1.RecordType.Self:
- return this._readContext(proto, values);
- case proto_record_1.RecordType.Const:
- return proto.funcOrValue;
- case proto_record_1.RecordType.PropertyRead:
- var context = this._readContext(proto, values);
- return proto.funcOrValue(context);
- case proto_record_1.RecordType.SafeProperty:
- var context = this._readContext(proto, values);
- return lang_1.isBlank(context) ? null : proto.funcOrValue(context);
- case proto_record_1.RecordType.PropertyWrite:
- var context = this._readContext(proto, values);
- var value = this._readArgs(proto, values)[0];
- proto.funcOrValue(context, value);
- return value;
- case proto_record_1.RecordType.KeyedWrite:
- var context = this._readContext(proto, values);
- var key = this._readArgs(proto, values)[0];
- var value = this._readArgs(proto, values)[1];
- context[key] = value;
- return value;
- case proto_record_1.RecordType.Local:
- return locals.get(proto.name);
- case proto_record_1.RecordType.InvokeMethod:
- var context = this._readContext(proto, values);
- var args = this._readArgs(proto, values);
- return proto.funcOrValue(context, args);
- case proto_record_1.RecordType.SafeMethodInvoke:
- var context = this._readContext(proto, values);
- if (lang_1.isBlank(context)) {
- return null;
- }
- var args = this._readArgs(proto, values);
- return proto.funcOrValue(context, args);
- case proto_record_1.RecordType.KeyedRead:
- var arg = this._readArgs(proto, values)[0];
- return this._readContext(proto, values)[arg];
- case proto_record_1.RecordType.Chain:
- var args = this._readArgs(proto, values);
- return args[args.length - 1];
- case proto_record_1.RecordType.InvokeClosure:
- return lang_1.FunctionWrapper.apply(this._readContext(proto, values), this._readArgs(proto, values));
- case proto_record_1.RecordType.Interpolate:
- case proto_record_1.RecordType.PrimitiveOp:
- case proto_record_1.RecordType.CollectionLiteral:
- return lang_1.FunctionWrapper.apply(proto.funcOrValue, this._readArgs(proto, values));
- default:
- throw new exceptions_1.BaseException("Unknown operation " + proto.mode);
- }
- };
- DynamicChangeDetector.prototype._pipeCheck = function (proto, throwOnChange, values) {
- var context = this._readContext(proto, values);
- var selectedPipe = this._pipeFor(proto, context);
- if (!selectedPipe.pure || this._argsOrContextChanged(proto)) {
- var args = this._readArgs(proto, values);
- var currValue = selectedPipe.pipe.transform(context, args);
- if (proto.shouldBeChecked()) {
- var prevValue = this._readSelf(proto, values);
- if (change_detection_util_1.ChangeDetectionUtil.looseNotIdentical(prevValue, currValue)) {
- currValue = change_detection_util_1.ChangeDetectionUtil.unwrapValue(currValue);
- if (proto.lastInBinding) {
- var change = change_detection_util_1.ChangeDetectionUtil.simpleChange(prevValue, currValue);
- if (throwOnChange)
- this.throwOnChangeError(prevValue, currValue);
- this._writeSelf(proto, currValue, values);
- this._setChanged(proto, true);
- return change;
- }
- else {
- this._writeSelf(proto, currValue, values);
- this._setChanged(proto, true);
- return null;
- }
- }
- else {
- this._setChanged(proto, false);
- return null;
- }
- }
- else {
- this._writeSelf(proto, currValue, values);
- this._setChanged(proto, true);
- return null;
- }
- }
- };
- DynamicChangeDetector.prototype._pipeFor = function (proto, context) {
- var storedPipe = this._readPipe(proto);
- if (lang_1.isPresent(storedPipe))
- return storedPipe;
- var pipe = this.pipes.get(proto.name);
- this._writePipe(proto, pipe);
- return pipe;
- };
- DynamicChangeDetector.prototype._readContext = function (proto, values) {
- if (proto.contextIndex == -1) {
- return this._getDirectiveFor(proto.directiveIndex);
- }
- return values[proto.contextIndex];
- };
- DynamicChangeDetector.prototype._readSelf = function (proto, values) { return values[proto.selfIndex]; };
- DynamicChangeDetector.prototype._writeSelf = function (proto, value, values) { values[proto.selfIndex] = value; };
- DynamicChangeDetector.prototype._readPipe = function (proto) { return this.localPipes[proto.selfIndex]; };
- DynamicChangeDetector.prototype._writePipe = function (proto, value) { this.localPipes[proto.selfIndex] = value; };
- DynamicChangeDetector.prototype._setChanged = function (proto, value) {
- if (proto.argumentToPureFunction)
- this.changes[proto.selfIndex] = value;
- };
- DynamicChangeDetector.prototype._pureFuncAndArgsDidNotChange = function (proto) {
- return proto.isPureFunction() && !this._argsChanged(proto);
- };
- DynamicChangeDetector.prototype._argsChanged = function (proto) {
- var args = proto.args;
- for (var i = 0; i < args.length; ++i) {
- if (this.changes[args[i]]) {
- return true;
- }
- }
- return false;
- };
- DynamicChangeDetector.prototype._argsOrContextChanged = function (proto) {
- return this._argsChanged(proto) || this.changes[proto.contextIndex];
- };
- DynamicChangeDetector.prototype._readArgs = function (proto, values) {
- var res = collection_1.ListWrapper.createFixedSize(proto.args.length);
- var args = proto.args;
- for (var i = 0; i < args.length; ++i) {
- res[i] = values[args[i]];
- }
- return res;
- };
- return DynamicChangeDetector;
- })(abstract_change_detector_1.AbstractChangeDetector);
- exports.DynamicChangeDetector = DynamicChangeDetector;
- /***/ },
- /* 43 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var change_detection_util_1 = __webpack_require__(38);
- var change_detector_ref_1 = __webpack_require__(44);
- var exceptions_1 = __webpack_require__(34);
- var constants_1 = __webpack_require__(36);
- var profile_1 = __webpack_require__(45);
- var observable_facade_1 = __webpack_require__(47);
- var _scope_check = profile_1.wtfCreateScope("ChangeDetector#check(ascii id, bool throwOnChange)");
- var _Context = (function () {
- function _Context(element, componentElement, context, locals, injector, expression) {
- this.element = element;
- this.componentElement = componentElement;
- this.context = context;
- this.locals = locals;
- this.injector = injector;
- this.expression = expression;
- }
- return _Context;
- })();
- var AbstractChangeDetector = (function () {
- function AbstractChangeDetector(id, dispatcher, numberOfPropertyProtoRecords, bindingTargets, directiveIndices, strategy) {
- this.id = id;
- this.dispatcher = dispatcher;
- this.numberOfPropertyProtoRecords = numberOfPropertyProtoRecords;
- this.bindingTargets = bindingTargets;
- this.directiveIndices = directiveIndices;
- this.strategy = strategy;
- this.contentChildren = [];
- this.viewChildren = [];
- // The names of the below fields must be kept in sync with codegen_name_util.ts or
- // change detection will fail.
- this.state = constants_1.ChangeDetectorState.NeverChecked;
- this.locals = null;
- this.mode = null;
- this.pipes = null;
- this.ref = new change_detector_ref_1.ChangeDetectorRef_(this);
- }
- AbstractChangeDetector.prototype.addContentChild = function (cd) {
- this.contentChildren.push(cd);
- cd.parent = this;
- };
- AbstractChangeDetector.prototype.removeContentChild = function (cd) { collection_1.ListWrapper.remove(this.contentChildren, cd); };
- AbstractChangeDetector.prototype.addViewChild = function (cd) {
- this.viewChildren.push(cd);
- cd.parent = this;
- };
- AbstractChangeDetector.prototype.removeViewChild = function (cd) { collection_1.ListWrapper.remove(this.viewChildren, cd); };
- AbstractChangeDetector.prototype.remove = function () { this.parent.removeContentChild(this); };
- AbstractChangeDetector.prototype.handleEvent = function (eventName, elIndex, locals) {
- var res = this.handleEventInternal(eventName, elIndex, locals);
- this.markPathToRootAsCheckOnce();
- return res;
- };
- AbstractChangeDetector.prototype.handleEventInternal = function (eventName, elIndex, locals) { return false; };
- AbstractChangeDetector.prototype.detectChanges = function () { this.runDetectChanges(false); };
- AbstractChangeDetector.prototype.checkNoChanges = function () {
- if (lang_1.assertionsEnabled()) {
- this.runDetectChanges(true);
- }
- };
- AbstractChangeDetector.prototype.runDetectChanges = function (throwOnChange) {
- if (this.mode === constants_1.ChangeDetectionStrategy.Detached ||
- this.mode === constants_1.ChangeDetectionStrategy.Checked || this.state === constants_1.ChangeDetectorState.Errored)
- return;
- var s = _scope_check(this.id, throwOnChange);
- this.detectChangesInRecords(throwOnChange);
- this._detectChangesContentChildren(throwOnChange);
- if (!throwOnChange)
- this.afterContentLifecycleCallbacks();
- this._detectChangesInViewChildren(throwOnChange);
- if (!throwOnChange)
- this.afterViewLifecycleCallbacks();
- if (this.mode === constants_1.ChangeDetectionStrategy.CheckOnce)
- this.mode = constants_1.ChangeDetectionStrategy.Checked;
- this.state = constants_1.ChangeDetectorState.CheckedBefore;
- profile_1.wtfLeave(s);
- };
- // This method is not intended to be overridden. Subclasses should instead provide an
- // implementation of `detectChangesInRecordsInternal` which does the work of detecting changes
- // and which this method will call.
- // This method expects that `detectChangesInRecordsInternal` will set the property
- // `this.propertyBindingIndex` to the propertyBindingIndex of the first proto record. This is to
- // facilitate error reporting.
- AbstractChangeDetector.prototype.detectChangesInRecords = function (throwOnChange) {
- if (!this.hydrated()) {
- this.throwDehydratedError();
- }
- try {
- this.detectChangesInRecordsInternal(throwOnChange);
- }
- catch (e) {
- // throwOnChange errors aren't counted as fatal errors.
- if (!(e instanceof exceptions_1.ExpressionChangedAfterItHasBeenCheckedException)) {
- this.state = constants_1.ChangeDetectorState.Errored;
- }
- this._throwError(e, e.stack);
- }
- };
- // Subclasses should override this method to perform any work necessary to detect and report
- // changes. For example, changes should be reported via `ChangeDetectionUtil.addChange`, lifecycle
- // methods should be called, etc.
- // This implementation should also set `this.propertyBindingIndex` to the propertyBindingIndex of
- // the
- // first proto record to facilitate error reporting. See {@link #detectChangesInRecords}.
- AbstractChangeDetector.prototype.detectChangesInRecordsInternal = function (throwOnChange) { };
- // This method is not intended to be overridden. Subclasses should instead provide an
- // implementation of `hydrateDirectives`.
- AbstractChangeDetector.prototype.hydrate = function (context, locals, directives, pipes) {
- this.mode = change_detection_util_1.ChangeDetectionUtil.changeDetectionMode(this.strategy);
- this.context = context;
- if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) {
- this.observeComponent(context);
- }
- this.locals = locals;
- this.pipes = pipes;
- this.hydrateDirectives(directives);
- this.state = constants_1.ChangeDetectorState.NeverChecked;
- };
- // Subclasses should override this method to hydrate any directives.
- AbstractChangeDetector.prototype.hydrateDirectives = function (directives) { };
- // This method is not intended to be overridden. Subclasses should instead provide an
- // implementation of `dehydrateDirectives`.
- AbstractChangeDetector.prototype.dehydrate = function () {
- this.dehydrateDirectives(true);
- // This is an experimental feature. Works only in Dart.
- if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) {
- this._unsubsribeFromObservables();
- }
- this.context = null;
- this.locals = null;
- this.pipes = null;
- };
- // Subclasses should override this method to dehydrate any directives. This method should reverse
- // any work done in `hydrateDirectives`.
- AbstractChangeDetector.prototype.dehydrateDirectives = function (destroyPipes) { };
- AbstractChangeDetector.prototype.hydrated = function () { return lang_1.isPresent(this.context); };
- AbstractChangeDetector.prototype.afterContentLifecycleCallbacks = function () {
- this.dispatcher.notifyAfterContentChecked();
- this.afterContentLifecycleCallbacksInternal();
- };
- AbstractChangeDetector.prototype.afterContentLifecycleCallbacksInternal = function () { };
- AbstractChangeDetector.prototype.afterViewLifecycleCallbacks = function () {
- this.dispatcher.notifyAfterViewChecked();
- this.afterViewLifecycleCallbacksInternal();
- };
- AbstractChangeDetector.prototype.afterViewLifecycleCallbacksInternal = function () { };
- /** @internal */
- AbstractChangeDetector.prototype._detectChangesContentChildren = function (throwOnChange) {
- var c = this.contentChildren;
- for (var i = 0; i < c.length; ++i) {
- c[i].runDetectChanges(throwOnChange);
- }
- };
- /** @internal */
- AbstractChangeDetector.prototype._detectChangesInViewChildren = function (throwOnChange) {
- var c = this.viewChildren;
- for (var i = 0; i < c.length; ++i) {
- c[i].runDetectChanges(throwOnChange);
- }
- };
- AbstractChangeDetector.prototype.markAsCheckOnce = function () { this.mode = constants_1.ChangeDetectionStrategy.CheckOnce; };
- AbstractChangeDetector.prototype.markPathToRootAsCheckOnce = function () {
- var c = this;
- while (lang_1.isPresent(c) && c.mode !== constants_1.ChangeDetectionStrategy.Detached) {
- if (c.mode === constants_1.ChangeDetectionStrategy.Checked)
- c.mode = constants_1.ChangeDetectionStrategy.CheckOnce;
- c = c.parent;
- }
- };
- // This is an experimental feature. Works only in Dart.
- AbstractChangeDetector.prototype._unsubsribeFromObservables = function () {
- if (lang_1.isPresent(this.subscriptions)) {
- for (var i = 0; i < this.subscriptions.length; ++i) {
- var s = this.subscriptions[i];
- if (lang_1.isPresent(this.subscriptions[i])) {
- s.cancel();
- this.subscriptions[i] = null;
- }
- }
- }
- };
- // This is an experimental feature. Works only in Dart.
- AbstractChangeDetector.prototype.observeValue = function (value, index) {
- var _this = this;
- if (observable_facade_1.isObservable(value)) {
- this._createArrayToStoreObservables();
- if (lang_1.isBlank(this.subscriptions[index])) {
- this.streams[index] = value.changes;
- this.subscriptions[index] = value.changes.listen(function (_) { return _this.ref.markForCheck(); });
- }
- else if (this.streams[index] !== value.changes) {
- this.subscriptions[index].cancel();
- this.streams[index] = value.changes;
- this.subscriptions[index] = value.changes.listen(function (_) { return _this.ref.markForCheck(); });
- }
- }
- return value;
- };
- // This is an experimental feature. Works only in Dart.
- AbstractChangeDetector.prototype.observeDirective = function (value, index) {
- var _this = this;
- if (observable_facade_1.isObservable(value)) {
- this._createArrayToStoreObservables();
- var arrayIndex = this.numberOfPropertyProtoRecords + index + 2; // +1 is component
- this.streams[arrayIndex] = value.changes;
- this.subscriptions[arrayIndex] = value.changes.listen(function (_) { return _this.ref.markForCheck(); });
- }
- return value;
- };
- // This is an experimental feature. Works only in Dart.
- AbstractChangeDetector.prototype.observeComponent = function (value) {
- var _this = this;
- if (observable_facade_1.isObservable(value)) {
- this._createArrayToStoreObservables();
- var index = this.numberOfPropertyProtoRecords + 1;
- this.streams[index] = value.changes;
- this.subscriptions[index] = value.changes.listen(function (_) { return _this.ref.markForCheck(); });
- }
- return value;
- };
- AbstractChangeDetector.prototype._createArrayToStoreObservables = function () {
- if (lang_1.isBlank(this.subscriptions)) {
- this.subscriptions = collection_1.ListWrapper.createFixedSize(this.numberOfPropertyProtoRecords +
- this.directiveIndices.length + 2);
- this.streams = collection_1.ListWrapper.createFixedSize(this.numberOfPropertyProtoRecords +
- this.directiveIndices.length + 2);
- }
- };
- AbstractChangeDetector.prototype.getDirectiveFor = function (directives, index) {
- return directives.getDirectiveFor(this.directiveIndices[index]);
- };
- AbstractChangeDetector.prototype.getDetectorFor = function (directives, index) {
- return directives.getDetectorFor(this.directiveIndices[index]);
- };
- AbstractChangeDetector.prototype.notifyDispatcher = function (value) {
- this.dispatcher.notifyOnBinding(this._currentBinding(), value);
- };
- AbstractChangeDetector.prototype.logBindingUpdate = function (value) {
- this.dispatcher.logBindingUpdate(this._currentBinding(), value);
- };
- AbstractChangeDetector.prototype.addChange = function (changes, oldValue, newValue) {
- if (lang_1.isBlank(changes)) {
- changes = {};
- }
- changes[this._currentBinding().name] = change_detection_util_1.ChangeDetectionUtil.simpleChange(oldValue, newValue);
- return changes;
- };
- AbstractChangeDetector.prototype._throwError = function (exception, stack) {
- var error;
- try {
- var c = this.dispatcher.getDebugContext(this._currentBinding().elementIndex, null);
- var context = lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.context, c.locals, c.injector, this._currentBinding().debug) :
- null;
- error = new exceptions_1.ChangeDetectionError(this._currentBinding().debug, exception, stack, context);
- }
- catch (e) {
- // if an error happens during getting the debug context, we throw a ChangeDetectionError
- // without the extra information.
- error = new exceptions_1.ChangeDetectionError(null, exception, stack, null);
- }
- throw error;
- };
- AbstractChangeDetector.prototype.throwOnChangeError = function (oldValue, newValue) {
- throw new exceptions_1.ExpressionChangedAfterItHasBeenCheckedException(this._currentBinding().debug, oldValue, newValue, null);
- };
- AbstractChangeDetector.prototype.throwDehydratedError = function () { throw new exceptions_1.DehydratedException(); };
- AbstractChangeDetector.prototype._currentBinding = function () {
- return this.bindingTargets[this.propertyBindingIndex];
- };
- return AbstractChangeDetector;
- })();
- exports.AbstractChangeDetector = AbstractChangeDetector;
- /***/ },
- /* 44 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var constants_1 = __webpack_require__(36);
- var ChangeDetectorRef = (function () {
- function ChangeDetectorRef() {
- }
- return ChangeDetectorRef;
- })();
- exports.ChangeDetectorRef = ChangeDetectorRef;
- var ChangeDetectorRef_ = (function (_super) {
- __extends(ChangeDetectorRef_, _super);
- function ChangeDetectorRef_(_cd) {
- _super.call(this);
- this._cd = _cd;
- }
- ChangeDetectorRef_.prototype.markForCheck = function () { this._cd.markPathToRootAsCheckOnce(); };
- ChangeDetectorRef_.prototype.detach = function () { this._cd.mode = constants_1.ChangeDetectionStrategy.Detached; };
- ChangeDetectorRef_.prototype.detectChanges = function () { this._cd.detectChanges(); };
- ChangeDetectorRef_.prototype.checkNoChanges = function () { this._cd.checkNoChanges(); };
- ChangeDetectorRef_.prototype.reattach = function () {
- this._cd.mode = constants_1.ChangeDetectionStrategy.CheckAlways;
- this.markForCheck();
- };
- return ChangeDetectorRef_;
- })(ChangeDetectorRef);
- exports.ChangeDetectorRef_ = ChangeDetectorRef_;
- /***/ },
- /* 45 */
- /***/ function(module, exports, __webpack_require__) {
- var impl = __webpack_require__(46);
- // Change exports to const once https://github.com/angular/ts2dart/issues/150
- /**
- * True if WTF is enabled.
- */
- exports.wtfEnabled = impl.detectWTF();
- function noopScope(arg0, arg1) {
- return null;
- }
- /**
- * Create trace scope.
- *
- * Scopes must be strictly nested and are analogous to stack frames, but
- * do not have to follow the stack frames. Instead it is recommended that they follow logical
- * nesting. You may want to use
- * [Event
- * Signatures](http://google.github.io/tracing-framework/instrumenting-code.html#custom-events)
- * as they are defined in WTF.
- *
- * Used to mark scope entry. The return value is used to leave the scope.
- *
- * var myScope = wtfCreateScope('MyClass#myMethod(ascii someVal)');
- *
- * someMethod() {
- * var s = myScope('Foo'); // 'Foo' gets stored in tracing UI
- * // DO SOME WORK HERE
- * return wtfLeave(s, 123); // Return value 123
- * }
- *
- * Note, adding try-finally block around the work to ensure that `wtfLeave` gets called can
- * negatively impact the performance of your application. For this reason we recommend that
- * you don't add them to ensure that `wtfLeave` gets called. In production `wtfLeave` is a noop and
- * so try-finally block has no value. When debugging perf issues, skipping `wtfLeave`, do to
- * exception, will produce incorrect trace, but presence of exception signifies logic error which
- * needs to be fixed before the app should be profiled. Add try-finally only when you expect that
- * an exception is expected during normal execution while profiling.
- *
- */
- exports.wtfCreateScope = exports.wtfEnabled ? impl.createScope : function (signature, flags) { return noopScope; };
- /**
- * Used to mark end of Scope.
- *
- * - `scope` to end.
- * - `returnValue` (optional) to be passed to the WTF.
- *
- * Returns the `returnValue for easy chaining.
- */
- exports.wtfLeave = exports.wtfEnabled ? impl.leave : function (s, r) { return r; };
- /**
- * Used to mark Async start. Async are similar to scope but they don't have to be strictly nested.
- * The return value is used in the call to [endAsync]. Async ranges only work if WTF has been
- * enabled.
- *
- * someMethod() {
- * var s = wtfStartTimeRange('HTTP:GET', 'some.url');
- * var future = new Future.delay(5).then((_) {
- * wtfEndTimeRange(s);
- * });
- * }
- */
- exports.wtfStartTimeRange = exports.wtfEnabled ? impl.startTimeRange : function (rangeType, action) { return null; };
- /**
- * Ends a async time range operation.
- * [range] is the return value from [wtfStartTimeRange] Async ranges only work if WTF has been
- * enabled.
- */
- exports.wtfEndTimeRange = exports.wtfEnabled ? impl.endTimeRange : function (r) {
- return null;
- };
- /***/ },
- /* 46 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var trace;
- var events;
- function detectWTF() {
- var wtf = lang_1.global['wtf'];
- if (wtf) {
- trace = wtf['trace'];
- if (trace) {
- events = trace['events'];
- return true;
- }
- }
- return false;
- }
- exports.detectWTF = detectWTF;
- function createScope(signature, flags) {
- if (flags === void 0) { flags = null; }
- return events.createScope(signature, flags);
- }
- exports.createScope = createScope;
- function leave(scope, returnValue) {
- trace.leaveScope(scope, returnValue);
- return returnValue;
- }
- exports.leave = leave;
- function startTimeRange(rangeType, action) {
- return trace.beginTimeRange(rangeType, action);
- }
- exports.startTimeRange = startTimeRange;
- function endTimeRange(range) {
- trace.endTimeRange(range);
- }
- exports.endTimeRange = endTimeRange;
- /***/ },
- /* 47 */
- /***/ function(module, exports) {
- function isObservable(value) {
- return false;
- }
- exports.isObservable = isObservable;
- /***/ },
- /* 48 */
- /***/ function(module, exports) {
- (function (RecordType) {
- RecordType[RecordType["Self"] = 0] = "Self";
- RecordType[RecordType["Const"] = 1] = "Const";
- RecordType[RecordType["PrimitiveOp"] = 2] = "PrimitiveOp";
- RecordType[RecordType["PropertyRead"] = 3] = "PropertyRead";
- RecordType[RecordType["PropertyWrite"] = 4] = "PropertyWrite";
- RecordType[RecordType["Local"] = 5] = "Local";
- RecordType[RecordType["InvokeMethod"] = 6] = "InvokeMethod";
- RecordType[RecordType["InvokeClosure"] = 7] = "InvokeClosure";
- RecordType[RecordType["KeyedRead"] = 8] = "KeyedRead";
- RecordType[RecordType["KeyedWrite"] = 9] = "KeyedWrite";
- RecordType[RecordType["Pipe"] = 10] = "Pipe";
- RecordType[RecordType["Interpolate"] = 11] = "Interpolate";
- RecordType[RecordType["SafeProperty"] = 12] = "SafeProperty";
- RecordType[RecordType["CollectionLiteral"] = 13] = "CollectionLiteral";
- RecordType[RecordType["SafeMethodInvoke"] = 14] = "SafeMethodInvoke";
- RecordType[RecordType["DirectiveLifecycle"] = 15] = "DirectiveLifecycle";
- RecordType[RecordType["Chain"] = 16] = "Chain";
- RecordType[RecordType["SkipRecordsIf"] = 17] = "SkipRecordsIf";
- RecordType[RecordType["SkipRecordsIfNot"] = 18] = "SkipRecordsIfNot";
- RecordType[RecordType["SkipRecords"] = 19] = "SkipRecords"; // Skip records unconditionally
- })(exports.RecordType || (exports.RecordType = {}));
- var RecordType = exports.RecordType;
- var ProtoRecord = (function () {
- function ProtoRecord(mode, name, funcOrValue, args, fixedArgs, contextIndex, directiveIndex, selfIndex, bindingRecord, lastInBinding, lastInDirective, argumentToPureFunction, referencedBySelf, propertyBindingIndex) {
- this.mode = mode;
- this.name = name;
- this.funcOrValue = funcOrValue;
- this.args = args;
- this.fixedArgs = fixedArgs;
- this.contextIndex = contextIndex;
- this.directiveIndex = directiveIndex;
- this.selfIndex = selfIndex;
- this.bindingRecord = bindingRecord;
- this.lastInBinding = lastInBinding;
- this.lastInDirective = lastInDirective;
- this.argumentToPureFunction = argumentToPureFunction;
- this.referencedBySelf = referencedBySelf;
- this.propertyBindingIndex = propertyBindingIndex;
- }
- ProtoRecord.prototype.isPureFunction = function () {
- return this.mode === RecordType.Interpolate || this.mode === RecordType.CollectionLiteral;
- };
- ProtoRecord.prototype.isUsedByOtherRecord = function () { return !this.lastInBinding || this.referencedBySelf; };
- ProtoRecord.prototype.shouldBeChecked = function () {
- return this.argumentToPureFunction || this.lastInBinding || this.isPureFunction() ||
- this.isPipeRecord();
- };
- ProtoRecord.prototype.isPipeRecord = function () { return this.mode === RecordType.Pipe; };
- ProtoRecord.prototype.isConditionalSkipRecord = function () {
- return this.mode === RecordType.SkipRecordsIfNot || this.mode === RecordType.SkipRecordsIf;
- };
- ProtoRecord.prototype.isUnconditionalSkipRecord = function () { return this.mode === RecordType.SkipRecords; };
- ProtoRecord.prototype.isSkipRecord = function () {
- return this.isConditionalSkipRecord() || this.isUnconditionalSkipRecord();
- };
- ProtoRecord.prototype.isLifeCycleRecord = function () { return this.mode === RecordType.DirectiveLifecycle; };
- return ProtoRecord;
- })();
- exports.ProtoRecord = ProtoRecord;
- /***/ },
- /* 49 */
- /***/ function(module, exports) {
- var EventBinding = (function () {
- function EventBinding(eventName, elIndex, dirIndex, records) {
- this.eventName = eventName;
- this.elIndex = elIndex;
- this.dirIndex = dirIndex;
- this.records = records;
- }
- return EventBinding;
- })();
- exports.EventBinding = EventBinding;
- /***/ },
- /* 50 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var proto_record_1 = __webpack_require__(48);
- /**
- * Removes "duplicate" records. It assumes that record evaluation does not have side-effects.
- *
- * Records that are not last in bindings are removed and all the indices of the records that depend
- * on them are updated.
- *
- * Records that are last in bindings CANNOT be removed, and instead are replaced with very cheap
- * SELF records.
- *
- * @internal
- */
- function coalesce(srcRecords) {
- var dstRecords = [];
- var excludedIdxs = [];
- var indexMap = new collection_1.Map();
- var skipDepth = 0;
- var skipSources = collection_1.ListWrapper.createFixedSize(srcRecords.length);
- for (var protoIndex = 0; protoIndex < srcRecords.length; protoIndex++) {
- var skipRecord = skipSources[protoIndex];
- if (lang_1.isPresent(skipRecord)) {
- skipDepth--;
- skipRecord.fixedArgs[0] = dstRecords.length;
- }
- var src = srcRecords[protoIndex];
- var dst = _cloneAndUpdateIndexes(src, dstRecords, indexMap);
- if (dst.isSkipRecord()) {
- dstRecords.push(dst);
- skipDepth++;
- skipSources[dst.fixedArgs[0]] = dst;
- }
- else {
- var record = _mayBeAddRecord(dst, dstRecords, excludedIdxs, skipDepth > 0);
- indexMap.set(src.selfIndex, record.selfIndex);
- }
- }
- return _optimizeSkips(dstRecords);
- }
- exports.coalesce = coalesce;
- /**
- * - Conditional skip of 1 record followed by an unconditional skip of N are replaced by a
- * conditional skip of N with the negated condition,
- * - Skips of 0 records are removed
- */
- function _optimizeSkips(srcRecords) {
- var dstRecords = [];
- var skipSources = collection_1.ListWrapper.createFixedSize(srcRecords.length);
- var indexMap = new collection_1.Map();
- for (var protoIndex = 0; protoIndex < srcRecords.length; protoIndex++) {
- var skipRecord = skipSources[protoIndex];
- if (lang_1.isPresent(skipRecord)) {
- skipRecord.fixedArgs[0] = dstRecords.length;
- }
- var src = srcRecords[protoIndex];
- if (src.isSkipRecord()) {
- if (src.isConditionalSkipRecord() && src.fixedArgs[0] === protoIndex + 2 &&
- protoIndex < srcRecords.length - 1 &&
- srcRecords[protoIndex + 1].mode === proto_record_1.RecordType.SkipRecords) {
- src.mode = src.mode === proto_record_1.RecordType.SkipRecordsIf ? proto_record_1.RecordType.SkipRecordsIfNot :
- proto_record_1.RecordType.SkipRecordsIf;
- src.fixedArgs[0] = srcRecords[protoIndex + 1].fixedArgs[0];
- protoIndex++;
- }
- if (src.fixedArgs[0] > protoIndex + 1) {
- var dst = _cloneAndUpdateIndexes(src, dstRecords, indexMap);
- dstRecords.push(dst);
- skipSources[dst.fixedArgs[0]] = dst;
- }
- }
- else {
- var dst = _cloneAndUpdateIndexes(src, dstRecords, indexMap);
- dstRecords.push(dst);
- indexMap.set(src.selfIndex, dst.selfIndex);
- }
- }
- return dstRecords;
- }
- /**
- * Add a new record or re-use one of the existing records.
- */
- function _mayBeAddRecord(record, dstRecords, excludedIdxs, excluded) {
- var match = _findFirstMatch(record, dstRecords, excludedIdxs);
- if (lang_1.isPresent(match)) {
- if (record.lastInBinding) {
- dstRecords.push(_createSelfRecord(record, match.selfIndex, dstRecords.length + 1));
- match.referencedBySelf = true;
- }
- else {
- if (record.argumentToPureFunction) {
- match.argumentToPureFunction = true;
- }
- }
- return match;
- }
- if (excluded) {
- excludedIdxs.push(record.selfIndex);
- }
- dstRecords.push(record);
- return record;
- }
- /**
- * Returns the first `ProtoRecord` that matches the record.
- */
- function _findFirstMatch(record, dstRecords, excludedIdxs) {
- return dstRecords.find(
- // TODO(vicb): optimize excludedIdxs.indexOf (sorted array)
- function (rr) { return excludedIdxs.indexOf(rr.selfIndex) == -1 && rr.mode !== proto_record_1.RecordType.DirectiveLifecycle &&
- _haveSameDirIndex(rr, record) && rr.mode === record.mode &&
- lang_1.looseIdentical(rr.funcOrValue, record.funcOrValue) &&
- rr.contextIndex === record.contextIndex && lang_1.looseIdentical(rr.name, record.name) &&
- collection_1.ListWrapper.equals(rr.args, record.args); });
- }
- /**
- * Clone the `ProtoRecord` and changes the indexes for the ones in the destination array for:
- * - the arguments,
- * - the context,
- * - self
- */
- function _cloneAndUpdateIndexes(record, dstRecords, indexMap) {
- var args = record.args.map(function (src) { return _srcToDstSelfIndex(indexMap, src); });
- var contextIndex = _srcToDstSelfIndex(indexMap, record.contextIndex);
- var selfIndex = dstRecords.length + 1;
- return new proto_record_1.ProtoRecord(record.mode, record.name, record.funcOrValue, args, record.fixedArgs, contextIndex, record.directiveIndex, selfIndex, record.bindingRecord, record.lastInBinding, record.lastInDirective, record.argumentToPureFunction, record.referencedBySelf, record.propertyBindingIndex);
- }
- /**
- * Returns the index in the destination array corresponding to the index in the src array.
- * When the element is not present in the destination array, return the source index.
- */
- function _srcToDstSelfIndex(indexMap, srcIdx) {
- var dstIdx = indexMap.get(srcIdx);
- return lang_1.isPresent(dstIdx) ? dstIdx : srcIdx;
- }
- function _createSelfRecord(r, contextIndex, selfIndex) {
- return new proto_record_1.ProtoRecord(proto_record_1.RecordType.Self, "self", null, [], r.fixedArgs, contextIndex, r.directiveIndex, selfIndex, r.bindingRecord, r.lastInBinding, r.lastInDirective, false, false, r.propertyBindingIndex);
- }
- function _haveSameDirIndex(a, b) {
- var di1 = lang_1.isBlank(a.directiveIndex) ? null : a.directiveIndex.directiveIndex;
- var ei1 = lang_1.isBlank(a.directiveIndex) ? null : a.directiveIndex.elementIndex;
- var di2 = lang_1.isBlank(b.directiveIndex) ? null : b.directiveIndex.directiveIndex;
- var ei2 = lang_1.isBlank(b.directiveIndex) ? null : b.directiveIndex.elementIndex;
- return di1 === di2 && ei1 === ei2;
- }
- /***/ },
- /* 51 */
- /***/ function(module, exports, __webpack_require__) {
- var change_detection_jit_generator_1 = __webpack_require__(52);
- var JitProtoChangeDetector = (function () {
- function JitProtoChangeDetector(definition) {
- this.definition = definition;
- this._factory = this._createFactory(definition);
- }
- JitProtoChangeDetector.isSupported = function () { return true; };
- JitProtoChangeDetector.prototype.instantiate = function (dispatcher) { return this._factory(dispatcher); };
- /** @internal */
- JitProtoChangeDetector.prototype._createFactory = function (definition) {
- return new change_detection_jit_generator_1.ChangeDetectorJITGenerator(definition, 'util', 'AbstractChangeDetector', 'ChangeDetectorStatus')
- .generate();
- };
- return JitProtoChangeDetector;
- })();
- exports.JitProtoChangeDetector = JitProtoChangeDetector;
- /***/ },
- /* 52 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var abstract_change_detector_1 = __webpack_require__(43);
- var change_detection_util_1 = __webpack_require__(38);
- var proto_record_1 = __webpack_require__(48);
- var codegen_name_util_1 = __webpack_require__(53);
- var codegen_logic_util_1 = __webpack_require__(54);
- var codegen_facade_1 = __webpack_require__(55);
- var constants_1 = __webpack_require__(36);
- var proto_change_detector_1 = __webpack_require__(37);
- /**
- * The code generator takes a list of proto records and creates a function/class
- * that "emulates" what the developer would write by hand to implement the same
- * kind of behaviour.
- *
- * This code should be kept in sync with the Dart transformer's
- * `angular2.transform.template_compiler.change_detector_codegen` library. If you make updates
- * here, please make equivalent changes there.
- */
- var IS_CHANGED_LOCAL = "isChanged";
- var CHANGES_LOCAL = "changes";
- var ChangeDetectorJITGenerator = (function () {
- function ChangeDetectorJITGenerator(definition, changeDetectionUtilVarName, abstractChangeDetectorVarName, changeDetectorStateVarName) {
- this.changeDetectionUtilVarName = changeDetectionUtilVarName;
- this.abstractChangeDetectorVarName = abstractChangeDetectorVarName;
- this.changeDetectorStateVarName = changeDetectorStateVarName;
- var propertyBindingRecords = proto_change_detector_1.createPropertyRecords(definition);
- var eventBindingRecords = proto_change_detector_1.createEventRecords(definition);
- var propertyBindingTargets = definition.bindingRecords.map(function (b) { return b.target; });
- this.id = definition.id;
- this.changeDetectionStrategy = definition.strategy;
- this.genConfig = definition.genConfig;
- this.records = propertyBindingRecords;
- this.propertyBindingTargets = propertyBindingTargets;
- this.eventBindings = eventBindingRecords;
- this.directiveRecords = definition.directiveRecords;
- this._names = new codegen_name_util_1.CodegenNameUtil(this.records, this.eventBindings, this.directiveRecords, this.changeDetectionUtilVarName);
- this._logic =
- new codegen_logic_util_1.CodegenLogicUtil(this._names, this.changeDetectionUtilVarName, this.changeDetectorStateVarName, this.changeDetectionStrategy);
- this.typeName = codegen_name_util_1.sanitizeName("ChangeDetector_" + this.id);
- }
- ChangeDetectorJITGenerator.prototype.generate = function () {
- var factorySource = "\n " + this.generateSource() + "\n return function(dispatcher) {\n return new " + this.typeName + "(dispatcher);\n }\n ";
- return new Function(this.abstractChangeDetectorVarName, this.changeDetectionUtilVarName, this.changeDetectorStateVarName, factorySource)(abstract_change_detector_1.AbstractChangeDetector, change_detection_util_1.ChangeDetectionUtil, constants_1.ChangeDetectorState);
- };
- ChangeDetectorJITGenerator.prototype.generateSource = function () {
- return "\n var " + this.typeName + " = function " + this.typeName + "(dispatcher) {\n " + this.abstractChangeDetectorVarName + ".call(\n this, " + JSON.stringify(this.id) + ", dispatcher, " + this.records.length + ",\n " + this.typeName + ".gen_propertyBindingTargets, " + this.typeName + ".gen_directiveIndices,\n " + codegen_facade_1.codify(this.changeDetectionStrategy) + ");\n this.dehydrateDirectives(false);\n }\n\n " + this.typeName + ".prototype = Object.create(" + this.abstractChangeDetectorVarName + ".prototype);\n\n " + this.typeName + ".prototype.detectChangesInRecordsInternal = function(throwOnChange) {\n " + this._names.genInitLocals() + "\n var " + IS_CHANGED_LOCAL + " = false;\n var " + CHANGES_LOCAL + " = null;\n\n " + this._genAllRecords(this.records) + "\n }\n\n " + this._maybeGenHandleEventInternal() + "\n\n " + this._maybeGenAfterContentLifecycleCallbacks() + "\n\n " + this._maybeGenAfterViewLifecycleCallbacks() + "\n\n " + this._maybeGenHydrateDirectives() + "\n\n " + this._maybeGenDehydrateDirectives() + "\n\n " + this._genPropertyBindingTargets() + "\n\n " + this._genDirectiveIndices() + "\n ";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genPropertyBindingTargets = function () {
- var targets = this._logic.genPropertyBindingTargets(this.propertyBindingTargets, this.genConfig.genDebugInfo);
- return this.typeName + ".gen_propertyBindingTargets = " + targets + ";";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genDirectiveIndices = function () {
- var indices = this._logic.genDirectiveIndices(this.directiveRecords);
- return this.typeName + ".gen_directiveIndices = " + indices + ";";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeGenHandleEventInternal = function () {
- var _this = this;
- if (this.eventBindings.length > 0) {
- var handlers = this.eventBindings.map(function (eb) { return _this._genEventBinding(eb); }).join("\n");
- return "\n " + this.typeName + ".prototype.handleEventInternal = function(eventName, elIndex, locals) {\n var " + this._names.getPreventDefaultAccesor() + " = false;\n " + this._names.genInitEventLocals() + "\n " + handlers + "\n return " + this._names.getPreventDefaultAccesor() + ";\n }\n ";
- }
- else {
- return '';
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genEventBinding = function (eb) {
- var _this = this;
- var codes = [];
- this._endOfBlockIdxs = [];
- collection_1.ListWrapper.forEachWithIndex(eb.records, function (r, i) {
- var code;
- if (r.isConditionalSkipRecord()) {
- code = _this._genConditionalSkip(r, _this._names.getEventLocalName(eb, i));
- }
- else if (r.isUnconditionalSkipRecord()) {
- code = _this._genUnconditionalSkip(r);
- }
- else {
- code = _this._genEventBindingEval(eb, r);
- }
- code += _this._genEndOfSkipBlock(i);
- codes.push(code);
- });
- return "\n if (eventName === \"" + eb.eventName + "\" && elIndex === " + eb.elIndex + ") {\n " + codes.join("\n") + "\n }";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genEventBindingEval = function (eb, r) {
- if (r.lastInBinding) {
- var evalRecord = this._logic.genEventBindingEvalValue(eb, r);
- var markPath = this._genMarkPathToRootAsCheckOnce(r);
- var prevDefault = this._genUpdatePreventDefault(eb, r);
- return evalRecord + "\n" + markPath + "\n" + prevDefault;
- }
- else {
- return this._logic.genEventBindingEvalValue(eb, r);
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genMarkPathToRootAsCheckOnce = function (r) {
- var br = r.bindingRecord;
- if (br.isDefaultChangeDetection()) {
- return "";
- }
- else {
- return this._names.getDetectorName(br.directiveRecord.directiveIndex) + ".markPathToRootAsCheckOnce();";
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genUpdatePreventDefault = function (eb, r) {
- var local = this._names.getEventLocalName(eb, r.selfIndex);
- return "if (" + local + " === false) { " + this._names.getPreventDefaultAccesor() + " = true};";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeGenDehydrateDirectives = function () {
- var destroyPipesCode = this._names.genPipeOnDestroy();
- if (destroyPipesCode) {
- destroyPipesCode = "if (destroyPipes) { " + destroyPipesCode + " }";
- }
- var dehydrateFieldsCode = this._names.genDehydrateFields();
- if (!destroyPipesCode && !dehydrateFieldsCode)
- return '';
- return this.typeName + ".prototype.dehydrateDirectives = function(destroyPipes) {\n " + destroyPipesCode + "\n " + dehydrateFieldsCode + "\n }";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeGenHydrateDirectives = function () {
- var hydrateDirectivesCode = this._logic.genHydrateDirectives(this.directiveRecords);
- var hydrateDetectorsCode = this._logic.genHydrateDetectors(this.directiveRecords);
- if (!hydrateDirectivesCode && !hydrateDetectorsCode)
- return '';
- return this.typeName + ".prototype.hydrateDirectives = function(directives) {\n " + hydrateDirectivesCode + "\n " + hydrateDetectorsCode + "\n }";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeGenAfterContentLifecycleCallbacks = function () {
- var notifications = this._logic.genContentLifecycleCallbacks(this.directiveRecords);
- if (notifications.length > 0) {
- var directiveNotifications = notifications.join("\n");
- return "\n " + this.typeName + ".prototype.afterContentLifecycleCallbacksInternal = function() {\n " + directiveNotifications + "\n }\n ";
- }
- else {
- return '';
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeGenAfterViewLifecycleCallbacks = function () {
- var notifications = this._logic.genViewLifecycleCallbacks(this.directiveRecords);
- if (notifications.length > 0) {
- var directiveNotifications = notifications.join("\n");
- return "\n " + this.typeName + ".prototype.afterViewLifecycleCallbacksInternal = function() {\n " + directiveNotifications + "\n }\n ";
- }
- else {
- return '';
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genAllRecords = function (rs) {
- var codes = [];
- this._endOfBlockIdxs = [];
- for (var i = 0; i < rs.length; i++) {
- var code = void 0;
- var r = rs[i];
- if (r.isLifeCycleRecord()) {
- code = this._genDirectiveLifecycle(r);
- }
- else if (r.isPipeRecord()) {
- code = this._genPipeCheck(r);
- }
- else if (r.isConditionalSkipRecord()) {
- code = this._genConditionalSkip(r, this._names.getLocalName(r.contextIndex));
- }
- else if (r.isUnconditionalSkipRecord()) {
- code = this._genUnconditionalSkip(r);
- }
- else {
- code = this._genReferenceCheck(r);
- }
- code = "\n " + this._maybeFirstInBinding(r) + "\n " + code + "\n " + this._maybeGenLastInDirective(r) + "\n " + this._genEndOfSkipBlock(i) + "\n ";
- codes.push(code);
- }
- return codes.join("\n");
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genConditionalSkip = function (r, condition) {
- var maybeNegate = r.mode === proto_record_1.RecordType.SkipRecordsIf ? '!' : '';
- this._endOfBlockIdxs.push(r.fixedArgs[0] - 1);
- return "if (" + maybeNegate + condition + ") {";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genUnconditionalSkip = function (r) {
- this._endOfBlockIdxs.pop();
- this._endOfBlockIdxs.push(r.fixedArgs[0] - 1);
- return "} else {";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genEndOfSkipBlock = function (protoIndex) {
- if (!collection_1.ListWrapper.isEmpty(this._endOfBlockIdxs)) {
- var endOfBlock = collection_1.ListWrapper.last(this._endOfBlockIdxs);
- if (protoIndex === endOfBlock) {
- this._endOfBlockIdxs.pop();
- return '}';
- }
- }
- return '';
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genDirectiveLifecycle = function (r) {
- if (r.name === "DoCheck") {
- return this._genOnCheck(r);
- }
- else if (r.name === "OnInit") {
- return this._genOnInit(r);
- }
- else if (r.name === "OnChanges") {
- return this._genOnChange(r);
- }
- else {
- throw new exceptions_1.BaseException("Unknown lifecycle event '" + r.name + "'");
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genPipeCheck = function (r) {
- var _this = this;
- var context = this._names.getLocalName(r.contextIndex);
- var argString = r.args.map(function (arg) { return _this._names.getLocalName(arg); }).join(", ");
- var oldValue = this._names.getFieldName(r.selfIndex);
- var newValue = this._names.getLocalName(r.selfIndex);
- var pipe = this._names.getPipeName(r.selfIndex);
- var pipeName = r.name;
- var init = "\n if (" + pipe + " === " + this.changeDetectionUtilVarName + ".uninitialized) {\n " + pipe + " = " + this._names.getPipesAccessorName() + ".get('" + pipeName + "');\n }\n ";
- var read = newValue + " = " + pipe + ".pipe.transform(" + context + ", [" + argString + "]);";
- var contexOrArgCheck = r.args.map(function (a) { return _this._names.getChangeName(a); });
- contexOrArgCheck.push(this._names.getChangeName(r.contextIndex));
- var condition = "!" + pipe + ".pure || (" + contexOrArgCheck.join(" || ") + ")";
- var check = "\n if (" + this.changeDetectionUtilVarName + ".looseNotIdentical(" + oldValue + ", " + newValue + ")) {\n " + newValue + " = " + this.changeDetectionUtilVarName + ".unwrapValue(" + newValue + ")\n " + this._genChangeMarker(r) + "\n " + this._genUpdateDirectiveOrElement(r) + "\n " + this._genAddToChanges(r) + "\n " + oldValue + " = " + newValue + ";\n }\n ";
- var genCode = r.shouldBeChecked() ? "" + read + check : read;
- if (r.isUsedByOtherRecord()) {
- return init + " if (" + condition + ") { " + genCode + " } else { " + newValue + " = " + oldValue + "; }";
- }
- else {
- return init + " if (" + condition + ") { " + genCode + " }";
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genReferenceCheck = function (r) {
- var _this = this;
- var oldValue = this._names.getFieldName(r.selfIndex);
- var newValue = this._names.getLocalName(r.selfIndex);
- var read = "\n " + this._logic.genPropertyBindingEvalValue(r) + "\n ";
- var check = "\n if (" + this.changeDetectionUtilVarName + ".looseNotIdentical(" + oldValue + ", " + newValue + ")) {\n " + this._genChangeMarker(r) + "\n " + this._genUpdateDirectiveOrElement(r) + "\n " + this._genAddToChanges(r) + "\n " + oldValue + " = " + newValue + ";\n }\n ";
- var genCode = r.shouldBeChecked() ? "" + read + check : read;
- if (r.isPureFunction()) {
- var condition = r.args.map(function (a) { return _this._names.getChangeName(a); }).join(" || ");
- if (r.isUsedByOtherRecord()) {
- return "if (" + condition + ") { " + genCode + " } else { " + newValue + " = " + oldValue + "; }";
- }
- else {
- return "if (" + condition + ") { " + genCode + " }";
- }
- }
- else {
- return genCode;
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genChangeMarker = function (r) {
- return r.argumentToPureFunction ? this._names.getChangeName(r.selfIndex) + " = true" : "";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genUpdateDirectiveOrElement = function (r) {
- if (!r.lastInBinding)
- return "";
- var newValue = this._names.getLocalName(r.selfIndex);
- var oldValue = this._names.getFieldName(r.selfIndex);
- var notifyDebug = this.genConfig.logBindingUpdate ? "this.logBindingUpdate(" + newValue + ");" : "";
- var br = r.bindingRecord;
- if (br.target.isDirective()) {
- var directiveProperty = this._names.getDirectiveName(br.directiveRecord.directiveIndex) + "." + br.target.name;
- return "\n " + this._genThrowOnChangeCheck(oldValue, newValue) + "\n " + directiveProperty + " = " + newValue + ";\n " + notifyDebug + "\n " + IS_CHANGED_LOCAL + " = true;\n ";
- }
- else {
- return "\n " + this._genThrowOnChangeCheck(oldValue, newValue) + "\n this.notifyDispatcher(" + newValue + ");\n " + notifyDebug + "\n ";
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genThrowOnChangeCheck = function (oldValue, newValue) {
- if (lang_1.assertionsEnabled()) {
- return "\n if(throwOnChange) {\n this.throwOnChangeError(" + oldValue + ", " + newValue + ");\n }\n ";
- }
- else {
- return '';
- }
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genAddToChanges = function (r) {
- var newValue = this._names.getLocalName(r.selfIndex);
- var oldValue = this._names.getFieldName(r.selfIndex);
- if (!r.bindingRecord.callOnChanges())
- return "";
- return CHANGES_LOCAL + " = this.addChange(" + CHANGES_LOCAL + ", " + oldValue + ", " + newValue + ");";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeFirstInBinding = function (r) {
- var prev = change_detection_util_1.ChangeDetectionUtil.protoByIndex(this.records, r.selfIndex - 1);
- var firstInBinding = lang_1.isBlank(prev) || prev.bindingRecord !== r.bindingRecord;
- return firstInBinding && !r.bindingRecord.isDirectiveLifecycle() ?
- this._names.getPropertyBindingIndex() + " = " + r.propertyBindingIndex + ";" :
- '';
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._maybeGenLastInDirective = function (r) {
- if (!r.lastInDirective)
- return "";
- return "\n " + CHANGES_LOCAL + " = null;\n " + this._genNotifyOnPushDetectors(r) + "\n " + IS_CHANGED_LOCAL + " = false;\n ";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genOnCheck = function (r) {
- var br = r.bindingRecord;
- return "if (!throwOnChange) " + this._names.getDirectiveName(br.directiveRecord.directiveIndex) + ".ngDoCheck();";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genOnInit = function (r) {
- var br = r.bindingRecord;
- return "if (!throwOnChange && " + this._names.getStateName() + " === " + this.changeDetectorStateVarName + ".NeverChecked) " + this._names.getDirectiveName(br.directiveRecord.directiveIndex) + ".ngOnInit();";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genOnChange = function (r) {
- var br = r.bindingRecord;
- return "if (!throwOnChange && " + CHANGES_LOCAL + ") " + this._names.getDirectiveName(br.directiveRecord.directiveIndex) + ".ngOnChanges(" + CHANGES_LOCAL + ");";
- };
- /** @internal */
- ChangeDetectorJITGenerator.prototype._genNotifyOnPushDetectors = function (r) {
- var br = r.bindingRecord;
- if (!r.lastInDirective || br.isDefaultChangeDetection())
- return "";
- var retVal = "\n if(" + IS_CHANGED_LOCAL + ") {\n " + this._names.getDetectorName(br.directiveRecord.directiveIndex) + ".markAsCheckOnce();\n }\n ";
- return retVal;
- };
- return ChangeDetectorJITGenerator;
- })();
- exports.ChangeDetectorJITGenerator = ChangeDetectorJITGenerator;
- /***/ },
- /* 53 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- // The names of these fields must be kept in sync with abstract_change_detector.ts or change
- // detection will fail.
- var _STATE_ACCESSOR = "state";
- var _CONTEXT_ACCESSOR = "context";
- var _PROP_BINDING_INDEX = "propertyBindingIndex";
- var _DIRECTIVES_ACCESSOR = "directiveIndices";
- var _DISPATCHER_ACCESSOR = "dispatcher";
- var _LOCALS_ACCESSOR = "locals";
- var _MODE_ACCESSOR = "mode";
- var _PIPES_ACCESSOR = "pipes";
- var _PROTOS_ACCESSOR = "protos";
- exports.CONTEXT_ACCESSOR = "context";
- // `context` is always first.
- exports.CONTEXT_INDEX = 0;
- var _FIELD_PREFIX = 'this.';
- var _whiteSpaceRegExp = /\W/g;
- /**
- * Returns `s` with all non-identifier characters removed.
- */
- function sanitizeName(s) {
- return lang_1.StringWrapper.replaceAll(s, _whiteSpaceRegExp, '');
- }
- exports.sanitizeName = sanitizeName;
- /**
- * Class responsible for providing field and local variable names for change detector classes.
- * Also provides some convenience functions, for example, declaring variables, destroying pipes,
- * and dehydrating the detector.
- */
- var CodegenNameUtil = (function () {
- function CodegenNameUtil(_records, _eventBindings, _directiveRecords, _utilName) {
- this._records = _records;
- this._eventBindings = _eventBindings;
- this._directiveRecords = _directiveRecords;
- this._utilName = _utilName;
- /** @internal */
- this._sanitizedEventNames = new collection_1.Map();
- this._sanitizedNames = collection_1.ListWrapper.createFixedSize(this._records.length + 1);
- this._sanitizedNames[exports.CONTEXT_INDEX] = exports.CONTEXT_ACCESSOR;
- for (var i = 0, iLen = this._records.length; i < iLen; ++i) {
- this._sanitizedNames[i + 1] = sanitizeName("" + this._records[i].name + i);
- }
- for (var ebIndex = 0; ebIndex < _eventBindings.length; ++ebIndex) {
- var eb = _eventBindings[ebIndex];
- var names = [exports.CONTEXT_ACCESSOR];
- for (var i = 0, iLen = eb.records.length; i < iLen; ++i) {
- names.push(sanitizeName("" + eb.records[i].name + i + "_" + ebIndex));
- }
- this._sanitizedEventNames.set(eb, names);
- }
- }
- /** @internal */
- CodegenNameUtil.prototype._addFieldPrefix = function (name) { return "" + _FIELD_PREFIX + name; };
- CodegenNameUtil.prototype.getDispatcherName = function () { return this._addFieldPrefix(_DISPATCHER_ACCESSOR); };
- CodegenNameUtil.prototype.getPipesAccessorName = function () { return this._addFieldPrefix(_PIPES_ACCESSOR); };
- CodegenNameUtil.prototype.getProtosName = function () { return this._addFieldPrefix(_PROTOS_ACCESSOR); };
- CodegenNameUtil.prototype.getDirectivesAccessorName = function () { return this._addFieldPrefix(_DIRECTIVES_ACCESSOR); };
- CodegenNameUtil.prototype.getLocalsAccessorName = function () { return this._addFieldPrefix(_LOCALS_ACCESSOR); };
- CodegenNameUtil.prototype.getStateName = function () { return this._addFieldPrefix(_STATE_ACCESSOR); };
- CodegenNameUtil.prototype.getModeName = function () { return this._addFieldPrefix(_MODE_ACCESSOR); };
- CodegenNameUtil.prototype.getPropertyBindingIndex = function () { return this._addFieldPrefix(_PROP_BINDING_INDEX); };
- CodegenNameUtil.prototype.getLocalName = function (idx) { return "l_" + this._sanitizedNames[idx]; };
- CodegenNameUtil.prototype.getEventLocalName = function (eb, idx) {
- return "l_" + this._sanitizedEventNames.get(eb)[idx];
- };
- CodegenNameUtil.prototype.getChangeName = function (idx) { return "c_" + this._sanitizedNames[idx]; };
- /**
- * Generate a statement initializing local variables used when detecting changes.
- */
- CodegenNameUtil.prototype.genInitLocals = function () {
- var declarations = [];
- var assignments = [];
- for (var i = 0, iLen = this.getFieldCount(); i < iLen; ++i) {
- if (i == exports.CONTEXT_INDEX) {
- declarations.push(this.getLocalName(i) + " = " + this.getFieldName(i));
- }
- else {
- var rec = this._records[i - 1];
- if (rec.argumentToPureFunction) {
- var changeName = this.getChangeName(i);
- declarations.push(this.getLocalName(i) + "," + changeName);
- assignments.push(changeName);
- }
- else {
- declarations.push("" + this.getLocalName(i));
- }
- }
- }
- var assignmentsCode = collection_1.ListWrapper.isEmpty(assignments) ? '' : assignments.join('=') + " = false;";
- return "var " + declarations.join(',') + ";" + assignmentsCode;
- };
- /**
- * Generate a statement initializing local variables for event handlers.
- */
- CodegenNameUtil.prototype.genInitEventLocals = function () {
- var _this = this;
- var res = [(this.getLocalName(exports.CONTEXT_INDEX) + " = " + this.getFieldName(exports.CONTEXT_INDEX))];
- this._sanitizedEventNames.forEach(function (names, eb) {
- for (var i = 0; i < names.length; ++i) {
- if (i !== exports.CONTEXT_INDEX) {
- res.push("" + _this.getEventLocalName(eb, i));
- }
- }
- });
- return res.length > 1 ? "var " + res.join(',') + ";" : '';
- };
- CodegenNameUtil.prototype.getPreventDefaultAccesor = function () { return "preventDefault"; };
- CodegenNameUtil.prototype.getFieldCount = function () { return this._sanitizedNames.length; };
- CodegenNameUtil.prototype.getFieldName = function (idx) { return this._addFieldPrefix(this._sanitizedNames[idx]); };
- CodegenNameUtil.prototype.getAllFieldNames = function () {
- var fieldList = [];
- for (var k = 0, kLen = this.getFieldCount(); k < kLen; ++k) {
- if (k === 0 || this._records[k - 1].shouldBeChecked()) {
- fieldList.push(this.getFieldName(k));
- }
- }
- for (var i = 0, iLen = this._records.length; i < iLen; ++i) {
- var rec = this._records[i];
- if (rec.isPipeRecord()) {
- fieldList.push(this.getPipeName(rec.selfIndex));
- }
- }
- for (var j = 0, jLen = this._directiveRecords.length; j < jLen; ++j) {
- var dRec = this._directiveRecords[j];
- fieldList.push(this.getDirectiveName(dRec.directiveIndex));
- if (!dRec.isDefaultChangeDetection()) {
- fieldList.push(this.getDetectorName(dRec.directiveIndex));
- }
- }
- return fieldList;
- };
- /**
- * Generates statements which clear all fields so that the change detector is dehydrated.
- */
- CodegenNameUtil.prototype.genDehydrateFields = function () {
- var fields = this.getAllFieldNames();
- collection_1.ListWrapper.removeAt(fields, exports.CONTEXT_INDEX);
- if (collection_1.ListWrapper.isEmpty(fields))
- return '';
- // At least one assignment.
- fields.push(this._utilName + ".uninitialized;");
- return fields.join(' = ');
- };
- /**
- * Generates statements destroying all pipe variables.
- */
- CodegenNameUtil.prototype.genPipeOnDestroy = function () {
- var _this = this;
- return this._records.filter(function (r) { return r.isPipeRecord(); })
- .map(function (r) { return (_this._utilName + ".callPipeOnDestroy(" + _this.getPipeName(r.selfIndex) + ");"); })
- .join('\n');
- };
- CodegenNameUtil.prototype.getPipeName = function (idx) {
- return this._addFieldPrefix(this._sanitizedNames[idx] + "_pipe");
- };
- CodegenNameUtil.prototype.getDirectiveName = function (d) {
- return this._addFieldPrefix("directive_" + d.name);
- };
- CodegenNameUtil.prototype.getDetectorName = function (d) { return this._addFieldPrefix("detector_" + d.name); };
- return CodegenNameUtil;
- })();
- exports.CodegenNameUtil = CodegenNameUtil;
- /***/ },
- /* 54 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var codegen_facade_1 = __webpack_require__(55);
- var proto_record_1 = __webpack_require__(48);
- var constants_1 = __webpack_require__(36);
- var exceptions_1 = __webpack_require__(14);
- /**
- * Class responsible for providing change detection logic for change detector classes.
- */
- var CodegenLogicUtil = (function () {
- function CodegenLogicUtil(_names, _utilName, _changeDetectorStateName, _changeDetection) {
- this._names = _names;
- this._utilName = _utilName;
- this._changeDetectorStateName = _changeDetectorStateName;
- this._changeDetection = _changeDetection;
- }
- /**
- * Generates a statement which updates the local variable representing `protoRec` with the current
- * value of the record. Used by property bindings.
- */
- CodegenLogicUtil.prototype.genPropertyBindingEvalValue = function (protoRec) {
- var _this = this;
- return this._genEvalValue(protoRec, function (idx) { return _this._names.getLocalName(idx); }, this._names.getLocalsAccessorName());
- };
- /**
- * Generates a statement which updates the local variable representing `protoRec` with the current
- * value of the record. Used by event bindings.
- */
- CodegenLogicUtil.prototype.genEventBindingEvalValue = function (eventRecord, protoRec) {
- var _this = this;
- return this._genEvalValue(protoRec, function (idx) { return _this._names.getEventLocalName(eventRecord, idx); }, "locals");
- };
- CodegenLogicUtil.prototype._genEvalValue = function (protoRec, getLocalName, localsAccessor) {
- var context = (protoRec.contextIndex == -1) ?
- this._names.getDirectiveName(protoRec.directiveIndex) :
- getLocalName(protoRec.contextIndex);
- var argString = protoRec.args.map(function (arg) { return getLocalName(arg); }).join(", ");
- var rhs;
- switch (protoRec.mode) {
- case proto_record_1.RecordType.Self:
- rhs = context;
- break;
- case proto_record_1.RecordType.Const:
- rhs = codegen_facade_1.codify(protoRec.funcOrValue);
- break;
- case proto_record_1.RecordType.PropertyRead:
- rhs = this._observe(context + "." + protoRec.name, protoRec);
- break;
- case proto_record_1.RecordType.SafeProperty:
- var read = this._observe(context + "." + protoRec.name, protoRec);
- rhs =
- this._utilName + ".isValueBlank(" + context + ") ? null : " + this._observe(read, protoRec);
- break;
- case proto_record_1.RecordType.PropertyWrite:
- rhs = context + "." + protoRec.name + " = " + getLocalName(protoRec.args[0]);
- break;
- case proto_record_1.RecordType.Local:
- rhs = this._observe(localsAccessor + ".get(" + codegen_facade_1.rawString(protoRec.name) + ")", protoRec);
- break;
- case proto_record_1.RecordType.InvokeMethod:
- rhs = this._observe(context + "." + protoRec.name + "(" + argString + ")", protoRec);
- break;
- case proto_record_1.RecordType.SafeMethodInvoke:
- var invoke = context + "." + protoRec.name + "(" + argString + ")";
- rhs =
- this._utilName + ".isValueBlank(" + context + ") ? null : " + this._observe(invoke, protoRec);
- break;
- case proto_record_1.RecordType.InvokeClosure:
- rhs = context + "(" + argString + ")";
- break;
- case proto_record_1.RecordType.PrimitiveOp:
- rhs = this._utilName + "." + protoRec.name + "(" + argString + ")";
- break;
- case proto_record_1.RecordType.CollectionLiteral:
- rhs = this._utilName + "." + protoRec.name + "(" + argString + ")";
- break;
- case proto_record_1.RecordType.Interpolate:
- rhs = this._genInterpolation(protoRec);
- break;
- case proto_record_1.RecordType.KeyedRead:
- rhs = this._observe(context + "[" + getLocalName(protoRec.args[0]) + "]", protoRec);
- break;
- case proto_record_1.RecordType.KeyedWrite:
- rhs = context + "[" + getLocalName(protoRec.args[0]) + "] = " + getLocalName(protoRec.args[1]);
- break;
- case proto_record_1.RecordType.Chain:
- rhs = 'null';
- break;
- default:
- throw new exceptions_1.BaseException("Unknown operation " + protoRec.mode);
- }
- return getLocalName(protoRec.selfIndex) + " = " + rhs + ";";
- };
- /** @internal */
- CodegenLogicUtil.prototype._observe = function (exp, rec) {
- // This is an experimental feature. Works only in Dart.
- if (this._changeDetection === constants_1.ChangeDetectionStrategy.OnPushObserve) {
- return "this.observeValue(" + exp + ", " + rec.selfIndex + ")";
- }
- else {
- return exp;
- }
- };
- CodegenLogicUtil.prototype.genPropertyBindingTargets = function (propertyBindingTargets, genDebugInfo) {
- var _this = this;
- var bs = propertyBindingTargets.map(function (b) {
- if (lang_1.isBlank(b))
- return "null";
- var debug = genDebugInfo ? codegen_facade_1.codify(b.debug) : "null";
- return _this._utilName + ".bindingTarget(" + codegen_facade_1.codify(b.mode) + ", " + b.elementIndex + ", " + codegen_facade_1.codify(b.name) + ", " + codegen_facade_1.codify(b.unit) + ", " + debug + ")";
- });
- return "[" + bs.join(", ") + "]";
- };
- CodegenLogicUtil.prototype.genDirectiveIndices = function (directiveRecords) {
- var _this = this;
- var bs = directiveRecords.map(function (b) {
- return (_this._utilName + ".directiveIndex(" + b.directiveIndex.elementIndex + ", " + b.directiveIndex.directiveIndex + ")");
- });
- return "[" + bs.join(", ") + "]";
- };
- /** @internal */
- CodegenLogicUtil.prototype._genInterpolation = function (protoRec) {
- var iVals = [];
- for (var i = 0; i < protoRec.args.length; ++i) {
- iVals.push(codegen_facade_1.codify(protoRec.fixedArgs[i]));
- iVals.push(this._utilName + ".s(" + this._names.getLocalName(protoRec.args[i]) + ")");
- }
- iVals.push(codegen_facade_1.codify(protoRec.fixedArgs[protoRec.args.length]));
- return codegen_facade_1.combineGeneratedStrings(iVals);
- };
- CodegenLogicUtil.prototype.genHydrateDirectives = function (directiveRecords) {
- var res = [];
- for (var i = 0; i < directiveRecords.length; ++i) {
- var r = directiveRecords[i];
- res.push(this._names.getDirectiveName(r.directiveIndex) + " = " + this._genReadDirective(i) + ";");
- }
- return res.join("\n");
- };
- CodegenLogicUtil.prototype._genReadDirective = function (index) {
- // This is an experimental feature. Works only in Dart.
- if (this._changeDetection === constants_1.ChangeDetectionStrategy.OnPushObserve) {
- return "this.observeDirective(this.getDirectiveFor(directives, " + index + "), " + index + ")";
- }
- else {
- return "this.getDirectiveFor(directives, " + index + ")";
- }
- };
- CodegenLogicUtil.prototype.genHydrateDetectors = function (directiveRecords) {
- var res = [];
- for (var i = 0; i < directiveRecords.length; ++i) {
- var r = directiveRecords[i];
- if (!r.isDefaultChangeDetection()) {
- res.push(this._names.getDetectorName(r.directiveIndex) + " = this.getDetectorFor(directives, " + i + ");");
- }
- }
- return res.join("\n");
- };
- CodegenLogicUtil.prototype.genContentLifecycleCallbacks = function (directiveRecords) {
- var res = [];
- var eq = lang_1.IS_DART ? '==' : '===';
- // NOTE(kegluneq): Order is important!
- for (var i = directiveRecords.length - 1; i >= 0; --i) {
- var dir = directiveRecords[i];
- if (dir.callAfterContentInit) {
- res.push("if(" + this._names.getStateName() + " " + eq + " " + this._changeDetectorStateName + ".NeverChecked) " + this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterContentInit();");
- }
- if (dir.callAfterContentChecked) {
- res.push(this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterContentChecked();");
- }
- }
- return res;
- };
- CodegenLogicUtil.prototype.genViewLifecycleCallbacks = function (directiveRecords) {
- var res = [];
- var eq = lang_1.IS_DART ? '==' : '===';
- // NOTE(kegluneq): Order is important!
- for (var i = directiveRecords.length - 1; i >= 0; --i) {
- var dir = directiveRecords[i];
- if (dir.callAfterViewInit) {
- res.push("if(" + this._names.getStateName() + " " + eq + " " + this._changeDetectorStateName + ".NeverChecked) " + this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterViewInit();");
- }
- if (dir.callAfterViewChecked) {
- res.push(this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterViewChecked();");
- }
- }
- return res;
- };
- return CodegenLogicUtil;
- })();
- exports.CodegenLogicUtil = CodegenLogicUtil;
- /***/ },
- /* 55 */
- /***/ function(module, exports) {
- /**
- * Converts `funcOrValue` to a string which can be used in generated code.
- */
- function codify(obj) {
- return JSON.stringify(obj);
- }
- exports.codify = codify;
- function rawString(str) {
- return "'" + str + "'";
- }
- exports.rawString = rawString;
- /**
- * Combine the strings of generated code into a single interpolated string.
- * Each element of `vals` is expected to be a string literal or a codegen'd
- * call to a method returning a string.
- */
- function combineGeneratedStrings(vals) {
- return vals.join(' + ');
- }
- exports.combineGeneratedStrings = combineGeneratedStrings;
- /***/ },
- /* 56 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- /**
- * Defines template and style encapsulation options available for Component's {@link View}.
- *
- * See {@link ViewMetadata#encapsulation}.
- */
- (function (ViewEncapsulation) {
- /**
- * Emulate `Native` scoping of styles by adding an attribute containing surrogate id to the Host
- * Element and pre-processing the style rules provided via
- * {@link ViewMetadata#styles} or {@link ViewMetadata#stylesUrls}, and adding the new Host Element
- * attribute to all selectors.
- *
- * This is the default option.
- */
- ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
- /**
- * Use the native encapsulation mechanism of the renderer.
- *
- * For the DOM this means using [Shadow DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
- * creating a ShadowRoot for Component's Host Element.
- */
- ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
- /**
- * Don't provide any template or style encapsulation.
- */
- ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
- })(exports.ViewEncapsulation || (exports.ViewEncapsulation = {}));
- var ViewEncapsulation = exports.ViewEncapsulation;
- exports.VIEW_ENCAPSULATION_VALUES = [ViewEncapsulation.Emulated, ViewEncapsulation.Native, ViewEncapsulation.None];
- /**
- * Metadata properties available for configuring Views.
- *
- * Each Angular component requires a single `@Component` and at least one `@View` annotation. The
- * `@View` annotation specifies the HTML template to use, and lists the directives that are active
- * within the template.
- *
- * When a component is instantiated, the template is loaded into the component's shadow root, and
- * the expressions and statements in the template are evaluated against the component.
- *
- * For details on the `@Component` annotation, see {@link ComponentMetadata}.
- *
- * ### Example
- *
- * ```
- * @Component({
- * selector: 'greet',
- * template: 'Hello {{name}}!',
- * directives: [GreetUser, Bold]
- * })
- * class Greet {
- * name: string;
- *
- * constructor() {
- * this.name = 'World';
- * }
- * }
- * ```
- */
- var ViewMetadata = (function () {
- function ViewMetadata(_a) {
- var _b = _a === void 0 ? {} : _a, templateUrl = _b.templateUrl, template = _b.template, directives = _b.directives, pipes = _b.pipes, encapsulation = _b.encapsulation, styles = _b.styles, styleUrls = _b.styleUrls;
- this.templateUrl = templateUrl;
- this.template = template;
- this.styleUrls = styleUrls;
- this.styles = styles;
- this.directives = directives;
- this.pipes = pipes;
- this.encapsulation = encapsulation;
- }
- ViewMetadata = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], ViewMetadata);
- return ViewMetadata;
- })();
- exports.ViewMetadata = ViewMetadata;
- /***/ },
- /* 57 */
- /***/ function(module, exports, __webpack_require__) {
- // Public API for util
- var decorators_1 = __webpack_require__(9);
- exports.Class = decorators_1.Class;
- /***/ },
- /* 58 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- exports.enableProdMode = lang_1.enableProdMode;
- /***/ },
- /* 59 */
- /***/ function(module, exports, __webpack_require__) {
- // Public API for Facade
- var lang_1 = __webpack_require__(5);
- exports.Type = lang_1.Type;
- var async_1 = __webpack_require__(60);
- exports.EventEmitter = async_1.EventEmitter;
- var exceptions_1 = __webpack_require__(14);
- exports.WrappedException = exceptions_1.WrappedException;
- var exception_handler_1 = __webpack_require__(15);
- exports.ExceptionHandler = exception_handler_1.ExceptionHandler;
- /***/ },
- /* 60 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var promise_1 = __webpack_require__(61);
- exports.PromiseWrapper = promise_1.PromiseWrapper;
- exports.Promise = promise_1.Promise;
- var Subject_1 = __webpack_require__(62);
- var fromPromise_1 = __webpack_require__(63);
- var toPromise_1 = __webpack_require__(64);
- var Observable_1 = __webpack_require__(62);
- exports.Observable = Observable_1.Observable;
- var Subject_2 = __webpack_require__(62);
- exports.Subject = Subject_2.Subject;
- var TimerWrapper = (function () {
- function TimerWrapper() {
- }
- TimerWrapper.setTimeout = function (fn, millis) {
- return lang_1.global.setTimeout(fn, millis);
- };
- TimerWrapper.clearTimeout = function (id) { lang_1.global.clearTimeout(id); };
- TimerWrapper.setInterval = function (fn, millis) {
- return lang_1.global.setInterval(fn, millis);
- };
- TimerWrapper.clearInterval = function (id) { lang_1.global.clearInterval(id); };
- return TimerWrapper;
- })();
- exports.TimerWrapper = TimerWrapper;
- var ObservableWrapper = (function () {
- function ObservableWrapper() {
- }
- // TODO(vsavkin): when we use rxnext, try inferring the generic type from the first arg
- ObservableWrapper.subscribe = function (emitter, onNext, onError, onComplete) {
- if (onComplete === void 0) { onComplete = function () { }; }
- onError = (typeof onError === "function") && onError || lang_1.noop;
- onComplete = (typeof onComplete === "function") && onComplete || lang_1.noop;
- return emitter.subscribe({ next: onNext, error: onError, complete: onComplete });
- };
- ObservableWrapper.isObservable = function (obs) { return !!obs.subscribe; };
- /**
- * Returns whether `obs` has any subscribers listening to events.
- */
- ObservableWrapper.hasSubscribers = function (obs) { return obs.observers.length > 0; };
- ObservableWrapper.dispose = function (subscription) { subscription.unsubscribe(); };
- /**
- * @deprecated - use callEmit() instead
- */
- ObservableWrapper.callNext = function (emitter, value) { emitter.next(value); };
- ObservableWrapper.callEmit = function (emitter, value) { emitter.emit(value); };
- ObservableWrapper.callError = function (emitter, error) { emitter.error(error); };
- ObservableWrapper.callComplete = function (emitter) { emitter.complete(); };
- ObservableWrapper.fromPromise = function (promise) {
- return fromPromise_1.PromiseObservable.create(promise);
- };
- ObservableWrapper.toPromise = function (obj) { return toPromise_1.toPromise.call(obj); };
- return ObservableWrapper;
- })();
- exports.ObservableWrapper = ObservableWrapper;
- /**
- * Use by directives and components to emit custom Events.
- *
- * ### Examples
- *
- * In the following example, `Zippy` alternatively emits `open` and `close` events when its
- * title gets clicked:
- *
- * ```
- * @Component({
- * selector: 'zippy',
- * template: `
- * <div class="zippy">
- * <div (click)="toggle()">Toggle</div>
- * <div [hidden]="!visible">
- * <ng-content></ng-content>
- * </div>
- * </div>`})
- * export class Zippy {
- * visible: boolean = true;
- * @Output() open: EventEmitter<any> = new EventEmitter();
- * @Output() close: EventEmitter<any> = new EventEmitter();
- *
- * toggle() {
- * this.visible = !this.visible;
- * if (this.visible) {
- * this.open.emit(null);
- * } else {
- * this.close.emit(null);
- * }
- * }
- * }
- * ```
- *
- * Use Rx.Observable but provides an adapter to make it work as specified here:
- * https://github.com/jhusain/observable-spec
- *
- * Once a reference implementation of the spec is available, switch to it.
- */
- var EventEmitter = (function (_super) {
- __extends(EventEmitter, _super);
- /**
- * Creates an instance of [EventEmitter], which depending on [isAsync],
- * delivers events synchronously or asynchronously.
- */
- function EventEmitter(isAsync) {
- if (isAsync === void 0) { isAsync = true; }
- _super.call(this);
- this._isAsync = isAsync;
- }
- EventEmitter.prototype.emit = function (value) { _super.prototype.next.call(this, value); };
- /**
- * @deprecated - use .emit(value) instead
- */
- EventEmitter.prototype.next = function (value) { _super.prototype.next.call(this, value); };
- EventEmitter.prototype.subscribe = function (generatorOrNext, error, complete) {
- var schedulerFn;
- var errorFn = function (err) { return null; };
- var completeFn = function () { return null; };
- if (generatorOrNext && typeof generatorOrNext === 'object') {
- schedulerFn = this._isAsync ? function (value) { setTimeout(function () { return generatorOrNext.next(value); }); } :
- function (value) { generatorOrNext.next(value); };
- if (generatorOrNext.error) {
- errorFn = this._isAsync ? function (err) { setTimeout(function () { return generatorOrNext.error(err); }); } :
- function (err) { generatorOrNext.error(err); };
- }
- if (generatorOrNext.complete) {
- completeFn = this._isAsync ? function () { setTimeout(function () { return generatorOrNext.complete(); }); } :
- function () { generatorOrNext.complete(); };
- }
- }
- else {
- schedulerFn = this._isAsync ? function (value) { setTimeout(function () { return generatorOrNext(value); }); } :
- function (value) { generatorOrNext(value); };
- if (error) {
- errorFn =
- this._isAsync ? function (err) { setTimeout(function () { return error(err); }); } : function (err) { error(err); };
- }
- if (complete) {
- completeFn =
- this._isAsync ? function () { setTimeout(function () { return complete(); }); } : function () { complete(); };
- }
- }
- return _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn);
- };
- return EventEmitter;
- })(Subject_1.Subject);
- exports.EventEmitter = EventEmitter;
- /***/ },
- /* 61 */
- /***/ function(module, exports) {
- // Promises are put into their own facade file so that they can be used without
- // introducing a dependency on rxjs. They are re-exported through facade/async.
- var PromiseWrapper = (function () {
- function PromiseWrapper() {
- }
- PromiseWrapper.resolve = function (obj) { return Promise.resolve(obj); };
- PromiseWrapper.reject = function (obj, _) { return Promise.reject(obj); };
- // Note: We can't rename this method into `catch`, as this is not a valid
- // method name in Dart.
- PromiseWrapper.catchError = function (promise, onError) {
- return promise.catch(onError);
- };
- PromiseWrapper.all = function (promises) {
- if (promises.length == 0)
- return Promise.resolve([]);
- return Promise.all(promises);
- };
- PromiseWrapper.then = function (promise, success, rejection) {
- return promise.then(success, rejection);
- };
- PromiseWrapper.wrap = function (computation) {
- return new Promise(function (res, rej) {
- try {
- res(computation());
- }
- catch (e) {
- rej(e);
- }
- });
- };
- PromiseWrapper.scheduleMicrotask = function (computation) {
- PromiseWrapper.then(PromiseWrapper.resolve(null), computation, function (_) { });
- };
- PromiseWrapper.isPromise = function (obj) { return obj instanceof Promise; };
- PromiseWrapper.completer = function () {
- var resolve;
- var reject;
- var p = new Promise(function (res, rej) {
- resolve = res;
- reject = rej;
- });
- return { promise: p, resolve: resolve, reject: reject };
- };
- return PromiseWrapper;
- })();
- exports.PromiseWrapper = PromiseWrapper;
- /***/ },
- /* 62 */
- /***/ function(module, exports) {
- module.exports = __WEBPACK_EXTERNAL_MODULE_62__;
- /***/ },
- /* 63 */
- /***/ function(module, exports) {
- module.exports = __WEBPACK_EXTERNAL_MODULE_63__;
- /***/ },
- /* 64 */
- /***/ function(module, exports) {
- module.exports = __WEBPACK_EXTERNAL_MODULE_64__;
- /***/ },
- /* 65 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var ng_zone_1 = __webpack_require__(66);
- var lang_1 = __webpack_require__(5);
- var di_1 = __webpack_require__(6);
- var application_tokens_1 = __webpack_require__(67);
- var async_1 = __webpack_require__(60);
- var collection_1 = __webpack_require__(12);
- var testability_1 = __webpack_require__(68);
- var dynamic_component_loader_1 = __webpack_require__(69);
- var exceptions_1 = __webpack_require__(14);
- var view_ref_1 = __webpack_require__(77);
- var console_1 = __webpack_require__(97);
- var profile_1 = __webpack_require__(45);
- var lang_2 = __webpack_require__(5);
- /**
- * Construct providers specific to an individual root component.
- */
- function _componentProviders(appComponentType) {
- return [
- di_1.provide(application_tokens_1.APP_COMPONENT, { useValue: appComponentType }),
- di_1.provide(application_tokens_1.APP_COMPONENT_REF_PROMISE, {
- useFactory: function (dynamicComponentLoader, appRef, injector) {
- // Save the ComponentRef for disposal later.
- var ref;
- // TODO(rado): investigate whether to support providers on root component.
- return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector, function () { appRef._unloadComponent(ref); })
- .then(function (componentRef) {
- ref = componentRef;
- if (lang_1.isPresent(componentRef.location.nativeElement)) {
- injector.get(testability_1.TestabilityRegistry)
- .registerApplication(componentRef.location.nativeElement, injector.get(testability_1.Testability));
- }
- return componentRef;
- });
- },
- deps: [dynamic_component_loader_1.DynamicComponentLoader, ApplicationRef, di_1.Injector]
- }),
- di_1.provide(appComponentType, {
- useFactory: function (p) { return p.then(function (ref) { return ref.instance; }); },
- deps: [application_tokens_1.APP_COMPONENT_REF_PROMISE]
- }),
- ];
- }
- /**
- * Create an Angular zone.
- */
- function createNgZone() {
- return new ng_zone_1.NgZone({ enableLongStackTrace: lang_1.assertionsEnabled() });
- }
- exports.createNgZone = createNgZone;
- var _platform;
- var _platformProviders;
- /**
- * Initialize the Angular 'platform' on the page.
- *
- * See {@link PlatformRef} for details on the Angular platform.
- *
- * It is also possible to specify providers to be made in the new platform. These providers
- * will be shared between all applications on the page. For example, an abstraction for
- * the browser cookie jar should be bound at the platform level, because there is only one
- * cookie jar regardless of how many applications on the page will be accessing it.
- *
- * The platform function can be called multiple times as long as the same list of providers
- * is passed into each call. If the platform function is called with a different set of
- * provides, Angular will throw an exception.
- */
- function platform(providers) {
- lang_2.lockMode();
- if (lang_1.isPresent(_platform)) {
- if (collection_1.ListWrapper.equals(_platformProviders, providers)) {
- return _platform;
- }
- else {
- throw new exceptions_1.BaseException("platform cannot be initialized with different sets of providers.");
- }
- }
- else {
- return _createPlatform(providers);
- }
- }
- exports.platform = platform;
- /**
- * Dispose the existing platform.
- */
- function disposePlatform() {
- if (lang_1.isPresent(_platform)) {
- _platform.dispose();
- _platform = null;
- }
- }
- exports.disposePlatform = disposePlatform;
- function _createPlatform(providers) {
- _platformProviders = providers;
- var injector = di_1.Injector.resolveAndCreate(providers);
- _platform = new PlatformRef_(injector, function () {
- _platform = null;
- _platformProviders = null;
- });
- _runPlatformInitializers(injector);
- return _platform;
- }
- function _runPlatformInitializers(injector) {
- var inits = injector.getOptional(application_tokens_1.PLATFORM_INITIALIZER);
- if (lang_1.isPresent(inits))
- inits.forEach(function (init) { return init(); });
- }
- /**
- * The Angular platform is the entry point for Angular on a web page. Each page
- * has exactly one platform, and services (such as reflection) which are common
- * to every Angular application running on the page are bound in its scope.
- *
- * A page's platform is initialized implicitly when {@link bootstrap}() is called, or
- * explicitly by calling {@link platform}().
- */
- var PlatformRef = (function () {
- function PlatformRef() {
- }
- Object.defineProperty(PlatformRef.prototype, "injector", {
- /**
- * Retrieve the platform {@link Injector}, which is the parent injector for
- * every Angular application on the page and provides singleton providers.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return PlatformRef;
- })();
- exports.PlatformRef = PlatformRef;
- var PlatformRef_ = (function (_super) {
- __extends(PlatformRef_, _super);
- function PlatformRef_(_injector, _dispose) {
- _super.call(this);
- this._injector = _injector;
- this._dispose = _dispose;
- /** @internal */
- this._applications = [];
- /** @internal */
- this._disposeListeners = [];
- }
- PlatformRef_.prototype.registerDisposeListener = function (dispose) { this._disposeListeners.push(dispose); };
- Object.defineProperty(PlatformRef_.prototype, "injector", {
- get: function () { return this._injector; },
- enumerable: true,
- configurable: true
- });
- PlatformRef_.prototype.application = function (providers) {
- var app = this._initApp(createNgZone(), providers);
- return app;
- };
- PlatformRef_.prototype.asyncApplication = function (bindingFn, additionalProviders) {
- var _this = this;
- var zone = createNgZone();
- var completer = async_1.PromiseWrapper.completer();
- zone.run(function () {
- async_1.PromiseWrapper.then(bindingFn(zone), function (providers) {
- if (lang_1.isPresent(additionalProviders)) {
- providers = collection_1.ListWrapper.concat(providers, additionalProviders);
- }
- completer.resolve(_this._initApp(zone, providers));
- });
- });
- return completer.promise;
- };
- PlatformRef_.prototype._initApp = function (zone, providers) {
- var _this = this;
- var injector;
- var app;
- zone.run(function () {
- providers = collection_1.ListWrapper.concat(providers, [
- di_1.provide(ng_zone_1.NgZone, { useValue: zone }),
- di_1.provide(ApplicationRef, { useFactory: function () { return app; }, deps: [] })
- ]);
- var exceptionHandler;
- try {
- injector = _this.injector.resolveAndCreateChild(providers);
- exceptionHandler = injector.get(exceptions_1.ExceptionHandler);
- zone.overrideOnErrorHandler(function (e, s) { return exceptionHandler.call(e, s); });
- }
- catch (e) {
- if (lang_1.isPresent(exceptionHandler)) {
- exceptionHandler.call(e, e.stack);
- }
- else {
- lang_1.print(e.toString());
- }
- }
- });
- app = new ApplicationRef_(this, zone, injector);
- this._applications.push(app);
- _runAppInitializers(injector);
- return app;
- };
- PlatformRef_.prototype.dispose = function () {
- collection_1.ListWrapper.clone(this._applications).forEach(function (app) { return app.dispose(); });
- this._disposeListeners.forEach(function (dispose) { return dispose(); });
- this._dispose();
- };
- /** @internal */
- PlatformRef_.prototype._applicationDisposed = function (app) { collection_1.ListWrapper.remove(this._applications, app); };
- return PlatformRef_;
- })(PlatformRef);
- exports.PlatformRef_ = PlatformRef_;
- function _runAppInitializers(injector) {
- var inits = injector.getOptional(application_tokens_1.APP_INITIALIZER);
- if (lang_1.isPresent(inits))
- inits.forEach(function (init) { return init(); });
- }
- /**
- * A reference to an Angular application running on a page.
- *
- * For more about Angular applications, see the documentation for {@link bootstrap}.
- */
- var ApplicationRef = (function () {
- function ApplicationRef() {
- }
- Object.defineProperty(ApplicationRef.prototype, "injector", {
- /**
- * Retrieve the application {@link Injector}.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(ApplicationRef.prototype, "zone", {
- /**
- * Retrieve the application {@link NgZone}.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(ApplicationRef.prototype, "componentTypes", {
- /**
- * Get a list of component types registered to this application.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return ApplicationRef;
- })();
- exports.ApplicationRef = ApplicationRef;
- var ApplicationRef_ = (function (_super) {
- __extends(ApplicationRef_, _super);
- function ApplicationRef_(_platform, _zone, _injector) {
- var _this = this;
- _super.call(this);
- this._platform = _platform;
- this._zone = _zone;
- this._injector = _injector;
- /** @internal */
- this._bootstrapListeners = [];
- /** @internal */
- this._disposeListeners = [];
- /** @internal */
- this._rootComponents = [];
- /** @internal */
- this._rootComponentTypes = [];
- /** @internal */
- this._changeDetectorRefs = [];
- /** @internal */
- this._runningTick = false;
- /** @internal */
- this._enforceNoNewChanges = false;
- if (lang_1.isPresent(this._zone)) {
- async_1.ObservableWrapper.subscribe(this._zone.onTurnDone, function (_) { _this._zone.run(function () { _this.tick(); }); });
- }
- this._enforceNoNewChanges = lang_1.assertionsEnabled();
- }
- ApplicationRef_.prototype.registerBootstrapListener = function (listener) {
- this._bootstrapListeners.push(listener);
- };
- ApplicationRef_.prototype.registerDisposeListener = function (dispose) { this._disposeListeners.push(dispose); };
- ApplicationRef_.prototype.registerChangeDetector = function (changeDetector) {
- this._changeDetectorRefs.push(changeDetector);
- };
- ApplicationRef_.prototype.unregisterChangeDetector = function (changeDetector) {
- collection_1.ListWrapper.remove(this._changeDetectorRefs, changeDetector);
- };
- ApplicationRef_.prototype.bootstrap = function (componentType, providers) {
- var _this = this;
- var completer = async_1.PromiseWrapper.completer();
- this._zone.run(function () {
- var componentProviders = _componentProviders(componentType);
- if (lang_1.isPresent(providers)) {
- componentProviders.push(providers);
- }
- var exceptionHandler = _this._injector.get(exceptions_1.ExceptionHandler);
- _this._rootComponentTypes.push(componentType);
- try {
- var injector = _this._injector.resolveAndCreateChild(componentProviders);
- var compRefToken = injector.get(application_tokens_1.APP_COMPONENT_REF_PROMISE);
- var tick = function (componentRef) {
- _this._loadComponent(componentRef);
- completer.resolve(componentRef);
- };
- var tickResult = async_1.PromiseWrapper.then(compRefToken, tick);
- // THIS MUST ONLY RUN IN DART.
- // This is required to report an error when no components with a matching selector found.
- // Otherwise the promise will never be completed.
- // Doing this in JS causes an extra error message to appear.
- if (lang_1.IS_DART) {
- async_1.PromiseWrapper.then(tickResult, function (_) { });
- }
- async_1.PromiseWrapper.then(tickResult, null, function (err, stackTrace) { return completer.reject(err, stackTrace); });
- }
- catch (e) {
- exceptionHandler.call(e, e.stack);
- completer.reject(e, e.stack);
- }
- });
- return completer.promise.then(function (_) {
- var c = _this._injector.get(console_1.Console);
- var modeDescription = lang_1.assertionsEnabled() ?
- "in the development mode. Call enableProdMode() to enable the production mode." :
- "in the production mode. Call enableDevMode() to enable the development mode.";
- c.log("Angular 2 is running " + modeDescription);
- return _;
- });
- };
- /** @internal */
- ApplicationRef_.prototype._loadComponent = function (ref) {
- var appChangeDetector = view_ref_1.internalView(ref.hostView).changeDetector;
- this._changeDetectorRefs.push(appChangeDetector.ref);
- this.tick();
- this._rootComponents.push(ref);
- this._bootstrapListeners.forEach(function (listener) { return listener(ref); });
- };
- /** @internal */
- ApplicationRef_.prototype._unloadComponent = function (ref) {
- if (!collection_1.ListWrapper.contains(this._rootComponents, ref)) {
- return;
- }
- this.unregisterChangeDetector(view_ref_1.internalView(ref.hostView).changeDetector.ref);
- collection_1.ListWrapper.remove(this._rootComponents, ref);
- };
- Object.defineProperty(ApplicationRef_.prototype, "injector", {
- get: function () { return this._injector; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ApplicationRef_.prototype, "zone", {
- get: function () { return this._zone; },
- enumerable: true,
- configurable: true
- });
- ApplicationRef_.prototype.tick = function () {
- if (this._runningTick) {
- throw new exceptions_1.BaseException("ApplicationRef.tick is called recursively");
- }
- var s = ApplicationRef_._tickScope();
- try {
- this._runningTick = true;
- this._changeDetectorRefs.forEach(function (detector) { return detector.detectChanges(); });
- if (this._enforceNoNewChanges) {
- this._changeDetectorRefs.forEach(function (detector) { return detector.checkNoChanges(); });
- }
- }
- finally {
- this._runningTick = false;
- profile_1.wtfLeave(s);
- }
- };
- ApplicationRef_.prototype.dispose = function () {
- // TODO(alxhub): Dispose of the NgZone.
- collection_1.ListWrapper.clone(this._rootComponents).forEach(function (ref) { return ref.dispose(); });
- this._disposeListeners.forEach(function (dispose) { return dispose(); });
- this._platform._applicationDisposed(this);
- };
- Object.defineProperty(ApplicationRef_.prototype, "componentTypes", {
- get: function () { return this._rootComponentTypes; },
- enumerable: true,
- configurable: true
- });
- /** @internal */
- ApplicationRef_._tickScope = profile_1.wtfCreateScope('ApplicationRef#tick()');
- return ApplicationRef_;
- })(ApplicationRef);
- exports.ApplicationRef_ = ApplicationRef_;
- /***/ },
- /* 66 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- var profile_1 = __webpack_require__(45);
- /**
- * Stores error information; delivered via [NgZone.onError] stream.
- */
- var NgZoneError = (function () {
- function NgZoneError(error, stackTrace) {
- this.error = error;
- this.stackTrace = stackTrace;
- }
- return NgZoneError;
- })();
- exports.NgZoneError = NgZoneError;
- /**
- * An injectable service for executing work inside or outside of the Angular zone.
- *
- * The most common use of this service is to optimize performance when starting a work consisting of
- * one or more asynchronous tasks that don't require UI updates or error handling to be handled by
- * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
- * can reenter the Angular zone via {@link #run}.
- *
- * <!-- TODO: add/fix links to:
- * - docs explaining zones and the use of zones in Angular and change-detection
- * - link to runOutsideAngular/run (throughout this file!)
- * -->
- *
- * ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview))
- * ```
- * import {Component, View, NgZone} from 'angular2/core';
- * import {NgIf} from 'angular2/common';
- *
- * @Component({
- * selector: 'ng-zone-demo'.
- * template: `
- * <h2>Demo: NgZone</h2>
- *
- * <p>Progress: {{progress}}%</p>
- * <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
- *
- * <button (click)="processWithinAngularZone()">Process within Angular zone</button>
- * <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
- * `,
- * directives: [NgIf]
- * })
- * export class NgZoneDemo {
- * progress: number = 0;
- * label: string;
- *
- * constructor(private _ngZone: NgZone) {}
- *
- * // Loop inside the Angular zone
- * // so the UI DOES refresh after each setTimeout cycle
- * processWithinAngularZone() {
- * this.label = 'inside';
- * this.progress = 0;
- * this._increaseProgress(() => console.log('Inside Done!'));
- * }
- *
- * // Loop outside of the Angular zone
- * // so the UI DOES NOT refresh after each setTimeout cycle
- * processOutsideOfAngularZone() {
- * this.label = 'outside';
- * this.progress = 0;
- * this._ngZone.runOutsideAngular(() => {
- * this._increaseProgress(() => {
- * // reenter the Angular zone and display done
- * this._ngZone.run(() => {console.log('Outside Done!') });
- * }}));
- * }
- *
- *
- * _increaseProgress(doneCallback: () => void) {
- * this.progress += 1;
- * console.log(`Current progress: ${this.progress}%`);
- *
- * if (this.progress < 100) {
- * window.setTimeout(() => this._increaseProgress(doneCallback)), 10)
- * } else {
- * doneCallback();
- * }
- * }
- * }
- * ```
- */
- var NgZone = (function () {
- /**
- * @param {bool} enableLongStackTrace whether to enable long stack trace. They should only be
- * enabled in development mode as they significantly impact perf.
- */
- function NgZone(_a) {
- var enableLongStackTrace = _a.enableLongStackTrace;
- /** @internal */
- this._runScope = profile_1.wtfCreateScope("NgZone#run()");
- /** @internal */
- this._microtaskScope = profile_1.wtfCreateScope("NgZone#microtask()");
- // Number of microtasks pending from _innerZone (& descendants)
- /** @internal */
- this._pendingMicrotasks = 0;
- // Whether some code has been executed in the _innerZone (& descendants) in the current turn
- /** @internal */
- this._hasExecutedCodeInInnerZone = false;
- // run() call depth in _mountZone. 0 at the end of a macrotask
- // zone.run(() => { // top-level call
- // zone.run(() => {}); // nested call -> in-turn
- // });
- /** @internal */
- this._nestedRun = 0;
- /** @internal */
- this._inVmTurnDone = false;
- /** @internal */
- this._pendingTimeouts = [];
- if (lang_1.global.zone) {
- this._disabled = false;
- this._mountZone = lang_1.global.zone;
- this._innerZone = this._createInnerZone(this._mountZone, enableLongStackTrace);
- }
- else {
- this._disabled = true;
- this._mountZone = null;
- }
- this._onTurnStartEvents = new async_1.EventEmitter(false);
- this._onTurnDoneEvents = new async_1.EventEmitter(false);
- this._onEventDoneEvents = new async_1.EventEmitter(false);
- this._onErrorEvents = new async_1.EventEmitter(false);
- }
- /**
- * Sets the zone hook that is called just before a browser task that is handled by Angular
- * executes.
- *
- * The hook is called once per browser task that is handled by Angular.
- *
- * Setting the hook overrides any previously set hook.
- *
- * @deprecated this API will be removed in the future. Use `onTurnStart` instead.
- */
- NgZone.prototype.overrideOnTurnStart = function (onTurnStartHook) {
- this._onTurnStart = lang_1.normalizeBlank(onTurnStartHook);
- };
- Object.defineProperty(NgZone.prototype, "onTurnStart", {
- /**
- * Notifies subscribers just before Angular event turn starts.
- *
- * Emits an event once per browser task that is handled by Angular.
- */
- get: function () { return this._onTurnStartEvents; },
- enumerable: true,
- configurable: true
- });
- /** @internal */
- NgZone.prototype._notifyOnTurnStart = function (parentRun) {
- var _this = this;
- parentRun.call(this._innerZone, function () { _this._onTurnStartEvents.emit(null); });
- };
- /**
- * Sets the zone hook that is called immediately after Angular zone is done processing the current
- * task and any microtasks scheduled from that task.
- *
- * This is where we typically do change-detection.
- *
- * The hook is called once per browser task that is handled by Angular.
- *
- * Setting the hook overrides any previously set hook.
- *
- * @deprecated this API will be removed in the future. Use `onTurnDone` instead.
- */
- NgZone.prototype.overrideOnTurnDone = function (onTurnDoneHook) {
- this._onTurnDone = lang_1.normalizeBlank(onTurnDoneHook);
- };
- Object.defineProperty(NgZone.prototype, "onTurnDone", {
- /**
- * Notifies subscribers immediately after Angular zone is done processing
- * the current turn and any microtasks scheduled from that turn.
- *
- * Used by Angular as a signal to kick off change-detection.
- */
- get: function () { return this._onTurnDoneEvents; },
- enumerable: true,
- configurable: true
- });
- /** @internal */
- NgZone.prototype._notifyOnTurnDone = function (parentRun) {
- var _this = this;
- parentRun.call(this._innerZone, function () { _this._onTurnDoneEvents.emit(null); });
- };
- /**
- * Sets the zone hook that is called immediately after the `onTurnDone` callback is called and any
- * microstasks scheduled from within that callback are drained.
- *
- * `onEventDoneFn` is executed outside Angular zone, which means that we will no longer attempt to
- * sync the UI with any model changes that occur within this callback.
- *
- * This hook is useful for validating application state (e.g. in a test).
- *
- * Setting the hook overrides any previously set hook.
- *
- * @deprecated this API will be removed in the future. Use `onEventDone` instead.
- */
- NgZone.prototype.overrideOnEventDone = function (onEventDoneFn, opt_waitForAsync) {
- var _this = this;
- if (opt_waitForAsync === void 0) { opt_waitForAsync = false; }
- var normalizedOnEventDone = lang_1.normalizeBlank(onEventDoneFn);
- if (opt_waitForAsync) {
- this._onEventDone = function () {
- if (!_this._pendingTimeouts.length) {
- normalizedOnEventDone();
- }
- };
- }
- else {
- this._onEventDone = normalizedOnEventDone;
- }
- };
- Object.defineProperty(NgZone.prototype, "onEventDone", {
- /**
- * Notifies subscribers immediately after the final `onTurnDone` callback
- * before ending VM event.
- *
- * This event is useful for validating application state (e.g. in a test).
- */
- get: function () { return this._onEventDoneEvents; },
- enumerable: true,
- configurable: true
- });
- /** @internal */
- NgZone.prototype._notifyOnEventDone = function () {
- var _this = this;
- this.runOutsideAngular(function () { _this._onEventDoneEvents.emit(null); });
- };
- Object.defineProperty(NgZone.prototype, "hasPendingMicrotasks", {
- /**
- * Whether there are any outstanding microtasks.
- */
- get: function () { return this._pendingMicrotasks > 0; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgZone.prototype, "hasPendingTimers", {
- /**
- * Whether there are any outstanding timers.
- */
- get: function () { return this._pendingTimeouts.length > 0; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgZone.prototype, "hasPendingAsyncTasks", {
- /**
- * Whether there are any outstanding asychnronous tasks of any kind that are
- * scheduled to run within Angular zone.
- *
- * Useful as a signal of UI stability. For example, when a test reaches a
- * point when [hasPendingAsyncTasks] is `false` it might be a good time to run
- * test expectations.
- */
- get: function () { return this.hasPendingMicrotasks || this.hasPendingTimers; },
- enumerable: true,
- configurable: true
- });
- /**
- * Sets the zone hook that is called when an error is thrown in the Angular zone.
- *
- * Setting the hook overrides any previously set hook.
- *
- * @deprecated this API will be removed in the future. Use `onError` instead.
- */
- NgZone.prototype.overrideOnErrorHandler = function (errorHandler) {
- this._onErrorHandler = lang_1.normalizeBlank(errorHandler);
- };
- Object.defineProperty(NgZone.prototype, "onError", {
- get: function () { return this._onErrorEvents; },
- enumerable: true,
- configurable: true
- });
- /**
- * Executes the `fn` function synchronously within the Angular zone and returns value returned by
- * the function.
- *
- * Running functions via `run` allows you to reenter Angular zone from a task that was executed
- * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
- *
- * Any future tasks or microtasks scheduled from within this function will continue executing from
- * within the Angular zone.
- */
- NgZone.prototype.run = function (fn) {
- if (this._disabled) {
- return fn();
- }
- else {
- var s = this._runScope();
- try {
- return this._innerZone.run(fn);
- }
- finally {
- profile_1.wtfLeave(s);
- }
- }
- };
- /**
- * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
- * the function.
- *
- * Running functions via `runOutsideAngular` allows you to escape Angular's zone and do work that
- * doesn't trigger Angular change-detection or is subject to Angular's error handling.
- *
- * Any future tasks or microtasks scheduled from within this function will continue executing from
- * outside of the Angular zone.
- *
- * Use {@link #run} to reenter the Angular zone and do work that updates the application model.
- */
- NgZone.prototype.runOutsideAngular = function (fn) {
- if (this._disabled) {
- return fn();
- }
- else {
- return this._mountZone.run(fn);
- }
- };
- /** @internal */
- NgZone.prototype._createInnerZone = function (zone, enableLongStackTrace) {
- var microtaskScope = this._microtaskScope;
- var ngZone = this;
- var errorHandling;
- if (enableLongStackTrace) {
- errorHandling = collection_1.StringMapWrapper.merge(Zone.longStackTraceZone, { onError: function (e) { ngZone._notifyOnError(this, e); } });
- }
- else {
- errorHandling = { onError: function (e) { ngZone._notifyOnError(this, e); } };
- }
- return zone.fork(errorHandling)
- .fork({
- '$run': function (parentRun) {
- return function () {
- try {
- ngZone._nestedRun++;
- if (!ngZone._hasExecutedCodeInInnerZone) {
- ngZone._hasExecutedCodeInInnerZone = true;
- ngZone._notifyOnTurnStart(parentRun);
- if (ngZone._onTurnStart) {
- parentRun.call(ngZone._innerZone, ngZone._onTurnStart);
- }
- }
- return parentRun.apply(this, arguments);
- }
- finally {
- ngZone._nestedRun--;
- // If there are no more pending microtasks, we are at the end of a VM turn (or in
- // onTurnStart)
- // _nestedRun will be 0 at the end of a macrotasks (it could be > 0 when there are
- // nested calls
- // to run()).
- if (ngZone._pendingMicrotasks == 0 && ngZone._nestedRun == 0 &&
- !this._inVmTurnDone) {
- if (ngZone._hasExecutedCodeInInnerZone) {
- try {
- this._inVmTurnDone = true;
- ngZone._notifyOnTurnDone(parentRun);
- if (ngZone._onTurnDone) {
- parentRun.call(ngZone._innerZone, ngZone._onTurnDone);
- }
- }
- finally {
- this._inVmTurnDone = false;
- ngZone._hasExecutedCodeInInnerZone = false;
- }
- }
- if (ngZone._pendingMicrotasks === 0) {
- ngZone._notifyOnEventDone();
- if (lang_1.isPresent(ngZone._onEventDone)) {
- ngZone.runOutsideAngular(ngZone._onEventDone);
- }
- }
- }
- }
- };
- },
- '$scheduleMicrotask': function (parentScheduleMicrotask) {
- return function (fn) {
- ngZone._pendingMicrotasks++;
- var microtask = function () {
- var s = microtaskScope();
- try {
- fn();
- }
- finally {
- ngZone._pendingMicrotasks--;
- profile_1.wtfLeave(s);
- }
- };
- parentScheduleMicrotask.call(this, microtask);
- };
- },
- '$setTimeout': function (parentSetTimeout) {
- return function (fn, delay) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- var id;
- var cb = function () {
- fn();
- collection_1.ListWrapper.remove(ngZone._pendingTimeouts, id);
- };
- id = parentSetTimeout(cb, delay, args);
- ngZone._pendingTimeouts.push(id);
- return id;
- };
- },
- '$clearTimeout': function (parentClearTimeout) {
- return function (id) {
- parentClearTimeout(id);
- collection_1.ListWrapper.remove(ngZone._pendingTimeouts, id);
- };
- },
- _innerZone: true
- });
- };
- /** @internal */
- NgZone.prototype._notifyOnError = function (zone, e) {
- if (lang_1.isPresent(this._onErrorHandler) || async_1.ObservableWrapper.hasSubscribers(this._onErrorEvents)) {
- var trace = [lang_1.normalizeBlank(e.stack)];
- while (zone && zone.constructedAtException) {
- trace.push(zone.constructedAtException.get());
- zone = zone.parent;
- }
- if (async_1.ObservableWrapper.hasSubscribers(this._onErrorEvents)) {
- async_1.ObservableWrapper.callEmit(this._onErrorEvents, new NgZoneError(e, trace));
- }
- if (lang_1.isPresent(this._onErrorHandler)) {
- this._onErrorHandler(e, trace);
- }
- }
- else {
- console.log('## _notifyOnError ##');
- console.log(e.stack);
- throw e;
- }
- };
- return NgZone;
- })();
- exports.NgZone = NgZone;
- /***/ },
- /* 67 */
- /***/ function(module, exports, __webpack_require__) {
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- /**
- * @internal
- */
- exports.APP_COMPONENT_REF_PROMISE = lang_1.CONST_EXPR(new di_1.OpaqueToken('Promise<ComponentRef>'));
- /**
- * An {@link angular2/di/OpaqueToken} representing the application root type in the {@link
- * Injector}.
- *
- * ```
- * @Component(...)
- * class MyApp {
- * ...
- * }
- *
- * bootstrap(MyApp).then((appRef:ApplicationRef) {
- * expect(appRef.injector.get(appComponentTypeToken)).toEqual(MyApp);
- * });
- *
- * ```
- */
- exports.APP_COMPONENT = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppComponent'));
- /**
- * A DI Token representing a unique string id assigned to the application by Angular and used
- * primarily for prefixing application attributes and CSS styles when
- * {@link ViewEncapsulation#Emulated} is being used.
- *
- * If you need to avoid randomly generated value to be used as an application id, you can provide
- * a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector}
- * using this token.
- */
- exports.APP_ID = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppId'));
- function _appIdRandomProviderFactory() {
- return "" + _randomChar() + _randomChar() + _randomChar();
- }
- /**
- * Providers that will generate a random APP_ID_TOKEN.
- */
- exports.APP_ID_RANDOM_PROVIDER = lang_1.CONST_EXPR(new di_1.Provider(exports.APP_ID, { useFactory: _appIdRandomProviderFactory, deps: [] }));
- function _randomChar() {
- return lang_1.StringWrapper.fromCharCode(97 + lang_1.Math.floor(lang_1.Math.random() * 25));
- }
- /**
- * A function that will be executed when a platform is initialized.
- */
- exports.PLATFORM_INITIALIZER = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Initializer"));
- /**
- * A function that will be executed when an application is initialized.
- */
- exports.APP_INITIALIZER = lang_1.CONST_EXPR(new di_1.OpaqueToken("Application Initializer"));
- /**
- * A token which indicates the root directory of the application
- */
- exports.PACKAGE_ROOT_URL = lang_1.CONST_EXPR(new di_1.OpaqueToken("Application Packages Root URL"));
- /***/ },
- /* 68 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var ng_zone_1 = __webpack_require__(66);
- var async_1 = __webpack_require__(60);
- /**
- * The Testability service provides testing hooks that can be accessed from
- * the browser and by services such as Protractor. Each bootstrapped Angular
- * application on the page will have an instance of Testability.
- */
- var Testability = (function () {
- function Testability(_ngZone) {
- /** @internal */
- this._pendingCount = 0;
- /** @internal */
- this._callbacks = [];
- /** @internal */
- this._isAngularEventPending = false;
- this._watchAngularEvents(_ngZone);
- }
- /** @internal */
- Testability.prototype._watchAngularEvents = function (_ngZone) {
- var _this = this;
- async_1.ObservableWrapper.subscribe(_ngZone.onTurnStart, function (_) { _this._isAngularEventPending = true; });
- _ngZone.runOutsideAngular(function () {
- async_1.ObservableWrapper.subscribe(_ngZone.onEventDone, function (_) {
- if (!_ngZone.hasPendingTimers) {
- _this._isAngularEventPending = false;
- _this._runCallbacksIfReady();
- }
- });
- });
- };
- Testability.prototype.increasePendingRequestCount = function () {
- this._pendingCount += 1;
- return this._pendingCount;
- };
- Testability.prototype.decreasePendingRequestCount = function () {
- this._pendingCount -= 1;
- if (this._pendingCount < 0) {
- throw new exceptions_1.BaseException('pending async requests below zero');
- }
- this._runCallbacksIfReady();
- return this._pendingCount;
- };
- Testability.prototype.isStable = function () { return this._pendingCount == 0 && !this._isAngularEventPending; };
- /** @internal */
- Testability.prototype._runCallbacksIfReady = function () {
- var _this = this;
- if (!this.isStable()) {
- return; // Not ready
- }
- // Schedules the call backs in a new frame so that it is always async.
- async_1.PromiseWrapper.resolve(null).then(function (_) {
- while (_this._callbacks.length !== 0) {
- (_this._callbacks.pop())();
- }
- });
- };
- Testability.prototype.whenStable = function (callback) {
- this._callbacks.push(callback);
- this._runCallbacksIfReady();
- };
- Testability.prototype.getPendingRequestCount = function () { return this._pendingCount; };
- // This only accounts for ngZone, and not pending counts. Use `whenStable` to
- // check for stability.
- Testability.prototype.isAngularEventPending = function () { return this._isAngularEventPending; };
- Testability.prototype.findBindings = function (using, provider, exactMatch) {
- // TODO(juliemr): implement.
- return [];
- };
- Testability.prototype.findProviders = function (using, provider, exactMatch) {
- // TODO(juliemr): implement.
- return [];
- };
- Testability = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [ng_zone_1.NgZone])
- ], Testability);
- return Testability;
- })();
- exports.Testability = Testability;
- /**
- * A global registry of {@link Testability} instances for specific elements.
- */
- var TestabilityRegistry = (function () {
- function TestabilityRegistry() {
- /** @internal */
- this._applications = new collection_1.Map();
- _testabilityGetter.addToWindow(this);
- }
- TestabilityRegistry.prototype.registerApplication = function (token, testability) {
- this._applications.set(token, testability);
- };
- TestabilityRegistry.prototype.getTestability = function (elem) { return this._applications.get(elem); };
- TestabilityRegistry.prototype.getAllTestabilities = function () { return collection_1.MapWrapper.values(this._applications); };
- TestabilityRegistry.prototype.findTestabilityInTree = function (elem, findInAncestors) {
- if (findInAncestors === void 0) { findInAncestors = true; }
- return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors);
- };
- TestabilityRegistry = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], TestabilityRegistry);
- return TestabilityRegistry;
- })();
- exports.TestabilityRegistry = TestabilityRegistry;
- var _NoopGetTestability = (function () {
- function _NoopGetTestability() {
- }
- _NoopGetTestability.prototype.addToWindow = function (registry) { };
- _NoopGetTestability.prototype.findTestabilityInTree = function (registry, elem, findInAncestors) {
- return null;
- };
- _NoopGetTestability = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], _NoopGetTestability);
- return _NoopGetTestability;
- })();
- /**
- * Set the {@link GetTestability} implementation used by the Angular testing framework.
- */
- function setTestabilityGetter(getter) {
- _testabilityGetter = getter;
- }
- exports.setTestabilityGetter = setTestabilityGetter;
- var _testabilityGetter = lang_1.CONST_EXPR(new _NoopGetTestability());
- /***/ },
- /* 69 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var compiler_1 = __webpack_require__(70);
- var lang_1 = __webpack_require__(5);
- var view_manager_1 = __webpack_require__(81);
- /**
- * Represents an instance of a Component created via {@link DynamicComponentLoader}.
- *
- * `ComponentRef` provides access to the Component Instance as well other objects related to this
- * Component Instance and allows you to destroy the Component Instance via the {@link #dispose}
- * method.
- */
- var ComponentRef = (function () {
- function ComponentRef() {
- }
- Object.defineProperty(ComponentRef.prototype, "hostView", {
- /**
- * The {@link ViewRef} of the Host View of this Component instance.
- */
- get: function () { return this.location.parentView; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ComponentRef.prototype, "hostComponent", {
- /**
- * @internal
- *
- * The instance of the component.
- *
- * TODO(i): this api should be removed
- */
- get: function () { return this.instance; },
- enumerable: true,
- configurable: true
- });
- return ComponentRef;
- })();
- exports.ComponentRef = ComponentRef;
- var ComponentRef_ = (function (_super) {
- __extends(ComponentRef_, _super);
- /**
- * TODO(i): refactor into public/private fields
- */
- function ComponentRef_(location, instance, componentType, injector, _dispose) {
- _super.call(this);
- this._dispose = _dispose;
- this.location = location;
- this.instance = instance;
- this.componentType = componentType;
- this.injector = injector;
- }
- Object.defineProperty(ComponentRef_.prototype, "hostComponentType", {
- /**
- * @internal
- *
- * Returns the type of this Component instance.
- *
- * TODO(i): this api should be removed
- */
- get: function () { return this.componentType; },
- enumerable: true,
- configurable: true
- });
- ComponentRef_.prototype.dispose = function () { this._dispose(); };
- return ComponentRef_;
- })(ComponentRef);
- exports.ComponentRef_ = ComponentRef_;
- /**
- * Service for instantiating a Component and attaching it to a View at a specified location.
- */
- var DynamicComponentLoader = (function () {
- function DynamicComponentLoader() {
- }
- return DynamicComponentLoader;
- })();
- exports.DynamicComponentLoader = DynamicComponentLoader;
- var DynamicComponentLoader_ = (function (_super) {
- __extends(DynamicComponentLoader_, _super);
- function DynamicComponentLoader_(_compiler, _viewManager) {
- _super.call(this);
- this._compiler = _compiler;
- this._viewManager = _viewManager;
- }
- DynamicComponentLoader_.prototype.loadAsRoot = function (type, overrideSelector, injector, onDispose) {
- var _this = this;
- return this._compiler.compileInHost(type).then(function (hostProtoViewRef) {
- var hostViewRef = _this._viewManager.createRootHostView(hostProtoViewRef, overrideSelector, injector);
- var newLocation = _this._viewManager.getHostElement(hostViewRef);
- var component = _this._viewManager.getComponent(newLocation);
- var dispose = function () {
- if (lang_1.isPresent(onDispose)) {
- onDispose();
- }
- _this._viewManager.destroyRootHostView(hostViewRef);
- };
- return new ComponentRef_(newLocation, component, type, injector, dispose);
- });
- };
- DynamicComponentLoader_.prototype.loadIntoLocation = function (type, hostLocation, anchorName, providers) {
- if (providers === void 0) { providers = null; }
- return this.loadNextToLocation(type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), providers);
- };
- DynamicComponentLoader_.prototype.loadNextToLocation = function (type, location, providers) {
- var _this = this;
- if (providers === void 0) { providers = null; }
- return this._compiler.compileInHost(type).then(function (hostProtoViewRef) {
- var viewContainer = _this._viewManager.getViewContainer(location);
- var hostViewRef = viewContainer.createHostView(hostProtoViewRef, viewContainer.length, providers);
- var newLocation = _this._viewManager.getHostElement(hostViewRef);
- var component = _this._viewManager.getComponent(newLocation);
- var dispose = function () {
- var index = viewContainer.indexOf(hostViewRef);
- if (index !== -1) {
- viewContainer.remove(index);
- }
- };
- return new ComponentRef_(newLocation, component, type, null, dispose);
- });
- };
- DynamicComponentLoader_ = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [compiler_1.Compiler, view_manager_1.AppViewManager])
- ], DynamicComponentLoader_);
- return DynamicComponentLoader_;
- })(DynamicComponentLoader);
- exports.DynamicComponentLoader_ = DynamicComponentLoader_;
- /***/ },
- /* 70 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var proto_view_factory_1 = __webpack_require__(71);
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var async_1 = __webpack_require__(60);
- var reflection_1 = __webpack_require__(16);
- var template_commands_1 = __webpack_require__(96);
- /**
- * Low-level service for compiling {@link Component}s into {@link ProtoViewRef ProtoViews}s, which
- * can later be used to create and render a Component instance.
- *
- * Most applications should instead use higher-level {@link DynamicComponentLoader} service, which
- * both compiles and instantiates a Component.
- */
- var Compiler = (function () {
- function Compiler() {
- }
- return Compiler;
- })();
- exports.Compiler = Compiler;
- function _isCompiledHostTemplate(type) {
- return type instanceof template_commands_1.CompiledHostTemplate;
- }
- var Compiler_ = (function (_super) {
- __extends(Compiler_, _super);
- function Compiler_(_protoViewFactory) {
- _super.call(this);
- this._protoViewFactory = _protoViewFactory;
- }
- Compiler_.prototype.compileInHost = function (componentType) {
- var metadatas = reflection_1.reflector.annotations(componentType);
- var compiledHostTemplate = metadatas.find(_isCompiledHostTemplate);
- if (lang_1.isBlank(compiledHostTemplate)) {
- throw new exceptions_1.BaseException("No precompiled template for component " + lang_1.stringify(componentType) + " found");
- }
- return async_1.PromiseWrapper.resolve(this._createProtoView(compiledHostTemplate));
- };
- Compiler_.prototype._createProtoView = function (compiledHostTemplate) {
- return this._protoViewFactory.createHost(compiledHostTemplate).ref;
- };
- Compiler_.prototype.clearCache = function () { this._protoViewFactory.clearCache(); };
- Compiler_ = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [proto_view_factory_1.ProtoViewFactory])
- ], Compiler_);
- return Compiler_;
- })(Compiler);
- exports.Compiler_ = Compiler_;
- function internalCreateProtoView(compiler, compiledHostTemplate) {
- return compiler._createProtoView(compiledHostTemplate);
- }
- exports.internalCreateProtoView = internalCreateProtoView;
- /***/ },
- /* 71 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var lang_1 = __webpack_require__(5);
- var api_1 = __webpack_require__(72);
- var di_1 = __webpack_require__(6);
- var pipe_provider_1 = __webpack_require__(73);
- var pipes_1 = __webpack_require__(74);
- var view_1 = __webpack_require__(76);
- var element_binder_1 = __webpack_require__(79);
- var element_injector_1 = __webpack_require__(80);
- var directive_resolver_1 = __webpack_require__(92);
- var view_resolver_1 = __webpack_require__(93);
- var pipe_resolver_1 = __webpack_require__(94);
- var view_2 = __webpack_require__(56);
- var platform_directives_and_pipes_1 = __webpack_require__(95);
- var template_commands_1 = __webpack_require__(96);
- var api_2 = __webpack_require__(72);
- var application_tokens_1 = __webpack_require__(67);
- var ProtoViewFactory = (function () {
- function ProtoViewFactory(_renderer, _platformPipes, _directiveResolver, _viewResolver, _pipeResolver, _appId) {
- this._renderer = _renderer;
- this._platformPipes = _platformPipes;
- this._directiveResolver = _directiveResolver;
- this._viewResolver = _viewResolver;
- this._pipeResolver = _pipeResolver;
- this._appId = _appId;
- this._cache = new Map();
- this._nextTemplateId = 0;
- }
- ProtoViewFactory.prototype.clearCache = function () { this._cache.clear(); };
- ProtoViewFactory.prototype.createHost = function (compiledHostTemplate) {
- var compiledTemplate = compiledHostTemplate.template;
- var result = this._cache.get(compiledTemplate.id);
- if (lang_1.isBlank(result)) {
- var emptyMap = {};
- var shortId = this._appId + "-" + this._nextTemplateId++;
- this._renderer.registerComponentTemplate(new api_1.RenderComponentTemplate(compiledTemplate.id, shortId, view_2.ViewEncapsulation.None, compiledTemplate.commands, []));
- result =
- new view_1.AppProtoView(compiledTemplate.id, compiledTemplate.commands, view_1.ViewType.HOST, true, compiledTemplate.changeDetectorFactory, null, new pipes_1.ProtoPipes(emptyMap));
- this._cache.set(compiledTemplate.id, result);
- }
- return result;
- };
- ProtoViewFactory.prototype._createComponent = function (cmd) {
- var _this = this;
- var nestedProtoView = this._cache.get(cmd.templateId);
- if (lang_1.isBlank(nestedProtoView)) {
- var component = cmd.directives[0];
- var view = this._viewResolver.resolve(component);
- var compiledTemplate = cmd.templateGetter();
- var styles = _flattenStyleArr(compiledTemplate.styles, []);
- var shortId = this._appId + "-" + this._nextTemplateId++;
- this._renderer.registerComponentTemplate(new api_1.RenderComponentTemplate(compiledTemplate.id, shortId, cmd.encapsulation, compiledTemplate.commands, styles));
- var boundPipes = this._flattenPipes(view).map(function (pipe) { return _this._bindPipe(pipe); });
- nestedProtoView = new view_1.AppProtoView(compiledTemplate.id, compiledTemplate.commands, view_1.ViewType.COMPONENT, true, compiledTemplate.changeDetectorFactory, null, pipes_1.ProtoPipes.fromProviders(boundPipes));
- // Note: The cache is updated before recursing
- // to be able to resolve cycles
- this._cache.set(compiledTemplate.id, nestedProtoView);
- this._initializeProtoView(nestedProtoView, null);
- }
- return nestedProtoView;
- };
- ProtoViewFactory.prototype._createEmbeddedTemplate = function (cmd, parent) {
- var nestedProtoView = new view_1.AppProtoView(parent.templateId, cmd.children, view_1.ViewType.EMBEDDED, cmd.isMerged, cmd.changeDetectorFactory, arrayToMap(cmd.variableNameAndValues, true), new pipes_1.ProtoPipes(parent.pipes.config));
- if (cmd.isMerged) {
- this.initializeProtoViewIfNeeded(nestedProtoView);
- }
- return nestedProtoView;
- };
- ProtoViewFactory.prototype.initializeProtoViewIfNeeded = function (protoView) {
- if (!protoView.isInitialized()) {
- var render = this._renderer.createProtoView(protoView.templateId, protoView.templateCmds);
- this._initializeProtoView(protoView, render);
- }
- };
- ProtoViewFactory.prototype._initializeProtoView = function (protoView, render) {
- var initializer = new _ProtoViewInitializer(protoView, this._directiveResolver, this);
- template_commands_1.visitAllCommands(initializer, protoView.templateCmds);
- var mergeInfo = new view_1.AppProtoViewMergeInfo(initializer.mergeEmbeddedViewCount, initializer.mergeElementCount, initializer.mergeViewCount);
- protoView.init(render, initializer.elementBinders, initializer.boundTextCount, mergeInfo, initializer.variableLocations);
- };
- ProtoViewFactory.prototype._bindPipe = function (typeOrProvider) {
- var meta = this._pipeResolver.resolve(typeOrProvider);
- return pipe_provider_1.PipeProvider.createFromType(typeOrProvider, meta);
- };
- ProtoViewFactory.prototype._flattenPipes = function (view) {
- var pipes = [];
- if (lang_1.isPresent(this._platformPipes)) {
- _flattenArray(this._platformPipes, pipes);
- }
- if (lang_1.isPresent(view.pipes)) {
- _flattenArray(view.pipes, pipes);
- }
- return pipes;
- };
- ProtoViewFactory = __decorate([
- di_1.Injectable(),
- __param(1, di_1.Optional()),
- __param(1, di_1.Inject(platform_directives_and_pipes_1.PLATFORM_PIPES)),
- __param(5, di_1.Inject(application_tokens_1.APP_ID)),
- __metadata('design:paramtypes', [api_2.Renderer, Array, directive_resolver_1.DirectiveResolver, view_resolver_1.ViewResolver, pipe_resolver_1.PipeResolver, String])
- ], ProtoViewFactory);
- return ProtoViewFactory;
- })();
- exports.ProtoViewFactory = ProtoViewFactory;
- function createComponent(protoViewFactory, cmd) {
- return protoViewFactory._createComponent(cmd);
- }
- function createEmbeddedTemplate(protoViewFactory, cmd, parent) {
- return protoViewFactory._createEmbeddedTemplate(cmd, parent);
- }
- var _ProtoViewInitializer = (function () {
- function _ProtoViewInitializer(_protoView, _directiveResolver, _protoViewFactory) {
- this._protoView = _protoView;
- this._directiveResolver = _directiveResolver;
- this._protoViewFactory = _protoViewFactory;
- this.variableLocations = new Map();
- this.boundTextCount = 0;
- this.boundElementIndex = 0;
- this.elementBinderStack = [];
- this.distanceToParentElementBinder = 0;
- this.distanceToParentProtoElementInjector = 0;
- this.elementBinders = [];
- this.mergeEmbeddedViewCount = 0;
- this.mergeElementCount = 0;
- this.mergeViewCount = 1;
- }
- _ProtoViewInitializer.prototype.visitText = function (cmd, context) {
- if (cmd.isBound) {
- this.boundTextCount++;
- }
- return null;
- };
- _ProtoViewInitializer.prototype.visitNgContent = function (cmd, context) { return null; };
- _ProtoViewInitializer.prototype.visitBeginElement = function (cmd, context) {
- if (cmd.isBound) {
- this._visitBeginBoundElement(cmd, null);
- }
- else {
- this._visitBeginElement(cmd, null, null);
- }
- return null;
- };
- _ProtoViewInitializer.prototype.visitEndElement = function (context) { return this._visitEndElement(); };
- _ProtoViewInitializer.prototype.visitBeginComponent = function (cmd, context) {
- var nestedProtoView = createComponent(this._protoViewFactory, cmd);
- return this._visitBeginBoundElement(cmd, nestedProtoView);
- };
- _ProtoViewInitializer.prototype.visitEndComponent = function (context) { return this._visitEndElement(); };
- _ProtoViewInitializer.prototype.visitEmbeddedTemplate = function (cmd, context) {
- var nestedProtoView = createEmbeddedTemplate(this._protoViewFactory, cmd, this._protoView);
- if (cmd.isMerged) {
- this.mergeEmbeddedViewCount++;
- }
- this._visitBeginBoundElement(cmd, nestedProtoView);
- return this._visitEndElement();
- };
- _ProtoViewInitializer.prototype._visitBeginBoundElement = function (cmd, nestedProtoView) {
- if (lang_1.isPresent(nestedProtoView) && nestedProtoView.isMergable) {
- this.mergeElementCount += nestedProtoView.mergeInfo.elementCount;
- this.mergeViewCount += nestedProtoView.mergeInfo.viewCount;
- this.mergeEmbeddedViewCount += nestedProtoView.mergeInfo.embeddedViewCount;
- }
- var elementBinder = _createElementBinder(this._directiveResolver, nestedProtoView, this.elementBinderStack, this.boundElementIndex, this.distanceToParentElementBinder, this.distanceToParentProtoElementInjector, cmd);
- this.elementBinders.push(elementBinder);
- var protoElementInjector = elementBinder.protoElementInjector;
- for (var i = 0; i < cmd.variableNameAndValues.length; i += 2) {
- this.variableLocations.set(cmd.variableNameAndValues[i], this.boundElementIndex);
- }
- this.boundElementIndex++;
- this.mergeElementCount++;
- return this._visitBeginElement(cmd, elementBinder, protoElementInjector);
- };
- _ProtoViewInitializer.prototype._visitBeginElement = function (cmd, elementBinder, protoElementInjector) {
- this.distanceToParentElementBinder =
- lang_1.isPresent(elementBinder) ? 1 : this.distanceToParentElementBinder + 1;
- this.distanceToParentProtoElementInjector =
- lang_1.isPresent(protoElementInjector) ? 1 : this.distanceToParentProtoElementInjector + 1;
- this.elementBinderStack.push(elementBinder);
- return null;
- };
- _ProtoViewInitializer.prototype._visitEndElement = function () {
- var parentElementBinder = this.elementBinderStack.pop();
- var parentProtoElementInjector = lang_1.isPresent(parentElementBinder) ? parentElementBinder.protoElementInjector : null;
- this.distanceToParentElementBinder = lang_1.isPresent(parentElementBinder) ?
- parentElementBinder.distanceToParent :
- this.distanceToParentElementBinder - 1;
- this.distanceToParentProtoElementInjector = lang_1.isPresent(parentProtoElementInjector) ?
- parentProtoElementInjector.distanceToParent :
- this.distanceToParentProtoElementInjector - 1;
- return null;
- };
- return _ProtoViewInitializer;
- })();
- function _createElementBinder(directiveResolver, nestedProtoView, elementBinderStack, boundElementIndex, distanceToParentBinder, distanceToParentPei, beginElementCmd) {
- var parentElementBinder = null;
- var parentProtoElementInjector = null;
- if (distanceToParentBinder > 0) {
- parentElementBinder = elementBinderStack[elementBinderStack.length - distanceToParentBinder];
- }
- if (lang_1.isBlank(parentElementBinder)) {
- distanceToParentBinder = -1;
- }
- if (distanceToParentPei > 0) {
- var peiBinder = elementBinderStack[elementBinderStack.length - distanceToParentPei];
- if (lang_1.isPresent(peiBinder)) {
- parentProtoElementInjector = peiBinder.protoElementInjector;
- }
- }
- if (lang_1.isBlank(parentProtoElementInjector)) {
- distanceToParentPei = -1;
- }
- var componentDirectiveProvider = null;
- var isEmbeddedTemplate = false;
- var directiveProviders = beginElementCmd.directives.map(function (type) { return provideDirective(directiveResolver, type); });
- if (beginElementCmd instanceof template_commands_1.BeginComponentCmd) {
- componentDirectiveProvider = directiveProviders[0];
- }
- else if (beginElementCmd instanceof template_commands_1.EmbeddedTemplateCmd) {
- isEmbeddedTemplate = true;
- }
- var protoElementInjector = null;
- // Create a protoElementInjector for any element that either has bindings *or* has one
- // or more var- defined *or* for <template> elements:
- // - Elements with a var- defined need a their own element injector
- // so that, when hydrating, $implicit can be set to the element.
- // - <template> elements need their own ElementInjector so that we can query their TemplateRef
- var hasVariables = beginElementCmd.variableNameAndValues.length > 0;
- if (directiveProviders.length > 0 || hasVariables || isEmbeddedTemplate) {
- var directiveVariableBindings = new Map();
- if (!isEmbeddedTemplate) {
- directiveVariableBindings = createDirectiveVariableBindings(beginElementCmd.variableNameAndValues, directiveProviders);
- }
- protoElementInjector = element_injector_1.ProtoElementInjector.create(parentProtoElementInjector, boundElementIndex, directiveProviders, lang_1.isPresent(componentDirectiveProvider), distanceToParentPei, directiveVariableBindings);
- protoElementInjector.attributes = arrayToMap(beginElementCmd.attrNameAndValues, false);
- }
- return new element_binder_1.ElementBinder(boundElementIndex, parentElementBinder, distanceToParentBinder, protoElementInjector, componentDirectiveProvider, nestedProtoView);
- }
- function provideDirective(directiveResolver, type) {
- var annotation = directiveResolver.resolve(type);
- return element_injector_1.DirectiveProvider.createFromType(type, annotation);
- }
- function createDirectiveVariableBindings(variableNameAndValues, directiveProviders) {
- var directiveVariableBindings = new Map();
- for (var i = 0; i < variableNameAndValues.length; i += 2) {
- var templateName = variableNameAndValues[i];
- var dirIndex = variableNameAndValues[i + 1];
- if (lang_1.isNumber(dirIndex)) {
- directiveVariableBindings.set(templateName, dirIndex);
- }
- else {
- // a variable without a directive index -> reference the element
- directiveVariableBindings.set(templateName, null);
- }
- }
- return directiveVariableBindings;
- }
- exports.createDirectiveVariableBindings = createDirectiveVariableBindings;
- function arrayToMap(arr, inverse) {
- var result = new Map();
- for (var i = 0; i < arr.length; i += 2) {
- if (inverse) {
- result.set(arr[i + 1], arr[i]);
- }
- else {
- result.set(arr[i], arr[i + 1]);
- }
- }
- return result;
- }
- function _flattenArray(tree, out) {
- for (var i = 0; i < tree.length; i++) {
- var item = di_1.resolveForwardRef(tree[i]);
- if (lang_1.isArray(item)) {
- _flattenArray(item, out);
- }
- else {
- out.push(item);
- }
- }
- }
- function _flattenStyleArr(arr, out) {
- for (var i = 0; i < arr.length; i++) {
- var entry = arr[i];
- if (lang_1.isArray(entry)) {
- _flattenStyleArr(entry, out);
- }
- else {
- out.push(entry);
- }
- }
- return out;
- }
- /***/ },
- /* 72 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var exceptions_1 = __webpack_require__(14);
- /**
- * Represents an Angular ProtoView in the Rendering Context.
- *
- * When you implement a custom {@link Renderer}, `RenderProtoViewRef` specifies what Render View
- * your renderer should create.
- *
- * `RenderProtoViewRef` is a counterpart to {@link ProtoViewRef} available in the Application
- * Context. But unlike `ProtoViewRef`, `RenderProtoViewRef` contains all static nested Proto Views
- * that are recursively merged into a single Render Proto View.
- *
- * <!-- TODO: this is created by Renderer#createProtoView in the new compiler -->
- */
- var RenderProtoViewRef = (function () {
- function RenderProtoViewRef() {
- }
- return RenderProtoViewRef;
- })();
- exports.RenderProtoViewRef = RenderProtoViewRef;
- /**
- * Represents a list of sibling Nodes that can be moved by the {@link Renderer} independently of
- * other Render Fragments.
- *
- * Any {@link RenderViewRef} has one Render Fragment.
- *
- * Additionally any View with an Embedded View that contains a {@link NgContentAst View Projection}
- * results in additional Render Fragment.
- */
- /*
- <div>foo</div>
- {{bar}}
- <div>foo</div> -> view 1 / fragment 1
- <ul>
- <template ngFor>
- <li>{{fg}}</li> -> view 2 / fragment 1
- </template>
- </ul>
- {{bar}}
- <div>foo</div> -> view 1 / fragment 1
- <ul>
- <template ngIf>
- <li><ng-content></></li> -> view 1 / fragment 2
- </template>
- <template ngFor>
- <li><ng-content></></li> ->
- <li></li> -> view 1 / fragment 2 + view 2 / fragment 1..n-1
- </template>
- </ul>
- {{bar}}
- */
- // TODO(i): refactor into an interface
- var RenderFragmentRef = (function () {
- function RenderFragmentRef() {
- }
- return RenderFragmentRef;
- })();
- exports.RenderFragmentRef = RenderFragmentRef;
- /**
- * Represents an Angular View in the Rendering Context.
- *
- * `RenderViewRef` specifies to the {@link Renderer} what View to update or destroy.
- *
- * Unlike a {@link ViewRef} available in the Application Context, Render View contains all the
- * static Component Views that have been recursively merged into a single Render View.
- *
- * Each `RenderViewRef` contains one or more {@link RenderFragmentRef Render Fragments}, these
- * Fragments are created, hydrated, dehydrated and destroyed as a single unit together with the
- * View.
- */
- // TODO(i): refactor into an interface
- var RenderViewRef = (function () {
- function RenderViewRef() {
- }
- return RenderViewRef;
- })();
- exports.RenderViewRef = RenderViewRef;
- /**
- * Abstract base class for commands to the Angular renderer, using the visitor pattern.
- */
- var RenderTemplateCmd = (function () {
- function RenderTemplateCmd() {
- }
- return RenderTemplateCmd;
- })();
- exports.RenderTemplateCmd = RenderTemplateCmd;
- /**
- * Command to begin rendering.
- */
- var RenderBeginCmd = (function (_super) {
- __extends(RenderBeginCmd, _super);
- function RenderBeginCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(RenderBeginCmd.prototype, "ngContentIndex", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(RenderBeginCmd.prototype, "isBound", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return RenderBeginCmd;
- })(RenderTemplateCmd);
- exports.RenderBeginCmd = RenderBeginCmd;
- /**
- * Command to render text.
- */
- var RenderTextCmd = (function (_super) {
- __extends(RenderTextCmd, _super);
- function RenderTextCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(RenderTextCmd.prototype, "value", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return RenderTextCmd;
- })(RenderBeginCmd);
- exports.RenderTextCmd = RenderTextCmd;
- /**
- * Command to render projected content.
- */
- var RenderNgContentCmd = (function (_super) {
- __extends(RenderNgContentCmd, _super);
- function RenderNgContentCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(RenderNgContentCmd.prototype, "index", {
- // The index of this NgContent element
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(RenderNgContentCmd.prototype, "ngContentIndex", {
- // The index of the NgContent element into which this
- // NgContent element should be projected (if any)
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return RenderNgContentCmd;
- })(RenderTemplateCmd);
- exports.RenderNgContentCmd = RenderNgContentCmd;
- /**
- * Command to begin rendering an element.
- */
- var RenderBeginElementCmd = (function (_super) {
- __extends(RenderBeginElementCmd, _super);
- function RenderBeginElementCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(RenderBeginElementCmd.prototype, "name", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(RenderBeginElementCmd.prototype, "attrNameAndValues", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(RenderBeginElementCmd.prototype, "eventTargetAndNames", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return RenderBeginElementCmd;
- })(RenderBeginCmd);
- exports.RenderBeginElementCmd = RenderBeginElementCmd;
- /**
- * Command to begin rendering a component.
- */
- var RenderBeginComponentCmd = (function (_super) {
- __extends(RenderBeginComponentCmd, _super);
- function RenderBeginComponentCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(RenderBeginComponentCmd.prototype, "templateId", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return RenderBeginComponentCmd;
- })(RenderBeginElementCmd);
- exports.RenderBeginComponentCmd = RenderBeginComponentCmd;
- /**
- * Command to render a component's template.
- */
- var RenderEmbeddedTemplateCmd = (function (_super) {
- __extends(RenderEmbeddedTemplateCmd, _super);
- function RenderEmbeddedTemplateCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(RenderEmbeddedTemplateCmd.prototype, "isMerged", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(RenderEmbeddedTemplateCmd.prototype, "children", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return RenderEmbeddedTemplateCmd;
- })(RenderBeginElementCmd);
- exports.RenderEmbeddedTemplateCmd = RenderEmbeddedTemplateCmd;
- /**
- * Container class produced by a {@link Renderer} when creating a Render View.
- *
- * An instance of `RenderViewWithFragments` contains a {@link RenderViewRef} and an array of
- * {@link RenderFragmentRef}s belonging to this Render View.
- */
- // TODO(i): refactor this by RenderViewWithFragments and adding fragments directly to RenderViewRef
- var RenderViewWithFragments = (function () {
- function RenderViewWithFragments(
- /**
- * Reference to the {@link RenderViewRef}.
- */
- viewRef,
- /**
- * Array of {@link RenderFragmentRef}s ordered in the depth-first order.
- */
- fragmentRefs) {
- this.viewRef = viewRef;
- this.fragmentRefs = fragmentRefs;
- }
- return RenderViewWithFragments;
- })();
- exports.RenderViewWithFragments = RenderViewWithFragments;
- /**
- * Template for rendering a component, including commands and styles.
- */
- var RenderComponentTemplate = (function () {
- function RenderComponentTemplate(id, shortId, encapsulation, commands, styles) {
- this.id = id;
- this.shortId = shortId;
- this.encapsulation = encapsulation;
- this.commands = commands;
- this.styles = styles;
- }
- return RenderComponentTemplate;
- })();
- exports.RenderComponentTemplate = RenderComponentTemplate;
- /**
- * Injectable service that provides a low-level interface for modifying the UI.
- *
- * Use this service to bypass Angular's templating and make custom UI changes that can't be
- * expressed declaratively. For example if you need to set a property or an attribute whose name is
- * not statically known, use {@link #setElementProperty} or {@link #setElementAttribute}
- * respectively.
- *
- * If you are implementing a custom renderer, you must implement this interface.
- *
- * The default Renderer implementation is `DomRenderer`. Also available is `WebWorkerRenderer`.
- */
- var Renderer = (function () {
- function Renderer() {
- }
- return Renderer;
- })();
- exports.Renderer = Renderer;
- /***/ },
- /* 73 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var provider_1 = __webpack_require__(13);
- var di_1 = __webpack_require__(6);
- var PipeProvider = (function (_super) {
- __extends(PipeProvider, _super);
- function PipeProvider(name, pure, key, resolvedFactories, multiBinding) {
- _super.call(this, key, resolvedFactories, multiBinding);
- this.name = name;
- this.pure = pure;
- }
- PipeProvider.createFromType = function (type, metadata) {
- var provider = new di_1.Provider(type, { useClass: type });
- var rb = provider_1.resolveProvider(provider);
- return new PipeProvider(metadata.name, metadata.pure, rb.key, rb.resolvedFactories, rb.multiProvider);
- };
- return PipeProvider;
- })(provider_1.ResolvedProvider_);
- exports.PipeProvider = PipeProvider;
- /***/ },
- /* 74 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var cd = __webpack_require__(75);
- var ProtoPipes = (function () {
- function ProtoPipes(
- /**
- * Map of {@link PipeMetadata} names to {@link PipeMetadata} implementations.
- */
- config) {
- this.config = config;
- this.config = config;
- }
- ProtoPipes.fromProviders = function (providers) {
- var config = {};
- providers.forEach(function (b) { return config[b.name] = b; });
- return new ProtoPipes(config);
- };
- ProtoPipes.prototype.get = function (name) {
- var provider = this.config[name];
- if (lang_1.isBlank(provider))
- throw new exceptions_1.BaseException("Cannot find pipe '" + name + "'.");
- return provider;
- };
- return ProtoPipes;
- })();
- exports.ProtoPipes = ProtoPipes;
- var Pipes = (function () {
- function Pipes(proto, injector) {
- this.proto = proto;
- this.injector = injector;
- /** @internal */
- this._config = {};
- }
- Pipes.prototype.get = function (name) {
- var cached = collection_1.StringMapWrapper.get(this._config, name);
- if (lang_1.isPresent(cached))
- return cached;
- var p = this.proto.get(name);
- var transform = this.injector.instantiateResolved(p);
- var res = new cd.SelectedPipe(transform, p.pure);
- if (p.pure) {
- collection_1.StringMapWrapper.set(this._config, name, res);
- }
- return res;
- };
- return Pipes;
- })();
- exports.Pipes = Pipes;
- /***/ },
- /* 75 */
- /***/ function(module, exports) {
- var SelectedPipe = (function () {
- function SelectedPipe(pipe, pure) {
- this.pipe = pipe;
- this.pure = pure;
- }
- return SelectedPipe;
- })();
- exports.SelectedPipe = SelectedPipe;
- /***/ },
- /* 76 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var change_detection_1 = __webpack_require__(25);
- var interfaces_1 = __webpack_require__(35);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var view_ref_1 = __webpack_require__(77);
- var util_1 = __webpack_require__(78);
- var view_ref_2 = __webpack_require__(77);
- var interfaces_2 = __webpack_require__(35);
- exports.DebugContext = interfaces_2.DebugContext;
- var REFLECT_PREFIX = 'ng-reflect-';
- (function (ViewType) {
- // A view that contains the host element with bound component directive.
- // Contains a COMPONENT view
- ViewType[ViewType["HOST"] = 0] = "HOST";
- // The view of the component
- // Can contain 0 to n EMBEDDED views
- ViewType[ViewType["COMPONENT"] = 1] = "COMPONENT";
- // A view that is embedded into another View via a <template> element
- // inside of a COMPONENT view
- ViewType[ViewType["EMBEDDED"] = 2] = "EMBEDDED";
- })(exports.ViewType || (exports.ViewType = {}));
- var ViewType = exports.ViewType;
- var AppViewContainer = (function () {
- function AppViewContainer() {
- // The order in this list matches the DOM order.
- this.views = [];
- }
- return AppViewContainer;
- })();
- exports.AppViewContainer = AppViewContainer;
- /**
- * Cost of making objects: http://jsperf.com/instantiate-size-of-object
- *
- */
- var AppView = (function () {
- function AppView(renderer, proto, viewOffset, elementOffset, textOffset, protoLocals, render, renderFragment, containerElementInjector) {
- this.renderer = renderer;
- this.proto = proto;
- this.viewOffset = viewOffset;
- this.elementOffset = elementOffset;
- this.textOffset = textOffset;
- this.render = render;
- this.renderFragment = renderFragment;
- this.containerElementInjector = containerElementInjector;
- // AppViews that have been merged in depth first order.
- // This list is shared between all merged views. Use this.elementOffset to get the local
- // entries.
- this.views = null;
- // ElementInjectors of all AppViews in views grouped by view.
- // This list is shared between all merged views. Use this.elementOffset to get the local
- // entries.
- this.elementInjectors = null;
- // ViewContainers of all AppViews in views grouped by view.
- // This list is shared between all merged views. Use this.elementOffset to get the local
- // entries.
- this.viewContainers = null;
- // PreBuiltObjects of all AppViews in views grouped by view.
- // This list is shared between all merged views. Use this.elementOffset to get the local
- // entries.
- this.preBuiltObjects = null;
- this.changeDetector = null;
- /**
- * The context against which data-binding expressions in this view are evaluated against.
- * This is always a component instance.
- */
- this.context = null;
- this.ref = new view_ref_2.ViewRef_(this);
- this.locals = new change_detection_1.Locals(null, collection_1.MapWrapper.clone(protoLocals)); // TODO optimize this
- }
- AppView.prototype.init = function (changeDetector, elementInjectors, rootElementInjectors, preBuiltObjects, views, elementRefs, viewContainers) {
- this.changeDetector = changeDetector;
- this.elementInjectors = elementInjectors;
- this.rootElementInjectors = rootElementInjectors;
- this.preBuiltObjects = preBuiltObjects;
- this.views = views;
- this.elementRefs = elementRefs;
- this.viewContainers = viewContainers;
- };
- AppView.prototype.setLocal = function (contextName, value) {
- if (!this.hydrated())
- throw new exceptions_1.BaseException('Cannot set locals on dehydrated view.');
- if (!this.proto.templateVariableBindings.has(contextName)) {
- return;
- }
- var templateName = this.proto.templateVariableBindings.get(contextName);
- this.locals.set(templateName, value);
- };
- AppView.prototype.hydrated = function () { return lang_1.isPresent(this.context); };
- /**
- * Triggers the event handlers for the element and the directives.
- *
- * This method is intended to be called from directive EventEmitters.
- *
- * @param {string} eventName
- * @param {*} eventObj
- * @param {number} boundElementIndex
- */
- AppView.prototype.triggerEventHandlers = function (eventName, eventObj, boundElementIndex) {
- var locals = new collection_1.Map();
- locals.set('$event', eventObj);
- this.dispatchEvent(boundElementIndex, eventName, locals);
- };
- // dispatch to element injector or text nodes based on context
- AppView.prototype.notifyOnBinding = function (b, currentValue) {
- if (b.isTextNode()) {
- this.renderer.setText(this.render, b.elementIndex + this.textOffset, currentValue);
- }
- else {
- var elementRef = this.elementRefs[this.elementOffset + b.elementIndex];
- if (b.isElementProperty()) {
- this.renderer.setElementProperty(elementRef, b.name, currentValue);
- }
- else if (b.isElementAttribute()) {
- this.renderer.setElementAttribute(elementRef, b.name, lang_1.isPresent(currentValue) ? "" + currentValue : null);
- }
- else if (b.isElementClass()) {
- this.renderer.setElementClass(elementRef, b.name, currentValue);
- }
- else if (b.isElementStyle()) {
- var unit = lang_1.isPresent(b.unit) ? b.unit : '';
- this.renderer.setElementStyle(elementRef, b.name, lang_1.isPresent(currentValue) ? "" + currentValue + unit : null);
- }
- else {
- throw new exceptions_1.BaseException('Unsupported directive record');
- }
- }
- };
- AppView.prototype.logBindingUpdate = function (b, value) {
- if (b.isDirective() || b.isElementProperty()) {
- var elementRef = this.elementRefs[this.elementOffset + b.elementIndex];
- this.renderer.setBindingDebugInfo(elementRef, "" + REFLECT_PREFIX + util_1.camelCaseToDashCase(b.name), "" + value);
- }
- };
- AppView.prototype.notifyAfterContentChecked = function () {
- var eiCount = this.proto.elementBinders.length;
- var ei = this.elementInjectors;
- for (var i = eiCount - 1; i >= 0; i--) {
- if (lang_1.isPresent(ei[i + this.elementOffset]))
- ei[i + this.elementOffset].ngAfterContentChecked();
- }
- };
- AppView.prototype.notifyAfterViewChecked = function () {
- var eiCount = this.proto.elementBinders.length;
- var ei = this.elementInjectors;
- for (var i = eiCount - 1; i >= 0; i--) {
- if (lang_1.isPresent(ei[i + this.elementOffset]))
- ei[i + this.elementOffset].ngAfterViewChecked();
- }
- };
- AppView.prototype.getDirectiveFor = function (directive) {
- var elementInjector = this.elementInjectors[this.elementOffset + directive.elementIndex];
- return elementInjector.getDirectiveAtIndex(directive.directiveIndex);
- };
- AppView.prototype.getNestedView = function (boundElementIndex) {
- var eli = this.elementInjectors[boundElementIndex];
- return lang_1.isPresent(eli) ? eli.getNestedView() : null;
- };
- AppView.prototype.getContainerElement = function () {
- return lang_1.isPresent(this.containerElementInjector) ?
- this.containerElementInjector.getElementRef() :
- null;
- };
- AppView.prototype.getDebugContext = function (elementIndex, directiveIndex) {
- try {
- var offsettedIndex = this.elementOffset + elementIndex;
- var hasRefForIndex = offsettedIndex < this.elementRefs.length;
- var elementRef = hasRefForIndex ? this.elementRefs[this.elementOffset + elementIndex] : null;
- var container = this.getContainerElement();
- var ei = hasRefForIndex ? this.elementInjectors[this.elementOffset + elementIndex] : null;
- var element = lang_1.isPresent(elementRef) ? elementRef.nativeElement : null;
- var componentElement = lang_1.isPresent(container) ? container.nativeElement : null;
- var directive = lang_1.isPresent(directiveIndex) ? this.getDirectiveFor(directiveIndex) : null;
- var injector = lang_1.isPresent(ei) ? ei.getInjector() : null;
- return new interfaces_1.DebugContext(element, componentElement, directive, this.context, _localsToStringMap(this.locals), injector);
- }
- catch (e) {
- // TODO: vsavkin log the exception once we have a good way to log errors and warnings
- // if an error happens during getting the debug context, we return null.
- return null;
- }
- };
- AppView.prototype.getDetectorFor = function (directive) {
- var childView = this.getNestedView(this.elementOffset + directive.elementIndex);
- return lang_1.isPresent(childView) ? childView.changeDetector : null;
- };
- AppView.prototype.invokeElementMethod = function (elementIndex, methodName, args) {
- this.renderer.invokeElementMethod(this.elementRefs[elementIndex], methodName, args);
- };
- // implementation of RenderEventDispatcher#dispatchRenderEvent
- AppView.prototype.dispatchRenderEvent = function (boundElementIndex, eventName, locals) {
- var elementRef = this.elementRefs[boundElementIndex];
- var view = view_ref_1.internalView(elementRef.parentView);
- return view.dispatchEvent(elementRef.boundElementIndex, eventName, locals);
- };
- // returns false if preventDefault must be applied to the DOM event
- AppView.prototype.dispatchEvent = function (boundElementIndex, eventName, locals) {
- try {
- if (this.hydrated()) {
- return !this.changeDetector.handleEvent(eventName, boundElementIndex - this.elementOffset, new change_detection_1.Locals(this.locals, locals));
- }
- else {
- return true;
- }
- }
- catch (e) {
- var c = this.getDebugContext(boundElementIndex - this.elementOffset, null);
- var context = lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.context, c.locals, c.injector) :
- null;
- throw new EventEvaluationError(eventName, e, e.stack, context);
- }
- };
- Object.defineProperty(AppView.prototype, "ownBindersCount", {
- get: function () { return this.proto.elementBinders.length; },
- enumerable: true,
- configurable: true
- });
- return AppView;
- })();
- exports.AppView = AppView;
- function _localsToStringMap(locals) {
- var res = {};
- var c = locals;
- while (lang_1.isPresent(c)) {
- res = collection_1.StringMapWrapper.merge(res, collection_1.MapWrapper.toStringMap(c.current));
- c = c.parent;
- }
- return res;
- }
- /**
- * Error context included when an event handler throws an exception.
- */
- var _Context = (function () {
- function _Context(element, componentElement, context, locals, injector) {
- this.element = element;
- this.componentElement = componentElement;
- this.context = context;
- this.locals = locals;
- this.injector = injector;
- }
- return _Context;
- })();
- /**
- * Wraps an exception thrown by an event handler.
- */
- var EventEvaluationError = (function (_super) {
- __extends(EventEvaluationError, _super);
- function EventEvaluationError(eventName, originalException, originalStack, context) {
- _super.call(this, "Error during evaluation of \"" + eventName + "\"", originalException, originalStack, context);
- }
- return EventEvaluationError;
- })(exceptions_1.WrappedException);
- var AppProtoViewMergeInfo = (function () {
- function AppProtoViewMergeInfo(embeddedViewCount, elementCount, viewCount) {
- this.embeddedViewCount = embeddedViewCount;
- this.elementCount = elementCount;
- this.viewCount = viewCount;
- }
- return AppProtoViewMergeInfo;
- })();
- exports.AppProtoViewMergeInfo = AppProtoViewMergeInfo;
- /**
- *
- */
- var AppProtoView = (function () {
- function AppProtoView(templateId, templateCmds, type, isMergable, changeDetectorFactory, templateVariableBindings, pipes) {
- this.templateId = templateId;
- this.templateCmds = templateCmds;
- this.type = type;
- this.isMergable = isMergable;
- this.changeDetectorFactory = changeDetectorFactory;
- this.templateVariableBindings = templateVariableBindings;
- this.pipes = pipes;
- this.elementBinders = null;
- this.mergeInfo = null;
- this.variableLocations = null;
- this.textBindingCount = null;
- this.render = null;
- this.ref = new view_ref_2.ProtoViewRef_(this);
- }
- AppProtoView.prototype.init = function (render, elementBinders, textBindingCount, mergeInfo, variableLocations) {
- var _this = this;
- this.render = render;
- this.elementBinders = elementBinders;
- this.textBindingCount = textBindingCount;
- this.mergeInfo = mergeInfo;
- this.variableLocations = variableLocations;
- this.protoLocals = new collection_1.Map();
- if (lang_1.isPresent(this.templateVariableBindings)) {
- this.templateVariableBindings.forEach(function (templateName, _) { _this.protoLocals.set(templateName, null); });
- }
- if (lang_1.isPresent(variableLocations)) {
- // The view's locals needs to have a full set of variable names at construction time
- // in order to prevent new variables from being set later in the lifecycle. Since we don't
- // want
- // to actually create variable bindings for the $implicit bindings, add to the
- // protoLocals manually.
- variableLocations.forEach(function (_, templateName) { _this.protoLocals.set(templateName, null); });
- }
- };
- AppProtoView.prototype.isInitialized = function () { return lang_1.isPresent(this.elementBinders); };
- return AppProtoView;
- })();
- exports.AppProtoView = AppProtoView;
- /***/ },
- /* 77 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- // This is a workaround for privacy in Dart as we don't have library parts
- function internalView(viewRef) {
- return viewRef._view;
- }
- exports.internalView = internalView;
- // This is a workaround for privacy in Dart as we don't have library parts
- function internalProtoView(protoViewRef) {
- return lang_1.isPresent(protoViewRef) ? protoViewRef._protoView : null;
- }
- exports.internalProtoView = internalProtoView;
- /**
- * Represents an Angular View.
- *
- * <!-- TODO: move the next two paragraphs to the dev guide -->
- * A View is a fundamental building block of the application UI. It is the smallest grouping of
- * Elements which are created and destroyed together.
- *
- * Properties of elements in a View can change, but the structure (number and order) of elements in
- * a View cannot. Changing the structure of Elements can only be done by inserting, moving or
- * removing nested Views via a {@link ViewContainerRef}. Each View can contain many View Containers.
- * <!-- /TODO -->
- *
- * ### Example
- *
- * Given this template...
- *
- * ```
- * Count: {{items.length}}
- * <ul>
- * <li *ngFor="var item of items">{{item}}</li>
- * </ul>
- * ```
- *
- * ... we have two {@link ProtoViewRef}s:
- *
- * Outer {@link ProtoViewRef}:
- * ```
- * Count: {{items.length}}
- * <ul>
- * <template ngFor var-item [ngForOf]="items"></template>
- * </ul>
- * ```
- *
- * Inner {@link ProtoViewRef}:
- * ```
- * <li>{{item}}</li>
- * ```
- *
- * Notice that the original template is broken down into two separate {@link ProtoViewRef}s.
- *
- * The outer/inner {@link ProtoViewRef}s are then assembled into views like so:
- *
- * ```
- * <!-- ViewRef: outer-0 -->
- * Count: 2
- * <ul>
- * <template view-container-ref></template>
- * <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
- * <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
- * </ul>
- * <!-- /ViewRef: outer-0 -->
- * ```
- */
- var ViewRef = (function () {
- function ViewRef() {
- }
- Object.defineProperty(ViewRef.prototype, "changeDetectorRef", {
- get: function () { return exceptions_1.unimplemented(); },
- set: function (value) {
- exceptions_1.unimplemented(); // TODO: https://github.com/Microsoft/TypeScript/issues/12
- },
- enumerable: true,
- configurable: true
- });
- return ViewRef;
- })();
- exports.ViewRef = ViewRef;
- var ViewRef_ = (function (_super) {
- __extends(ViewRef_, _super);
- function ViewRef_(_view) {
- _super.call(this);
- this._changeDetectorRef = null;
- this._view = _view;
- }
- Object.defineProperty(ViewRef_.prototype, "render", {
- /**
- * Return `RenderViewRef`
- */
- get: function () { return this._view.render; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ViewRef_.prototype, "renderFragment", {
- /**
- * Return `RenderFragmentRef`
- */
- get: function () { return this._view.renderFragment; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ViewRef_.prototype, "changeDetectorRef", {
- /**
- * Return `ChangeDetectorRef`
- */
- get: function () {
- if (this._changeDetectorRef === null) {
- this._changeDetectorRef = this._view.changeDetector.ref;
- }
- return this._changeDetectorRef;
- },
- enumerable: true,
- configurable: true
- });
- ViewRef_.prototype.setLocal = function (variableName, value) { this._view.setLocal(variableName, value); };
- return ViewRef_;
- })(ViewRef);
- exports.ViewRef_ = ViewRef_;
- /**
- * Represents an Angular ProtoView.
- *
- * A ProtoView is a prototypical {@link ViewRef View} that is the result of Template compilation and
- * is used by Angular to efficiently create an instance of this View based on the compiled Template.
- *
- * Most ProtoViews are created and used internally by Angular and you don't need to know about them,
- * except in advanced use-cases where you compile components yourself via the low-level
- * {@link Compiler#compileInHost} API.
- *
- *
- * ### Example
- *
- * Given this template:
- *
- * ```
- * Count: {{items.length}}
- * <ul>
- * <li *ngFor="var item of items">{{item}}</li>
- * </ul>
- * ```
- *
- * Angular desugars and compiles the template into two ProtoViews:
- *
- * Outer ProtoView:
- * ```
- * Count: {{items.length}}
- * <ul>
- * <template ngFor var-item [ngForOf]="items"></template>
- * </ul>
- * ```
- *
- * Inner ProtoView:
- * ```
- * <li>{{item}}</li>
- * ```
- *
- * Notice that the original template is broken down into two separate ProtoViews.
- */
- var ProtoViewRef = (function () {
- function ProtoViewRef() {
- }
- return ProtoViewRef;
- })();
- exports.ProtoViewRef = ProtoViewRef;
- var ProtoViewRef_ = (function (_super) {
- __extends(ProtoViewRef_, _super);
- function ProtoViewRef_(_protoView) {
- _super.call(this);
- this._protoView = _protoView;
- }
- return ProtoViewRef_;
- })(ProtoViewRef);
- exports.ProtoViewRef_ = ProtoViewRef_;
- /***/ },
- /* 78 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var CAMEL_CASE_REGEXP = /([A-Z])/g;
- var DASH_CASE_REGEXP = /-([a-z])/g;
- function camelCaseToDashCase(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function (m) { return '-' + m[1].toLowerCase(); });
- }
- exports.camelCaseToDashCase = camelCaseToDashCase;
- function dashCaseToCamelCase(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function (m) { return m[1].toUpperCase(); });
- }
- exports.dashCaseToCamelCase = dashCaseToCamelCase;
- /***/ },
- /* 79 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var ElementBinder = (function () {
- function ElementBinder(index, parent, distanceToParent, protoElementInjector, componentDirective, nestedProtoView) {
- this.index = index;
- this.parent = parent;
- this.distanceToParent = distanceToParent;
- this.protoElementInjector = protoElementInjector;
- this.componentDirective = componentDirective;
- this.nestedProtoView = nestedProtoView;
- if (lang_1.isBlank(index)) {
- throw new exceptions_1.BaseException('null index not allowed.');
- }
- }
- return ElementBinder;
- })();
- exports.ElementBinder = ElementBinder;
- /***/ },
- /* 80 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var async_1 = __webpack_require__(60);
- var collection_1 = __webpack_require__(12);
- var di_1 = __webpack_require__(6);
- var injector_1 = __webpack_require__(11);
- var provider_1 = __webpack_require__(13);
- var di_2 = __webpack_require__(4);
- /* circular */ var avmModule = __webpack_require__(81);
- var view_container_ref_1 = __webpack_require__(87);
- var element_ref_1 = __webpack_require__(83);
- var template_ref_1 = __webpack_require__(84);
- var directives_1 = __webpack_require__(23);
- var directive_lifecycle_reflector_1 = __webpack_require__(88);
- var change_detection_1 = __webpack_require__(25);
- var query_list_1 = __webpack_require__(90);
- var reflection_1 = __webpack_require__(16);
- var event_config_1 = __webpack_require__(91);
- var pipe_provider_1 = __webpack_require__(73);
- var interfaces_1 = __webpack_require__(89);
- var view_container_ref_2 = __webpack_require__(87);
- var _staticKeys;
- var StaticKeys = (function () {
- function StaticKeys() {
- this.viewManagerId = di_1.Key.get(avmModule.AppViewManager).id;
- this.templateRefId = di_1.Key.get(template_ref_1.TemplateRef).id;
- this.viewContainerId = di_1.Key.get(view_container_ref_1.ViewContainerRef).id;
- this.changeDetectorRefId = di_1.Key.get(change_detection_1.ChangeDetectorRef).id;
- this.elementRefId = di_1.Key.get(element_ref_1.ElementRef).id;
- }
- StaticKeys.instance = function () {
- if (lang_1.isBlank(_staticKeys))
- _staticKeys = new StaticKeys();
- return _staticKeys;
- };
- return StaticKeys;
- })();
- exports.StaticKeys = StaticKeys;
- var TreeNode = (function () {
- function TreeNode(parent) {
- if (lang_1.isPresent(parent)) {
- parent.addChild(this);
- }
- else {
- this._parent = null;
- }
- }
- TreeNode.prototype.addChild = function (child) { child._parent = this; };
- TreeNode.prototype.remove = function () { this._parent = null; };
- Object.defineProperty(TreeNode.prototype, "parent", {
- get: function () { return this._parent; },
- enumerable: true,
- configurable: true
- });
- return TreeNode;
- })();
- exports.TreeNode = TreeNode;
- var DirectiveDependency = (function (_super) {
- __extends(DirectiveDependency, _super);
- function DirectiveDependency(key, optional, lowerBoundVisibility, upperBoundVisibility, properties, attributeName, queryDecorator) {
- _super.call(this, key, optional, lowerBoundVisibility, upperBoundVisibility, properties);
- this.attributeName = attributeName;
- this.queryDecorator = queryDecorator;
- this._verify();
- }
- /** @internal */
- DirectiveDependency.prototype._verify = function () {
- var count = 0;
- if (lang_1.isPresent(this.queryDecorator))
- count++;
- if (lang_1.isPresent(this.attributeName))
- count++;
- if (count > 1)
- throw new exceptions_1.BaseException('A directive injectable can contain only one of the following @Attribute or @Query.');
- };
- DirectiveDependency.createFrom = function (d) {
- return new DirectiveDependency(d.key, d.optional, d.lowerBoundVisibility, d.upperBoundVisibility, d.properties, DirectiveDependency._attributeName(d.properties), DirectiveDependency._query(d.properties));
- };
- /** @internal */
- DirectiveDependency._attributeName = function (properties) {
- var p = properties.find(function (p) { return p instanceof di_2.AttributeMetadata; });
- return lang_1.isPresent(p) ? p.attributeName : null;
- };
- /** @internal */
- DirectiveDependency._query = function (properties) {
- return properties.find(function (p) { return p instanceof di_2.QueryMetadata; });
- };
- return DirectiveDependency;
- })(di_1.Dependency);
- exports.DirectiveDependency = DirectiveDependency;
- var DirectiveProvider = (function (_super) {
- __extends(DirectiveProvider, _super);
- function DirectiveProvider(key, factory, deps, metadata, providers, viewProviders) {
- _super.call(this, key, [new provider_1.ResolvedFactory(factory, deps)], false);
- this.metadata = metadata;
- this.providers = providers;
- this.viewProviders = viewProviders;
- this.callOnDestroy = directive_lifecycle_reflector_1.hasLifecycleHook(interfaces_1.LifecycleHooks.OnDestroy, key.token);
- }
- Object.defineProperty(DirectiveProvider.prototype, "displayName", {
- get: function () { return this.key.displayName; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveProvider.prototype, "queries", {
- get: function () {
- if (lang_1.isBlank(this.metadata.queries))
- return [];
- var res = [];
- collection_1.StringMapWrapper.forEach(this.metadata.queries, function (meta, fieldName) {
- var setter = reflection_1.reflector.setter(fieldName);
- res.push(new QueryMetadataWithSetter(setter, meta));
- });
- return res;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DirectiveProvider.prototype, "eventEmitters", {
- get: function () {
- return lang_1.isPresent(this.metadata) && lang_1.isPresent(this.metadata.outputs) ? this.metadata.outputs :
- [];
- },
- enumerable: true,
- configurable: true
- });
- DirectiveProvider.createFromProvider = function (provider, meta) {
- if (lang_1.isBlank(meta)) {
- meta = new directives_1.DirectiveMetadata();
- }
- var rb = provider_1.resolveProvider(provider);
- var rf = rb.resolvedFactories[0];
- var deps = rf.dependencies.map(DirectiveDependency.createFrom);
- var providers = lang_1.isPresent(meta.providers) ? meta.providers : [];
- var viewBindigs = meta instanceof directives_1.ComponentMetadata && lang_1.isPresent(meta.viewProviders) ?
- meta.viewProviders :
- [];
- return new DirectiveProvider(rb.key, rf.factory, deps, meta, providers, viewBindigs);
- };
- DirectiveProvider.createFromType = function (type, annotation) {
- var provider = new di_1.Provider(type, { useClass: type });
- return DirectiveProvider.createFromProvider(provider, annotation);
- };
- return DirectiveProvider;
- })(provider_1.ResolvedProvider_);
- exports.DirectiveProvider = DirectiveProvider;
- // TODO(rado): benchmark and consider rolling in as ElementInjector fields.
- var PreBuiltObjects = (function () {
- function PreBuiltObjects(viewManager, view, elementRef, templateRef) {
- this.viewManager = viewManager;
- this.view = view;
- this.elementRef = elementRef;
- this.templateRef = templateRef;
- this.nestedView = null;
- }
- return PreBuiltObjects;
- })();
- exports.PreBuiltObjects = PreBuiltObjects;
- var QueryMetadataWithSetter = (function () {
- function QueryMetadataWithSetter(setter, metadata) {
- this.setter = setter;
- this.metadata = metadata;
- }
- return QueryMetadataWithSetter;
- })();
- exports.QueryMetadataWithSetter = QueryMetadataWithSetter;
- var EventEmitterAccessor = (function () {
- function EventEmitterAccessor(eventName, getter) {
- this.eventName = eventName;
- this.getter = getter;
- }
- EventEmitterAccessor.prototype.subscribe = function (view, boundElementIndex, directive) {
- var _this = this;
- var eventEmitter = this.getter(directive);
- return async_1.ObservableWrapper.subscribe(eventEmitter, function (eventObj) { return view.triggerEventHandlers(_this.eventName, eventObj, boundElementIndex); });
- };
- return EventEmitterAccessor;
- })();
- exports.EventEmitterAccessor = EventEmitterAccessor;
- function _createEventEmitterAccessors(bwv) {
- var provider = bwv.provider;
- if (!(provider instanceof DirectiveProvider))
- return [];
- var db = provider;
- return db.eventEmitters.map(function (eventConfig) {
- var parsedEvent = event_config_1.EventConfig.parse(eventConfig);
- return new EventEmitterAccessor(parsedEvent.eventName, reflection_1.reflector.getter(parsedEvent.fieldName));
- });
- }
- function _createProtoQueryRefs(providers) {
- var res = [];
- collection_1.ListWrapper.forEachWithIndex(providers, function (b, i) {
- if (b.provider instanceof DirectiveProvider) {
- var directiveProvider = b.provider;
- // field queries
- var queries = directiveProvider.queries;
- queries.forEach(function (q) { return res.push(new ProtoQueryRef(i, q.setter, q.metadata)); });
- // queries passed into the constructor.
- // TODO: remove this after constructor queries are no longer supported
- var deps = directiveProvider.resolvedFactory.dependencies;
- deps.forEach(function (d) {
- if (lang_1.isPresent(d.queryDecorator))
- res.push(new ProtoQueryRef(i, null, d.queryDecorator));
- });
- }
- });
- return res;
- }
- var ProtoElementInjector = (function () {
- function ProtoElementInjector(parent, index, bwv, distanceToParent, _firstProviderIsComponent, directiveVariableBindings) {
- this.parent = parent;
- this.index = index;
- this.distanceToParent = distanceToParent;
- this.directiveVariableBindings = directiveVariableBindings;
- this._firstProviderIsComponent = _firstProviderIsComponent;
- var length = bwv.length;
- this.protoInjector = new injector_1.ProtoInjector(bwv);
- this.eventEmitterAccessors = collection_1.ListWrapper.createFixedSize(length);
- for (var i = 0; i < length; ++i) {
- this.eventEmitterAccessors[i] = _createEventEmitterAccessors(bwv[i]);
- }
- this.protoQueryRefs = _createProtoQueryRefs(bwv);
- }
- ProtoElementInjector.create = function (parent, index, providers, firstProviderIsComponent, distanceToParent, directiveVariableBindings) {
- var bd = [];
- ProtoElementInjector._createDirectiveProviderWithVisibility(providers, bd, firstProviderIsComponent);
- if (firstProviderIsComponent) {
- ProtoElementInjector._createViewProvidersWithVisibility(providers, bd);
- }
- ProtoElementInjector._createProvidersWithVisibility(providers, bd);
- return new ProtoElementInjector(parent, index, bd, distanceToParent, firstProviderIsComponent, directiveVariableBindings);
- };
- ProtoElementInjector._createDirectiveProviderWithVisibility = function (dirProviders, bd, firstProviderIsComponent) {
- dirProviders.forEach(function (dirProvider) {
- bd.push(ProtoElementInjector._createProviderWithVisibility(firstProviderIsComponent, dirProvider, dirProviders, dirProvider));
- });
- };
- ProtoElementInjector._createProvidersWithVisibility = function (dirProviders, bd) {
- var providersFromAllDirectives = [];
- dirProviders.forEach(function (dirProvider) {
- providersFromAllDirectives =
- collection_1.ListWrapper.concat(providersFromAllDirectives, dirProvider.providers);
- });
- var resolved = di_1.Injector.resolve(providersFromAllDirectives);
- resolved.forEach(function (b) { return bd.push(new injector_1.ProviderWithVisibility(b, injector_1.Visibility.Public)); });
- };
- ProtoElementInjector._createProviderWithVisibility = function (firstProviderIsComponent, dirProvider, dirProviders, provider) {
- var isComponent = firstProviderIsComponent && dirProviders[0] === dirProvider;
- return new injector_1.ProviderWithVisibility(provider, isComponent ? injector_1.Visibility.PublicAndPrivate : injector_1.Visibility.Public);
- };
- ProtoElementInjector._createViewProvidersWithVisibility = function (dirProviders, bd) {
- var resolvedViewProviders = di_1.Injector.resolve(dirProviders[0].viewProviders);
- resolvedViewProviders.forEach(function (b) { return bd.push(new injector_1.ProviderWithVisibility(b, injector_1.Visibility.Private)); });
- };
- ProtoElementInjector.prototype.instantiate = function (parent) {
- return new ElementInjector(this, parent);
- };
- ProtoElementInjector.prototype.directParent = function () { return this.distanceToParent < 2 ? this.parent : null; };
- Object.defineProperty(ProtoElementInjector.prototype, "hasBindings", {
- get: function () { return this.eventEmitterAccessors.length > 0; },
- enumerable: true,
- configurable: true
- });
- ProtoElementInjector.prototype.getProviderAtIndex = function (index) { return this.protoInjector.getProviderAtIndex(index); };
- return ProtoElementInjector;
- })();
- exports.ProtoElementInjector = ProtoElementInjector;
- var _Context = (function () {
- function _Context(element, componentElement, injector) {
- this.element = element;
- this.componentElement = componentElement;
- this.injector = injector;
- }
- return _Context;
- })();
- var ElementInjector = (function (_super) {
- __extends(ElementInjector, _super);
- function ElementInjector(_proto, parent) {
- var _this = this;
- _super.call(this, parent);
- this._preBuiltObjects = null;
- this._proto = _proto;
- this._injector =
- new di_1.Injector(this._proto.protoInjector, null, this, function () { return _this._debugContext(); });
- // we couple ourselves to the injector strategy to avoid polymoprhic calls
- var injectorStrategy = this._injector.internalStrategy;
- this._strategy = injectorStrategy instanceof injector_1.InjectorInlineStrategy ?
- new ElementInjectorInlineStrategy(injectorStrategy, this) :
- new ElementInjectorDynamicStrategy(injectorStrategy, this);
- this.hydrated = false;
- this._queryStrategy = this._buildQueryStrategy();
- }
- ElementInjector.prototype.dehydrate = function () {
- this.hydrated = false;
- this._host = null;
- this._preBuiltObjects = null;
- this._strategy.callOnDestroy();
- this._strategy.dehydrate();
- this._queryStrategy.dehydrate();
- };
- ElementInjector.prototype.hydrate = function (imperativelyCreatedInjector, host, preBuiltObjects) {
- this._host = host;
- this._preBuiltObjects = preBuiltObjects;
- this._reattachInjectors(imperativelyCreatedInjector);
- this._queryStrategy.hydrate();
- this._strategy.hydrate();
- this.hydrated = true;
- };
- ElementInjector.prototype._debugContext = function () {
- var p = this._preBuiltObjects;
- var index = p.elementRef.boundElementIndex - p.view.elementOffset;
- var c = this._preBuiltObjects.view.getDebugContext(index, null);
- return lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.injector) : null;
- };
- ElementInjector.prototype._reattachInjectors = function (imperativelyCreatedInjector) {
- // Dynamically-loaded component in the template. Not a root ElementInjector.
- if (lang_1.isPresent(this._parent)) {
- if (lang_1.isPresent(imperativelyCreatedInjector)) {
- // The imperative injector is similar to having an element between
- // the dynamic-loaded component and its parent => no boundaries.
- this._reattachInjector(this._injector, imperativelyCreatedInjector, false);
- this._reattachInjector(imperativelyCreatedInjector, this._parent._injector, false);
- }
- else {
- this._reattachInjector(this._injector, this._parent._injector, false);
- }
- }
- else if (lang_1.isPresent(this._host)) {
- // The imperative injector is similar to having an element between
- // the dynamic-loaded component and its parent => no boundary between
- // the component and imperativelyCreatedInjector.
- // But since it is a root ElementInjector, we need to create a boundary
- // between imperativelyCreatedInjector and _host.
- if (lang_1.isPresent(imperativelyCreatedInjector)) {
- this._reattachInjector(this._injector, imperativelyCreatedInjector, false);
- this._reattachInjector(imperativelyCreatedInjector, this._host._injector, true);
- }
- else {
- this._reattachInjector(this._injector, this._host._injector, true);
- }
- }
- else {
- if (lang_1.isPresent(imperativelyCreatedInjector)) {
- this._reattachInjector(this._injector, imperativelyCreatedInjector, true);
- }
- }
- };
- ElementInjector.prototype._reattachInjector = function (injector, parentInjector, isBoundary) {
- injector.internalStrategy.attach(parentInjector, isBoundary);
- };
- ElementInjector.prototype.hasVariableBinding = function (name) {
- var vb = this._proto.directiveVariableBindings;
- return lang_1.isPresent(vb) && vb.has(name);
- };
- ElementInjector.prototype.getVariableBinding = function (name) {
- var index = this._proto.directiveVariableBindings.get(name);
- return lang_1.isPresent(index) ? this.getDirectiveAtIndex(index) : this.getElementRef();
- };
- ElementInjector.prototype.get = function (token) { return this._injector.get(token); };
- ElementInjector.prototype.hasDirective = function (type) { return lang_1.isPresent(this._injector.getOptional(type)); };
- ElementInjector.prototype.getEventEmitterAccessors = function () { return this._proto.eventEmitterAccessors; };
- ElementInjector.prototype.getDirectiveVariableBindings = function () {
- return this._proto.directiveVariableBindings;
- };
- ElementInjector.prototype.getComponent = function () { return this._strategy.getComponent(); };
- ElementInjector.prototype.getInjector = function () { return this._injector; };
- ElementInjector.prototype.getElementRef = function () { return this._preBuiltObjects.elementRef; };
- ElementInjector.prototype.getViewContainerRef = function () {
- return new view_container_ref_2.ViewContainerRef_(this._preBuiltObjects.viewManager, this.getElementRef());
- };
- ElementInjector.prototype.getNestedView = function () { return this._preBuiltObjects.nestedView; };
- ElementInjector.prototype.getView = function () { return this._preBuiltObjects.view; };
- ElementInjector.prototype.directParent = function () { return this._proto.distanceToParent < 2 ? this.parent : null; };
- ElementInjector.prototype.isComponentKey = function (key) { return this._strategy.isComponentKey(key); };
- ElementInjector.prototype.getDependency = function (injector, provider, dep) {
- var key = dep.key;
- if (provider instanceof DirectiveProvider) {
- var dirDep = dep;
- var dirProvider = provider;
- var staticKeys = StaticKeys.instance();
- if (key.id === staticKeys.viewManagerId)
- return this._preBuiltObjects.viewManager;
- if (lang_1.isPresent(dirDep.attributeName))
- return this._buildAttribute(dirDep);
- if (lang_1.isPresent(dirDep.queryDecorator))
- return this._queryStrategy.findQuery(dirDep.queryDecorator).list;
- if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) {
- // We provide the component's view change detector to components and
- // the surrounding component's change detector to directives.
- if (dirProvider.metadata instanceof directives_1.ComponentMetadata) {
- var componentView = this._preBuiltObjects.view.getNestedView(this._preBuiltObjects.elementRef.boundElementIndex);
- return componentView.changeDetector.ref;
- }
- else {
- return this._preBuiltObjects.view.changeDetector.ref;
- }
- }
- if (dirDep.key.id === StaticKeys.instance().elementRefId) {
- return this.getElementRef();
- }
- if (dirDep.key.id === StaticKeys.instance().viewContainerId) {
- return this.getViewContainerRef();
- }
- if (dirDep.key.id === StaticKeys.instance().templateRefId) {
- if (lang_1.isBlank(this._preBuiltObjects.templateRef)) {
- if (dirDep.optional) {
- return null;
- }
- throw new di_1.NoProviderError(null, dirDep.key);
- }
- return this._preBuiltObjects.templateRef;
- }
- }
- else if (provider instanceof pipe_provider_1.PipeProvider) {
- if (dep.key.id === StaticKeys.instance().changeDetectorRefId) {
- var componentView = this._preBuiltObjects.view.getNestedView(this._preBuiltObjects.elementRef.boundElementIndex);
- return componentView.changeDetector.ref;
- }
- }
- return injector_1.UNDEFINED;
- };
- ElementInjector.prototype._buildAttribute = function (dep) {
- var attributes = this._proto.attributes;
- if (lang_1.isPresent(attributes) && attributes.has(dep.attributeName)) {
- return attributes.get(dep.attributeName);
- }
- else {
- return null;
- }
- };
- ElementInjector.prototype.addDirectivesMatchingQuery = function (query, list) {
- var templateRef = lang_1.isBlank(this._preBuiltObjects) ? null : this._preBuiltObjects.templateRef;
- if (query.selector === template_ref_1.TemplateRef && lang_1.isPresent(templateRef)) {
- list.push(templateRef);
- }
- this._strategy.addDirectivesMatchingQuery(query, list);
- };
- ElementInjector.prototype._buildQueryStrategy = function () {
- if (this._proto.protoQueryRefs.length === 0) {
- return _emptyQueryStrategy;
- }
- else if (this._proto.protoQueryRefs.length <=
- InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES) {
- return new InlineQueryStrategy(this);
- }
- else {
- return new DynamicQueryStrategy(this);
- }
- };
- ElementInjector.prototype.link = function (parent) { parent.addChild(this); };
- ElementInjector.prototype.unlink = function () { this.remove(); };
- ElementInjector.prototype.getDirectiveAtIndex = function (index) { return this._injector.getAt(index); };
- ElementInjector.prototype.hasInstances = function () { return this._proto.hasBindings && this.hydrated; };
- ElementInjector.prototype.getHost = function () { return this._host; };
- ElementInjector.prototype.getBoundElementIndex = function () { return this._proto.index; };
- ElementInjector.prototype.getRootViewInjectors = function () {
- if (!this.hydrated)
- return [];
- var view = this._preBuiltObjects.view;
- var nestedView = view.getNestedView(view.elementOffset + this.getBoundElementIndex());
- return lang_1.isPresent(nestedView) ? nestedView.rootElementInjectors : [];
- };
- ElementInjector.prototype.ngAfterViewChecked = function () { this._queryStrategy.updateViewQueries(); };
- ElementInjector.prototype.ngAfterContentChecked = function () { this._queryStrategy.updateContentQueries(); };
- ElementInjector.prototype.traverseAndSetQueriesAsDirty = function () {
- var inj = this;
- while (lang_1.isPresent(inj)) {
- inj._setQueriesAsDirty();
- inj = inj.parent;
- }
- };
- ElementInjector.prototype._setQueriesAsDirty = function () {
- this._queryStrategy.setContentQueriesAsDirty();
- if (lang_1.isPresent(this._host))
- this._host._queryStrategy.setViewQueriesAsDirty();
- };
- return ElementInjector;
- })(TreeNode);
- exports.ElementInjector = ElementInjector;
- var _EmptyQueryStrategy = (function () {
- function _EmptyQueryStrategy() {
- }
- _EmptyQueryStrategy.prototype.setContentQueriesAsDirty = function () { };
- _EmptyQueryStrategy.prototype.setViewQueriesAsDirty = function () { };
- _EmptyQueryStrategy.prototype.hydrate = function () { };
- _EmptyQueryStrategy.prototype.dehydrate = function () { };
- _EmptyQueryStrategy.prototype.updateContentQueries = function () { };
- _EmptyQueryStrategy.prototype.updateViewQueries = function () { };
- _EmptyQueryStrategy.prototype.findQuery = function (query) {
- throw new exceptions_1.BaseException("Cannot find query for directive " + query + ".");
- };
- return _EmptyQueryStrategy;
- })();
- var _emptyQueryStrategy = new _EmptyQueryStrategy();
- var InlineQueryStrategy = (function () {
- function InlineQueryStrategy(ei) {
- var protoRefs = ei._proto.protoQueryRefs;
- if (protoRefs.length > 0)
- this.query0 = new QueryRef(protoRefs[0], ei);
- if (protoRefs.length > 1)
- this.query1 = new QueryRef(protoRefs[1], ei);
- if (protoRefs.length > 2)
- this.query2 = new QueryRef(protoRefs[2], ei);
- }
- InlineQueryStrategy.prototype.setContentQueriesAsDirty = function () {
- if (lang_1.isPresent(this.query0) && !this.query0.isViewQuery)
- this.query0.dirty = true;
- if (lang_1.isPresent(this.query1) && !this.query1.isViewQuery)
- this.query1.dirty = true;
- if (lang_1.isPresent(this.query2) && !this.query2.isViewQuery)
- this.query2.dirty = true;
- };
- InlineQueryStrategy.prototype.setViewQueriesAsDirty = function () {
- if (lang_1.isPresent(this.query0) && this.query0.isViewQuery)
- this.query0.dirty = true;
- if (lang_1.isPresent(this.query1) && this.query1.isViewQuery)
- this.query1.dirty = true;
- if (lang_1.isPresent(this.query2) && this.query2.isViewQuery)
- this.query2.dirty = true;
- };
- InlineQueryStrategy.prototype.hydrate = function () {
- if (lang_1.isPresent(this.query0))
- this.query0.hydrate();
- if (lang_1.isPresent(this.query1))
- this.query1.hydrate();
- if (lang_1.isPresent(this.query2))
- this.query2.hydrate();
- };
- InlineQueryStrategy.prototype.dehydrate = function () {
- if (lang_1.isPresent(this.query0))
- this.query0.dehydrate();
- if (lang_1.isPresent(this.query1))
- this.query1.dehydrate();
- if (lang_1.isPresent(this.query2))
- this.query2.dehydrate();
- };
- InlineQueryStrategy.prototype.updateContentQueries = function () {
- if (lang_1.isPresent(this.query0) && !this.query0.isViewQuery) {
- this.query0.update();
- }
- if (lang_1.isPresent(this.query1) && !this.query1.isViewQuery) {
- this.query1.update();
- }
- if (lang_1.isPresent(this.query2) && !this.query2.isViewQuery) {
- this.query2.update();
- }
- };
- InlineQueryStrategy.prototype.updateViewQueries = function () {
- if (lang_1.isPresent(this.query0) && this.query0.isViewQuery) {
- this.query0.update();
- }
- if (lang_1.isPresent(this.query1) && this.query1.isViewQuery) {
- this.query1.update();
- }
- if (lang_1.isPresent(this.query2) && this.query2.isViewQuery) {
- this.query2.update();
- }
- };
- InlineQueryStrategy.prototype.findQuery = function (query) {
- if (lang_1.isPresent(this.query0) && this.query0.protoQueryRef.query === query) {
- return this.query0;
- }
- if (lang_1.isPresent(this.query1) && this.query1.protoQueryRef.query === query) {
- return this.query1;
- }
- if (lang_1.isPresent(this.query2) && this.query2.protoQueryRef.query === query) {
- return this.query2;
- }
- throw new exceptions_1.BaseException("Cannot find query for directive " + query + ".");
- };
- InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES = 3;
- return InlineQueryStrategy;
- })();
- var DynamicQueryStrategy = (function () {
- function DynamicQueryStrategy(ei) {
- this.queries = ei._proto.protoQueryRefs.map(function (p) { return new QueryRef(p, ei); });
- }
- DynamicQueryStrategy.prototype.setContentQueriesAsDirty = function () {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- if (!q.isViewQuery)
- q.dirty = true;
- }
- };
- DynamicQueryStrategy.prototype.setViewQueriesAsDirty = function () {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- if (q.isViewQuery)
- q.dirty = true;
- }
- };
- DynamicQueryStrategy.prototype.hydrate = function () {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- q.hydrate();
- }
- };
- DynamicQueryStrategy.prototype.dehydrate = function () {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- q.dehydrate();
- }
- };
- DynamicQueryStrategy.prototype.updateContentQueries = function () {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- if (!q.isViewQuery) {
- q.update();
- }
- }
- };
- DynamicQueryStrategy.prototype.updateViewQueries = function () {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- if (q.isViewQuery) {
- q.update();
- }
- }
- };
- DynamicQueryStrategy.prototype.findQuery = function (query) {
- for (var i = 0; i < this.queries.length; ++i) {
- var q = this.queries[i];
- if (q.protoQueryRef.query === query) {
- return q;
- }
- }
- throw new exceptions_1.BaseException("Cannot find query for directive " + query + ".");
- };
- return DynamicQueryStrategy;
- })();
- /**
- * Strategy used by the `ElementInjector` when the number of providers is 10 or less.
- * In such a case, inlining fields is beneficial for performances.
- */
- var ElementInjectorInlineStrategy = (function () {
- function ElementInjectorInlineStrategy(injectorStrategy, _ei) {
- this.injectorStrategy = injectorStrategy;
- this._ei = _ei;
- }
- ElementInjectorInlineStrategy.prototype.hydrate = function () {
- var i = this.injectorStrategy;
- var p = i.protoStrategy;
- i.resetConstructionCounter();
- if (p.provider0 instanceof DirectiveProvider && lang_1.isPresent(p.keyId0) && i.obj0 === injector_1.UNDEFINED)
- i.obj0 = i.instantiateProvider(p.provider0, p.visibility0);
- if (p.provider1 instanceof DirectiveProvider && lang_1.isPresent(p.keyId1) && i.obj1 === injector_1.UNDEFINED)
- i.obj1 = i.instantiateProvider(p.provider1, p.visibility1);
- if (p.provider2 instanceof DirectiveProvider && lang_1.isPresent(p.keyId2) && i.obj2 === injector_1.UNDEFINED)
- i.obj2 = i.instantiateProvider(p.provider2, p.visibility2);
- if (p.provider3 instanceof DirectiveProvider && lang_1.isPresent(p.keyId3) && i.obj3 === injector_1.UNDEFINED)
- i.obj3 = i.instantiateProvider(p.provider3, p.visibility3);
- if (p.provider4 instanceof DirectiveProvider && lang_1.isPresent(p.keyId4) && i.obj4 === injector_1.UNDEFINED)
- i.obj4 = i.instantiateProvider(p.provider4, p.visibility4);
- if (p.provider5 instanceof DirectiveProvider && lang_1.isPresent(p.keyId5) && i.obj5 === injector_1.UNDEFINED)
- i.obj5 = i.instantiateProvider(p.provider5, p.visibility5);
- if (p.provider6 instanceof DirectiveProvider && lang_1.isPresent(p.keyId6) && i.obj6 === injector_1.UNDEFINED)
- i.obj6 = i.instantiateProvider(p.provider6, p.visibility6);
- if (p.provider7 instanceof DirectiveProvider && lang_1.isPresent(p.keyId7) && i.obj7 === injector_1.UNDEFINED)
- i.obj7 = i.instantiateProvider(p.provider7, p.visibility7);
- if (p.provider8 instanceof DirectiveProvider && lang_1.isPresent(p.keyId8) && i.obj8 === injector_1.UNDEFINED)
- i.obj8 = i.instantiateProvider(p.provider8, p.visibility8);
- if (p.provider9 instanceof DirectiveProvider && lang_1.isPresent(p.keyId9) && i.obj9 === injector_1.UNDEFINED)
- i.obj9 = i.instantiateProvider(p.provider9, p.visibility9);
- };
- ElementInjectorInlineStrategy.prototype.dehydrate = function () {
- var i = this.injectorStrategy;
- i.obj0 = injector_1.UNDEFINED;
- i.obj1 = injector_1.UNDEFINED;
- i.obj2 = injector_1.UNDEFINED;
- i.obj3 = injector_1.UNDEFINED;
- i.obj4 = injector_1.UNDEFINED;
- i.obj5 = injector_1.UNDEFINED;
- i.obj6 = injector_1.UNDEFINED;
- i.obj7 = injector_1.UNDEFINED;
- i.obj8 = injector_1.UNDEFINED;
- i.obj9 = injector_1.UNDEFINED;
- };
- ElementInjectorInlineStrategy.prototype.callOnDestroy = function () {
- var i = this.injectorStrategy;
- var p = i.protoStrategy;
- if (p.provider0 instanceof DirectiveProvider &&
- p.provider0.callOnDestroy) {
- i.obj0.ngOnDestroy();
- }
- if (p.provider1 instanceof DirectiveProvider &&
- p.provider1.callOnDestroy) {
- i.obj1.ngOnDestroy();
- }
- if (p.provider2 instanceof DirectiveProvider &&
- p.provider2.callOnDestroy) {
- i.obj2.ngOnDestroy();
- }
- if (p.provider3 instanceof DirectiveProvider &&
- p.provider3.callOnDestroy) {
- i.obj3.ngOnDestroy();
- }
- if (p.provider4 instanceof DirectiveProvider &&
- p.provider4.callOnDestroy) {
- i.obj4.ngOnDestroy();
- }
- if (p.provider5 instanceof DirectiveProvider &&
- p.provider5.callOnDestroy) {
- i.obj5.ngOnDestroy();
- }
- if (p.provider6 instanceof DirectiveProvider &&
- p.provider6.callOnDestroy) {
- i.obj6.ngOnDestroy();
- }
- if (p.provider7 instanceof DirectiveProvider &&
- p.provider7.callOnDestroy) {
- i.obj7.ngOnDestroy();
- }
- if (p.provider8 instanceof DirectiveProvider &&
- p.provider8.callOnDestroy) {
- i.obj8.ngOnDestroy();
- }
- if (p.provider9 instanceof DirectiveProvider &&
- p.provider9.callOnDestroy) {
- i.obj9.ngOnDestroy();
- }
- };
- ElementInjectorInlineStrategy.prototype.getComponent = function () { return this.injectorStrategy.obj0; };
- ElementInjectorInlineStrategy.prototype.isComponentKey = function (key) {
- return this._ei._proto._firstProviderIsComponent && lang_1.isPresent(key) &&
- key.id === this.injectorStrategy.protoStrategy.keyId0;
- };
- ElementInjectorInlineStrategy.prototype.addDirectivesMatchingQuery = function (query, list) {
- var i = this.injectorStrategy;
- var p = i.protoStrategy;
- if (lang_1.isPresent(p.provider0) && p.provider0.key.token === query.selector) {
- if (i.obj0 === injector_1.UNDEFINED)
- i.obj0 = i.instantiateProvider(p.provider0, p.visibility0);
- list.push(i.obj0);
- }
- if (lang_1.isPresent(p.provider1) && p.provider1.key.token === query.selector) {
- if (i.obj1 === injector_1.UNDEFINED)
- i.obj1 = i.instantiateProvider(p.provider1, p.visibility1);
- list.push(i.obj1);
- }
- if (lang_1.isPresent(p.provider2) && p.provider2.key.token === query.selector) {
- if (i.obj2 === injector_1.UNDEFINED)
- i.obj2 = i.instantiateProvider(p.provider2, p.visibility2);
- list.push(i.obj2);
- }
- if (lang_1.isPresent(p.provider3) && p.provider3.key.token === query.selector) {
- if (i.obj3 === injector_1.UNDEFINED)
- i.obj3 = i.instantiateProvider(p.provider3, p.visibility3);
- list.push(i.obj3);
- }
- if (lang_1.isPresent(p.provider4) && p.provider4.key.token === query.selector) {
- if (i.obj4 === injector_1.UNDEFINED)
- i.obj4 = i.instantiateProvider(p.provider4, p.visibility4);
- list.push(i.obj4);
- }
- if (lang_1.isPresent(p.provider5) && p.provider5.key.token === query.selector) {
- if (i.obj5 === injector_1.UNDEFINED)
- i.obj5 = i.instantiateProvider(p.provider5, p.visibility5);
- list.push(i.obj5);
- }
- if (lang_1.isPresent(p.provider6) && p.provider6.key.token === query.selector) {
- if (i.obj6 === injector_1.UNDEFINED)
- i.obj6 = i.instantiateProvider(p.provider6, p.visibility6);
- list.push(i.obj6);
- }
- if (lang_1.isPresent(p.provider7) && p.provider7.key.token === query.selector) {
- if (i.obj7 === injector_1.UNDEFINED)
- i.obj7 = i.instantiateProvider(p.provider7, p.visibility7);
- list.push(i.obj7);
- }
- if (lang_1.isPresent(p.provider8) && p.provider8.key.token === query.selector) {
- if (i.obj8 === injector_1.UNDEFINED)
- i.obj8 = i.instantiateProvider(p.provider8, p.visibility8);
- list.push(i.obj8);
- }
- if (lang_1.isPresent(p.provider9) && p.provider9.key.token === query.selector) {
- if (i.obj9 === injector_1.UNDEFINED)
- i.obj9 = i.instantiateProvider(p.provider9, p.visibility9);
- list.push(i.obj9);
- }
- };
- return ElementInjectorInlineStrategy;
- })();
- /**
- * Strategy used by the `ElementInjector` when the number of bindings is 11 or more.
- * In such a case, there are too many fields to inline (see ElementInjectorInlineStrategy).
- */
- var ElementInjectorDynamicStrategy = (function () {
- function ElementInjectorDynamicStrategy(injectorStrategy, _ei) {
- this.injectorStrategy = injectorStrategy;
- this._ei = _ei;
- }
- ElementInjectorDynamicStrategy.prototype.hydrate = function () {
- var inj = this.injectorStrategy;
- var p = inj.protoStrategy;
- inj.resetConstructionCounter();
- for (var i = 0; i < p.keyIds.length; i++) {
- if (p.providers[i] instanceof DirectiveProvider && lang_1.isPresent(p.keyIds[i]) &&
- inj.objs[i] === injector_1.UNDEFINED) {
- inj.objs[i] = inj.instantiateProvider(p.providers[i], p.visibilities[i]);
- }
- }
- };
- ElementInjectorDynamicStrategy.prototype.dehydrate = function () {
- var inj = this.injectorStrategy;
- collection_1.ListWrapper.fill(inj.objs, injector_1.UNDEFINED);
- };
- ElementInjectorDynamicStrategy.prototype.callOnDestroy = function () {
- var ist = this.injectorStrategy;
- var p = ist.protoStrategy;
- for (var i = 0; i < p.providers.length; i++) {
- if (p.providers[i] instanceof DirectiveProvider &&
- p.providers[i].callOnDestroy) {
- ist.objs[i].ngOnDestroy();
- }
- }
- };
- ElementInjectorDynamicStrategy.prototype.getComponent = function () { return this.injectorStrategy.objs[0]; };
- ElementInjectorDynamicStrategy.prototype.isComponentKey = function (key) {
- var p = this.injectorStrategy.protoStrategy;
- return this._ei._proto._firstProviderIsComponent && lang_1.isPresent(key) && key.id === p.keyIds[0];
- };
- ElementInjectorDynamicStrategy.prototype.addDirectivesMatchingQuery = function (query, list) {
- var ist = this.injectorStrategy;
- var p = ist.protoStrategy;
- for (var i = 0; i < p.providers.length; i++) {
- if (p.providers[i].key.token === query.selector) {
- if (ist.objs[i] === injector_1.UNDEFINED) {
- ist.objs[i] = ist.instantiateProvider(p.providers[i], p.visibilities[i]);
- }
- list.push(ist.objs[i]);
- }
- }
- };
- return ElementInjectorDynamicStrategy;
- })();
- var ProtoQueryRef = (function () {
- function ProtoQueryRef(dirIndex, setter, query) {
- this.dirIndex = dirIndex;
- this.setter = setter;
- this.query = query;
- }
- Object.defineProperty(ProtoQueryRef.prototype, "usesPropertySyntax", {
- get: function () { return lang_1.isPresent(this.setter); },
- enumerable: true,
- configurable: true
- });
- return ProtoQueryRef;
- })();
- exports.ProtoQueryRef = ProtoQueryRef;
- var QueryRef = (function () {
- function QueryRef(protoQueryRef, originator) {
- this.protoQueryRef = protoQueryRef;
- this.originator = originator;
- }
- Object.defineProperty(QueryRef.prototype, "isViewQuery", {
- get: function () { return this.protoQueryRef.query.isViewQuery; },
- enumerable: true,
- configurable: true
- });
- QueryRef.prototype.update = function () {
- if (!this.dirty)
- return;
- this._update();
- this.dirty = false;
- // TODO delete the check once only field queries are supported
- if (this.protoQueryRef.usesPropertySyntax) {
- var dir = this.originator.getDirectiveAtIndex(this.protoQueryRef.dirIndex);
- if (this.protoQueryRef.query.first) {
- this.protoQueryRef.setter(dir, this.list.length > 0 ? this.list.first : null);
- }
- else {
- this.protoQueryRef.setter(dir, this.list);
- }
- }
- this.list.notifyOnChanges();
- };
- QueryRef.prototype._update = function () {
- var aggregator = [];
- if (this.protoQueryRef.query.isViewQuery) {
- var view = this.originator.getView();
- // intentionally skipping originator for view queries.
- var nestedView = view.getNestedView(view.elementOffset + this.originator.getBoundElementIndex());
- if (lang_1.isPresent(nestedView))
- this._visitView(nestedView, aggregator);
- }
- else {
- this._visit(this.originator, aggregator);
- }
- this.list.reset(aggregator);
- };
- ;
- QueryRef.prototype._visit = function (inj, aggregator) {
- var view = inj.getView();
- var startIdx = view.elementOffset + inj._proto.index;
- for (var i = startIdx; i < view.elementOffset + view.ownBindersCount; i++) {
- var curInj = view.elementInjectors[i];
- if (lang_1.isBlank(curInj))
- continue;
- // The first injector after inj, that is outside the subtree rooted at
- // inj has to have a null parent or a parent that is an ancestor of inj.
- if (i > startIdx && (lang_1.isBlank(curInj) || lang_1.isBlank(curInj.parent) ||
- view.elementOffset + curInj.parent._proto.index < startIdx)) {
- break;
- }
- if (!this.protoQueryRef.query.descendants &&
- !(curInj.parent == this.originator || curInj == this.originator))
- continue;
- // We visit the view container(VC) views right after the injector that contains
- // the VC. Theoretically, that might not be the right order if there are
- // child injectors of said injector. Not clear whether if such case can
- // even be constructed with the current apis.
- this._visitInjector(curInj, aggregator);
- var vc = view.viewContainers[i];
- if (lang_1.isPresent(vc))
- this._visitViewContainer(vc, aggregator);
- }
- };
- QueryRef.prototype._visitInjector = function (inj, aggregator) {
- if (this.protoQueryRef.query.isVarBindingQuery) {
- this._aggregateVariableBinding(inj, aggregator);
- }
- else {
- this._aggregateDirective(inj, aggregator);
- }
- };
- QueryRef.prototype._visitViewContainer = function (vc, aggregator) {
- for (var j = 0; j < vc.views.length; j++) {
- this._visitView(vc.views[j], aggregator);
- }
- };
- QueryRef.prototype._visitView = function (view, aggregator) {
- for (var i = view.elementOffset; i < view.elementOffset + view.ownBindersCount; i++) {
- var inj = view.elementInjectors[i];
- if (lang_1.isBlank(inj))
- continue;
- this._visitInjector(inj, aggregator);
- var vc = view.viewContainers[i];
- if (lang_1.isPresent(vc))
- this._visitViewContainer(vc, aggregator);
- }
- };
- QueryRef.prototype._aggregateVariableBinding = function (inj, aggregator) {
- var vb = this.protoQueryRef.query.varBindings;
- for (var i = 0; i < vb.length; ++i) {
- if (inj.hasVariableBinding(vb[i])) {
- aggregator.push(inj.getVariableBinding(vb[i]));
- }
- }
- };
- QueryRef.prototype._aggregateDirective = function (inj, aggregator) {
- inj.addDirectivesMatchingQuery(this.protoQueryRef.query, aggregator);
- };
- QueryRef.prototype.dehydrate = function () { this.list = null; };
- QueryRef.prototype.hydrate = function () {
- this.list = new query_list_1.QueryList();
- this.dirty = true;
- };
- return QueryRef;
- })();
- exports.QueryRef = QueryRef;
- /***/ },
- /* 81 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var viewModule = __webpack_require__(76);
- var view_ref_1 = __webpack_require__(77);
- var api_1 = __webpack_require__(72);
- var view_manager_utils_1 = __webpack_require__(82);
- var view_pool_1 = __webpack_require__(85);
- var view_listener_1 = __webpack_require__(86);
- var profile_1 = __webpack_require__(45);
- var proto_view_factory_1 = __webpack_require__(71);
- /**
- * Service exposing low level API for creating, moving and destroying Views.
- *
- * Most applications should use higher-level abstractions like {@link DynamicComponentLoader} and
- * {@link ViewContainerRef} instead.
- */
- var AppViewManager = (function () {
- function AppViewManager() {
- }
- /**
- * Returns the {@link ElementRef} that makes up the specified Host View.
- */
- AppViewManager.prototype.getHostElement = function (hostViewRef) {
- var hostView = view_ref_1.internalView(hostViewRef);
- if (hostView.proto.type !== viewModule.ViewType.HOST) {
- throw new exceptions_1.BaseException('This operation is only allowed on host views');
- }
- return hostView.elementRefs[hostView.elementOffset];
- };
- return AppViewManager;
- })();
- exports.AppViewManager = AppViewManager;
- var AppViewManager_ = (function (_super) {
- __extends(AppViewManager_, _super);
- function AppViewManager_(_viewPool, _viewListener, _utils, _renderer, _protoViewFactory) {
- _super.call(this);
- this._viewPool = _viewPool;
- this._viewListener = _viewListener;
- this._utils = _utils;
- this._renderer = _renderer;
- /** @internal */
- this._createRootHostViewScope = profile_1.wtfCreateScope('AppViewManager#createRootHostView()');
- /** @internal */
- this._destroyRootHostViewScope = profile_1.wtfCreateScope('AppViewManager#destroyRootHostView()');
- /** @internal */
- this._createEmbeddedViewInContainerScope = profile_1.wtfCreateScope('AppViewManager#createEmbeddedViewInContainer()');
- /** @internal */
- this._createHostViewInContainerScope = profile_1.wtfCreateScope('AppViewManager#createHostViewInContainer()');
- /** @internal */
- this._destroyViewInContainerScope = profile_1.wtfCreateScope('AppViewMananger#destroyViewInContainer()');
- /** @internal */
- this._attachViewInContainerScope = profile_1.wtfCreateScope('AppViewMananger#attachViewInContainer()');
- /** @internal */
- this._detachViewInContainerScope = profile_1.wtfCreateScope('AppViewMananger#detachViewInContainer()');
- this._protoViewFactory = _protoViewFactory;
- }
- AppViewManager_.prototype.getViewContainer = function (location) {
- var hostView = view_ref_1.internalView(location.parentView);
- return hostView.elementInjectors[location.boundElementIndex]
- .getViewContainerRef();
- };
- AppViewManager_.prototype.getNamedElementInComponentView = function (hostLocation, variableName) {
- var hostView = view_ref_1.internalView(hostLocation.parentView);
- var boundElementIndex = hostLocation.boundElementIndex;
- var componentView = hostView.getNestedView(boundElementIndex);
- if (lang_1.isBlank(componentView)) {
- throw new exceptions_1.BaseException("There is no component directive at element " + boundElementIndex);
- }
- var binderIdx = componentView.proto.variableLocations.get(variableName);
- if (lang_1.isBlank(binderIdx)) {
- throw new exceptions_1.BaseException("Could not find variable " + variableName);
- }
- return componentView.elementRefs[componentView.elementOffset + binderIdx];
- };
- AppViewManager_.prototype.getComponent = function (hostLocation) {
- var hostView = view_ref_1.internalView(hostLocation.parentView);
- var boundElementIndex = hostLocation.boundElementIndex;
- return this._utils.getComponentInstance(hostView, boundElementIndex);
- };
- AppViewManager_.prototype.createRootHostView = function (hostProtoViewRef, overrideSelector, injector) {
- var s = this._createRootHostViewScope();
- var hostProtoView = view_ref_1.internalProtoView(hostProtoViewRef);
- this._protoViewFactory.initializeProtoViewIfNeeded(hostProtoView);
- var hostElementSelector = overrideSelector;
- if (lang_1.isBlank(hostElementSelector)) {
- hostElementSelector = hostProtoView.elementBinders[0].componentDirective.metadata.selector;
- }
- var renderViewWithFragments = this._renderer.createRootHostView(hostProtoView.render, hostProtoView.mergeInfo.embeddedViewCount + 1, hostElementSelector);
- var hostView = this._createMainView(hostProtoView, renderViewWithFragments);
- this._renderer.hydrateView(hostView.render);
- this._utils.hydrateRootHostView(hostView, injector);
- return profile_1.wtfLeave(s, hostView.ref);
- };
- AppViewManager_.prototype.destroyRootHostView = function (hostViewRef) {
- // Note: Don't put the hostView into the view pool
- // as it is depending on the element for which it was created.
- var s = this._destroyRootHostViewScope();
- var hostView = view_ref_1.internalView(hostViewRef);
- this._renderer.detachFragment(hostView.renderFragment);
- this._renderer.dehydrateView(hostView.render);
- this._viewDehydrateRecurse(hostView);
- this._viewListener.onViewDestroyed(hostView);
- this._renderer.destroyView(hostView.render);
- profile_1.wtfLeave(s);
- };
- AppViewManager_.prototype.createEmbeddedViewInContainer = function (viewContainerLocation, index, templateRef) {
- var s = this._createEmbeddedViewInContainerScope();
- var protoView = view_ref_1.internalProtoView(templateRef.protoViewRef);
- if (protoView.type !== viewModule.ViewType.EMBEDDED) {
- throw new exceptions_1.BaseException('This method can only be called with embedded ProtoViews!');
- }
- this._protoViewFactory.initializeProtoViewIfNeeded(protoView);
- return profile_1.wtfLeave(s, this._createViewInContainer(viewContainerLocation, index, protoView, templateRef.elementRef, null));
- };
- AppViewManager_.prototype.createHostViewInContainer = function (viewContainerLocation, index, protoViewRef, imperativelyCreatedInjector) {
- var s = this._createHostViewInContainerScope();
- var protoView = view_ref_1.internalProtoView(protoViewRef);
- if (protoView.type !== viewModule.ViewType.HOST) {
- throw new exceptions_1.BaseException('This method can only be called with host ProtoViews!');
- }
- this._protoViewFactory.initializeProtoViewIfNeeded(protoView);
- return profile_1.wtfLeave(s, this._createViewInContainer(viewContainerLocation, index, protoView, viewContainerLocation, imperativelyCreatedInjector));
- };
- /**
- *
- * See {@link AppViewManager#destroyViewInContainer}.
- * @internal
- */
- AppViewManager_.prototype._createViewInContainer = function (viewContainerLocation, index, protoView, context, imperativelyCreatedInjector) {
- var parentView = view_ref_1.internalView(viewContainerLocation.parentView);
- var boundElementIndex = viewContainerLocation.boundElementIndex;
- var contextView = view_ref_1.internalView(context.parentView);
- var contextBoundElementIndex = context.boundElementIndex;
- var embeddedFragmentView = contextView.getNestedView(contextBoundElementIndex);
- var view;
- if (protoView.type === viewModule.ViewType.EMBEDDED && lang_1.isPresent(embeddedFragmentView) &&
- !embeddedFragmentView.hydrated()) {
- // Case 1: instantiate the first view of a template that has been merged into a parent
- view = embeddedFragmentView;
- this._attachRenderView(parentView, boundElementIndex, index, view);
- }
- else {
- // Case 2: instantiate another copy of the template or a host ProtoView.
- // This is a separate case
- // as we only inline one copy of the template into the parent view.
- view = this._createPooledView(protoView);
- this._attachRenderView(parentView, boundElementIndex, index, view);
- this._renderer.hydrateView(view.render);
- }
- this._utils.attachViewInContainer(parentView, boundElementIndex, contextView, contextBoundElementIndex, index, view);
- try {
- this._utils.hydrateViewInContainer(parentView, boundElementIndex, contextView, contextBoundElementIndex, index, imperativelyCreatedInjector);
- }
- catch (e) {
- this._utils.detachViewInContainer(parentView, boundElementIndex, index);
- throw e;
- }
- return view.ref;
- };
- /** @internal */
- AppViewManager_.prototype._attachRenderView = function (parentView, boundElementIndex, index, view) {
- var elementRef = parentView.elementRefs[boundElementIndex];
- if (index === 0) {
- this._renderer.attachFragmentAfterElement(elementRef, view.renderFragment);
- }
- else {
- var prevView = parentView.viewContainers[boundElementIndex].views[index - 1];
- this._renderer.attachFragmentAfterFragment(prevView.renderFragment, view.renderFragment);
- }
- };
- AppViewManager_.prototype.destroyViewInContainer = function (viewContainerLocation, index) {
- var s = this._destroyViewInContainerScope();
- var parentView = view_ref_1.internalView(viewContainerLocation.parentView);
- var boundElementIndex = viewContainerLocation.boundElementIndex;
- this._destroyViewInContainer(parentView, boundElementIndex, index);
- profile_1.wtfLeave(s);
- };
- // TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer
- AppViewManager_.prototype.attachViewInContainer = function (viewContainerLocation, index, viewRef) {
- var s = this._attachViewInContainerScope();
- var view = view_ref_1.internalView(viewRef);
- var parentView = view_ref_1.internalView(viewContainerLocation.parentView);
- var boundElementIndex = viewContainerLocation.boundElementIndex;
- // TODO(tbosch): the public methods attachViewInContainer/detachViewInContainer
- // are used for moving elements without the same container.
- // We will change this into an atomic `move` operation, which should preserve the
- // previous parent injector (see https://github.com/angular/angular/issues/1377).
- // Right now we are destroying any special
- // context view that might have been used.
- this._utils.attachViewInContainer(parentView, boundElementIndex, null, null, index, view);
- this._attachRenderView(parentView, boundElementIndex, index, view);
- return profile_1.wtfLeave(s, viewRef);
- };
- // TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer
- AppViewManager_.prototype.detachViewInContainer = function (viewContainerLocation, index) {
- var s = this._detachViewInContainerScope();
- var parentView = view_ref_1.internalView(viewContainerLocation.parentView);
- var boundElementIndex = viewContainerLocation.boundElementIndex;
- var viewContainer = parentView.viewContainers[boundElementIndex];
- var view = viewContainer.views[index];
- this._utils.detachViewInContainer(parentView, boundElementIndex, index);
- this._renderer.detachFragment(view.renderFragment);
- return profile_1.wtfLeave(s, view.ref);
- };
- /** @internal */
- AppViewManager_.prototype._createMainView = function (protoView, renderViewWithFragments) {
- var mergedParentView = this._utils.createView(protoView, renderViewWithFragments, this, this._renderer);
- this._renderer.setEventDispatcher(mergedParentView.render, mergedParentView);
- this._viewListener.onViewCreated(mergedParentView);
- return mergedParentView;
- };
- /** @internal */
- AppViewManager_.prototype._createPooledView = function (protoView) {
- var view = this._viewPool.getView(protoView);
- if (lang_1.isBlank(view)) {
- view = this._createMainView(protoView, this._renderer.createView(protoView.render, protoView.mergeInfo.embeddedViewCount + 1));
- }
- return view;
- };
- /** @internal */
- AppViewManager_.prototype._destroyPooledView = function (view) {
- var wasReturned = this._viewPool.returnView(view);
- if (!wasReturned) {
- this._viewListener.onViewDestroyed(view);
- this._renderer.destroyView(view.render);
- }
- };
- /** @internal */
- AppViewManager_.prototype._destroyViewInContainer = function (parentView, boundElementIndex, index) {
- var viewContainer = parentView.viewContainers[boundElementIndex];
- var view = viewContainer.views[index];
- this._viewDehydrateRecurse(view);
- this._utils.detachViewInContainer(parentView, boundElementIndex, index);
- if (view.viewOffset > 0) {
- // Case 1: a view that is part of another view.
- // Just detach the fragment
- this._renderer.detachFragment(view.renderFragment);
- }
- else {
- // Case 2: a view that is not part of another view.
- // dehydrate and destroy it.
- this._renderer.dehydrateView(view.render);
- this._renderer.detachFragment(view.renderFragment);
- this._destroyPooledView(view);
- }
- };
- /** @internal */
- AppViewManager_.prototype._viewDehydrateRecurse = function (view) {
- if (view.hydrated()) {
- this._utils.dehydrateView(view);
- }
- var viewContainers = view.viewContainers;
- var startViewOffset = view.viewOffset;
- var endViewOffset = view.viewOffset + view.proto.mergeInfo.viewCount - 1;
- var elementOffset = view.elementOffset;
- for (var viewIdx = startViewOffset; viewIdx <= endViewOffset; viewIdx++) {
- var currView = view.views[viewIdx];
- for (var binderIdx = 0; binderIdx < currView.proto.elementBinders.length; binderIdx++, elementOffset++) {
- var vc = viewContainers[elementOffset];
- if (lang_1.isPresent(vc)) {
- for (var j = vc.views.length - 1; j >= 0; j--) {
- this._destroyViewInContainer(currView, elementOffset, j);
- }
- }
- }
- }
- };
- AppViewManager_ = __decorate([
- di_1.Injectable(),
- __param(4, di_1.Inject(di_1.forwardRef(function () { return proto_view_factory_1.ProtoViewFactory; }))),
- __metadata('design:paramtypes', [view_pool_1.AppViewPool, view_listener_1.AppViewListener, view_manager_utils_1.AppViewManagerUtils, api_1.Renderer, Object])
- ], AppViewManager_);
- return AppViewManager_;
- })(AppViewManager);
- exports.AppViewManager_ = AppViewManager_;
- /***/ },
- /* 82 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var collection_1 = __webpack_require__(12);
- var eli = __webpack_require__(80);
- var lang_1 = __webpack_require__(5);
- var viewModule = __webpack_require__(76);
- var element_ref_1 = __webpack_require__(83);
- var template_ref_1 = __webpack_require__(84);
- var pipes_1 = __webpack_require__(74);
- var AppViewManagerUtils = (function () {
- function AppViewManagerUtils() {
- }
- AppViewManagerUtils.prototype.getComponentInstance = function (parentView, boundElementIndex) {
- var eli = parentView.elementInjectors[boundElementIndex];
- return eli.getComponent();
- };
- AppViewManagerUtils.prototype.createView = function (mergedParentViewProto, renderViewWithFragments, viewManager, renderer) {
- var renderFragments = renderViewWithFragments.fragmentRefs;
- var renderView = renderViewWithFragments.viewRef;
- var elementCount = mergedParentViewProto.mergeInfo.elementCount;
- var viewCount = mergedParentViewProto.mergeInfo.viewCount;
- var elementRefs = collection_1.ListWrapper.createFixedSize(elementCount);
- var viewContainers = collection_1.ListWrapper.createFixedSize(elementCount);
- var preBuiltObjects = collection_1.ListWrapper.createFixedSize(elementCount);
- var elementInjectors = collection_1.ListWrapper.createFixedSize(elementCount);
- var views = collection_1.ListWrapper.createFixedSize(viewCount);
- var elementOffset = 0;
- var textOffset = 0;
- var fragmentIdx = 0;
- var containerElementIndicesByViewIndex = collection_1.ListWrapper.createFixedSize(viewCount);
- for (var viewOffset = 0; viewOffset < viewCount; viewOffset++) {
- var containerElementIndex = containerElementIndicesByViewIndex[viewOffset];
- var containerElementInjector = lang_1.isPresent(containerElementIndex) ? elementInjectors[containerElementIndex] : null;
- var parentView = lang_1.isPresent(containerElementInjector) ? preBuiltObjects[containerElementIndex].view : null;
- var protoView = lang_1.isPresent(containerElementIndex) ?
- parentView.proto.elementBinders[containerElementIndex - parentView.elementOffset]
- .nestedProtoView :
- mergedParentViewProto;
- var renderFragment = null;
- if (viewOffset === 0 || protoView.type === viewModule.ViewType.EMBEDDED) {
- renderFragment = renderFragments[fragmentIdx++];
- }
- var currentView = new viewModule.AppView(renderer, protoView, viewOffset, elementOffset, textOffset, protoView.protoLocals, renderView, renderFragment, containerElementInjector);
- views[viewOffset] = currentView;
- if (lang_1.isPresent(containerElementIndex)) {
- preBuiltObjects[containerElementIndex].nestedView = currentView;
- }
- var rootElementInjectors = [];
- var nestedViewOffset = viewOffset + 1;
- for (var binderIdx = 0; binderIdx < protoView.elementBinders.length; binderIdx++) {
- var binder = protoView.elementBinders[binderIdx];
- var boundElementIndex = elementOffset + binderIdx;
- var elementInjector = null;
- if (lang_1.isPresent(binder.nestedProtoView) && binder.nestedProtoView.isMergable) {
- containerElementIndicesByViewIndex[nestedViewOffset] = boundElementIndex;
- nestedViewOffset += binder.nestedProtoView.mergeInfo.viewCount;
- }
- // elementInjectors and rootElementInjectors
- var protoElementInjector = binder.protoElementInjector;
- if (lang_1.isPresent(protoElementInjector)) {
- if (lang_1.isPresent(protoElementInjector.parent)) {
- var parentElementInjector = elementInjectors[elementOffset + protoElementInjector.parent.index];
- elementInjector = protoElementInjector.instantiate(parentElementInjector);
- }
- else {
- elementInjector = protoElementInjector.instantiate(null);
- rootElementInjectors.push(elementInjector);
- }
- }
- elementInjectors[boundElementIndex] = elementInjector;
- // elementRefs
- var el = new element_ref_1.ElementRef_(currentView.ref, boundElementIndex, renderer);
- elementRefs[el.boundElementIndex] = el;
- // preBuiltObjects
- if (lang_1.isPresent(elementInjector)) {
- var templateRef = lang_1.isPresent(binder.nestedProtoView) &&
- binder.nestedProtoView.type === viewModule.ViewType.EMBEDDED ?
- new template_ref_1.TemplateRef_(el) :
- null;
- preBuiltObjects[boundElementIndex] =
- new eli.PreBuiltObjects(viewManager, currentView, el, templateRef);
- }
- }
- currentView.init(protoView.changeDetectorFactory(currentView), elementInjectors, rootElementInjectors, preBuiltObjects, views, elementRefs, viewContainers);
- if (lang_1.isPresent(parentView) && protoView.type === viewModule.ViewType.COMPONENT) {
- parentView.changeDetector.addViewChild(currentView.changeDetector);
- }
- elementOffset += protoView.elementBinders.length;
- textOffset += protoView.textBindingCount;
- }
- return views[0];
- };
- AppViewManagerUtils.prototype.hydrateRootHostView = function (hostView, injector) {
- this._hydrateView(hostView, injector, null, new Object(), null);
- };
- // Misnomer: this method is attaching next to the view container.
- AppViewManagerUtils.prototype.attachViewInContainer = function (parentView, boundElementIndex, contextView, contextBoundElementIndex, index, view) {
- if (lang_1.isBlank(contextView)) {
- contextView = parentView;
- contextBoundElementIndex = boundElementIndex;
- }
- parentView.changeDetector.addContentChild(view.changeDetector);
- var viewContainer = parentView.viewContainers[boundElementIndex];
- if (lang_1.isBlank(viewContainer)) {
- viewContainer = new viewModule.AppViewContainer();
- parentView.viewContainers[boundElementIndex] = viewContainer;
- }
- collection_1.ListWrapper.insert(viewContainer.views, index, view);
- var elementInjector = contextView.elementInjectors[contextBoundElementIndex];
- for (var i = view.rootElementInjectors.length - 1; i >= 0; i--) {
- if (lang_1.isPresent(elementInjector.parent)) {
- view.rootElementInjectors[i].link(elementInjector.parent);
- }
- }
- elementInjector.traverseAndSetQueriesAsDirty();
- };
- AppViewManagerUtils.prototype.detachViewInContainer = function (parentView, boundElementIndex, index) {
- var viewContainer = parentView.viewContainers[boundElementIndex];
- var view = viewContainer.views[index];
- parentView.elementInjectors[boundElementIndex].traverseAndSetQueriesAsDirty();
- view.changeDetector.remove();
- collection_1.ListWrapper.removeAt(viewContainer.views, index);
- for (var i = 0; i < view.rootElementInjectors.length; ++i) {
- var inj = view.rootElementInjectors[i];
- inj.unlink();
- }
- };
- AppViewManagerUtils.prototype.hydrateViewInContainer = function (parentView, boundElementIndex, contextView, contextBoundElementIndex, index, imperativelyCreatedProviders) {
- if (lang_1.isBlank(contextView)) {
- contextView = parentView;
- contextBoundElementIndex = boundElementIndex;
- }
- var viewContainer = parentView.viewContainers[boundElementIndex];
- var view = viewContainer.views[index];
- var elementInjector = contextView.elementInjectors[contextBoundElementIndex];
- var injector = lang_1.isPresent(imperativelyCreatedProviders) ?
- di_1.Injector.fromResolvedProviders(imperativelyCreatedProviders) :
- null;
- this._hydrateView(view, injector, elementInjector.getHost(), contextView.context, contextView.locals);
- };
- /** @internal */
- AppViewManagerUtils.prototype._hydrateView = function (initView, imperativelyCreatedInjector, hostElementInjector, context, parentLocals) {
- var viewIdx = initView.viewOffset;
- var endViewOffset = viewIdx + initView.proto.mergeInfo.viewCount - 1;
- while (viewIdx <= endViewOffset) {
- var currView = initView.views[viewIdx];
- var currProtoView = currView.proto;
- if (currView !== initView && currView.proto.type === viewModule.ViewType.EMBEDDED) {
- // Don't hydrate components of embedded fragment views.
- viewIdx += currView.proto.mergeInfo.viewCount;
- }
- else {
- if (currView !== initView) {
- // hydrate a nested component view
- imperativelyCreatedInjector = null;
- parentLocals = null;
- hostElementInjector = currView.containerElementInjector;
- context = hostElementInjector.getComponent();
- }
- currView.context = context;
- currView.locals.parent = parentLocals;
- var binders = currProtoView.elementBinders;
- for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) {
- var boundElementIndex = binderIdx + currView.elementOffset;
- var elementInjector = initView.elementInjectors[boundElementIndex];
- if (lang_1.isPresent(elementInjector)) {
- elementInjector.hydrate(imperativelyCreatedInjector, hostElementInjector, currView.preBuiltObjects[boundElementIndex]);
- this._populateViewLocals(currView, elementInjector, boundElementIndex);
- this._setUpEventEmitters(currView, elementInjector, boundElementIndex);
- }
- }
- var pipes = lang_1.isPresent(hostElementInjector) ?
- new pipes_1.Pipes(currView.proto.pipes, hostElementInjector.getInjector()) :
- null;
- currView.changeDetector.hydrate(currView.context, currView.locals, currView, pipes);
- viewIdx++;
- }
- }
- };
- /** @internal */
- AppViewManagerUtils.prototype._populateViewLocals = function (view, elementInjector, boundElementIdx) {
- if (lang_1.isPresent(elementInjector.getDirectiveVariableBindings())) {
- elementInjector.getDirectiveVariableBindings().forEach(function (directiveIndex, name) {
- if (lang_1.isBlank(directiveIndex)) {
- view.locals.set(name, view.elementRefs[boundElementIdx].nativeElement);
- }
- else {
- view.locals.set(name, elementInjector.getDirectiveAtIndex(directiveIndex));
- }
- });
- }
- };
- /** @internal */
- AppViewManagerUtils.prototype._setUpEventEmitters = function (view, elementInjector, boundElementIndex) {
- var emitters = elementInjector.getEventEmitterAccessors();
- for (var directiveIndex = 0; directiveIndex < emitters.length; ++directiveIndex) {
- var directiveEmitters = emitters[directiveIndex];
- var directive = elementInjector.getDirectiveAtIndex(directiveIndex);
- for (var eventIndex = 0; eventIndex < directiveEmitters.length; ++eventIndex) {
- var eventEmitterAccessor = directiveEmitters[eventIndex];
- eventEmitterAccessor.subscribe(view, boundElementIndex, directive);
- }
- }
- };
- AppViewManagerUtils.prototype.dehydrateView = function (initView) {
- var endViewOffset = initView.viewOffset + initView.proto.mergeInfo.viewCount - 1;
- for (var viewIdx = initView.viewOffset; viewIdx <= endViewOffset; viewIdx++) {
- var currView = initView.views[viewIdx];
- if (currView.hydrated()) {
- if (lang_1.isPresent(currView.locals)) {
- currView.locals.clearValues();
- }
- currView.context = null;
- currView.changeDetector.dehydrate();
- var binders = currView.proto.elementBinders;
- for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) {
- var eli = initView.elementInjectors[currView.elementOffset + binderIdx];
- if (lang_1.isPresent(eli)) {
- eli.dehydrate();
- }
- }
- }
- }
- };
- AppViewManagerUtils = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], AppViewManagerUtils);
- return AppViewManagerUtils;
- })();
- exports.AppViewManagerUtils = AppViewManagerUtils;
- /***/ },
- /* 83 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var exceptions_1 = __webpack_require__(14);
- /**
- * Represents a location in a View that has an injection, change-detection and render context
- * associated with it.
- *
- * An `ElementRef` is created for each element in the Template that contains a Directive, Component
- * or data-binding.
- *
- * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
- * element.
- */
- var ElementRef = (function () {
- function ElementRef() {
- }
- Object.defineProperty(ElementRef.prototype, "nativeElement", {
- /**
- * The underlying native element or `null` if direct access to native elements is not supported
- * (e.g. when the application runs in a web worker).
- *
- * <div class="callout is-critical">
- * <header>Use with caution</header>
- * <p>
- * Use this API as the last resort when direct access to DOM is needed. Use templating and
- * data-binding provided by Angular instead. Alternatively you take a look at {@link Renderer}
- * which provides API that can safely be used even when direct access to native elements is not
- * supported.
- * </p>
- * <p>
- * Relying on direct DOM access creates tight coupling between your application and rendering
- * layers which will make it impossible to separate the two and deploy your application into a
- * web worker.
- * </p>
- * </div>
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(ElementRef.prototype, "renderView", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- return ElementRef;
- })();
- exports.ElementRef = ElementRef;
- var ElementRef_ = (function (_super) {
- __extends(ElementRef_, _super);
- function ElementRef_(parentView,
- /**
- * Index of the element inside the {@link ViewRef}.
- *
- * This is used internally by the Angular framework to locate elements.
- */
- boundElementIndex, _renderer) {
- _super.call(this);
- this.parentView = parentView;
- this.boundElementIndex = boundElementIndex;
- this._renderer = _renderer;
- }
- Object.defineProperty(ElementRef_.prototype, "renderView", {
- get: function () { return this.parentView.render; },
- set: function (value) { exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ElementRef_.prototype, "nativeElement", {
- get: function () { return this._renderer.getNativeElementSync(this); },
- enumerable: true,
- configurable: true
- });
- return ElementRef_;
- })(ElementRef);
- exports.ElementRef_ = ElementRef_;
- /***/ },
- /* 84 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var view_ref_1 = __webpack_require__(77);
- /**
- * Represents an Embedded Template that can be used to instantiate Embedded Views.
- *
- * You can access a `TemplateRef`, in two ways. Via a directive placed on a `<template>` element (or
- * directive prefixed with `*`) and have the `TemplateRef` for this Embedded View injected into the
- * constructor of the directive using the `TemplateRef` Token. Alternatively you can query for the
- * `TemplateRef` from a Component or a Directive via {@link Query}.
- *
- * To instantiate Embedded Views based on a Template, use
- * {@link ViewContainerRef#createEmbeddedView}, which will create the View and attach it to the
- * View Container.
- */
- var TemplateRef = (function () {
- function TemplateRef() {
- }
- return TemplateRef;
- })();
- exports.TemplateRef = TemplateRef;
- var TemplateRef_ = (function (_super) {
- __extends(TemplateRef_, _super);
- function TemplateRef_(elementRef) {
- _super.call(this);
- this.elementRef = elementRef;
- }
- TemplateRef_.prototype._getProtoView = function () {
- var elementRef = this.elementRef;
- var parentView = view_ref_1.internalView(elementRef.parentView);
- return parentView.proto.elementBinders[elementRef.boundElementIndex - parentView.elementOffset]
- .nestedProtoView;
- };
- Object.defineProperty(TemplateRef_.prototype, "protoViewRef", {
- /**
- * Reference to the ProtoView used for creating Embedded Views that are based on the compiled
- * Embedded Template.
- */
- get: function () { return this._getProtoView().ref; },
- enumerable: true,
- configurable: true
- });
- TemplateRef_.prototype.hasLocal = function (name) {
- return this._getProtoView().templateVariableBindings.has(name);
- };
- return TemplateRef_;
- })(TemplateRef);
- exports.TemplateRef_ = TemplateRef_;
- /***/ },
- /* 85 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- exports.APP_VIEW_POOL_CAPACITY = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppViewPool.viewPoolCapacity'));
- var AppViewPool = (function () {
- function AppViewPool(poolCapacityPerProtoView) {
- /** @internal */
- this._pooledViewsPerProtoView = new collection_1.Map();
- this._poolCapacityPerProtoView = poolCapacityPerProtoView;
- }
- AppViewPool.prototype.getView = function (protoView) {
- var pooledViews = this._pooledViewsPerProtoView.get(protoView);
- if (lang_1.isPresent(pooledViews) && pooledViews.length > 0) {
- return pooledViews.pop();
- }
- return null;
- };
- AppViewPool.prototype.returnView = function (view) {
- var protoView = view.proto;
- var pooledViews = this._pooledViewsPerProtoView.get(protoView);
- if (lang_1.isBlank(pooledViews)) {
- pooledViews = [];
- this._pooledViewsPerProtoView.set(protoView, pooledViews);
- }
- var haveRemainingCapacity = pooledViews.length < this._poolCapacityPerProtoView;
- if (haveRemainingCapacity) {
- pooledViews.push(view);
- }
- return haveRemainingCapacity;
- };
- AppViewPool = __decorate([
- di_1.Injectable(),
- __param(0, di_1.Inject(exports.APP_VIEW_POOL_CAPACITY)),
- __metadata('design:paramtypes', [Object])
- ], AppViewPool);
- return AppViewPool;
- })();
- exports.AppViewPool = AppViewPool;
- /***/ },
- /* 86 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- /**
- * Listener for view creation / destruction.
- */
- var AppViewListener = (function () {
- function AppViewListener() {
- }
- AppViewListener.prototype.onViewCreated = function (view) { };
- AppViewListener.prototype.onViewDestroyed = function (view) { };
- AppViewListener = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], AppViewListener);
- return AppViewListener;
- })();
- exports.AppViewListener = AppViewListener;
- /***/ },
- /* 87 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var exceptions_1 = __webpack_require__(14);
- var lang_1 = __webpack_require__(5);
- var view_ref_1 = __webpack_require__(77);
- /**
- * Represents a container where one or more Views can be attached.
- *
- * The container can contain two kinds of Views. Host Views, created by instantiating a
- * {@link Component} via {@link #createHostView}, and Embedded Views, created by instantiating an
- * {@link TemplateRef Embedded Template} via {@link #createEmbeddedView}.
- *
- * The location of the View Container within the containing View is specified by the Anchor
- * `element`. Each View Container can have only one Anchor Element and each Anchor Element can only
- * have a single View Container.
- *
- * Root elements of Views attached to this container become siblings of the Anchor Element in
- * the Rendered View.
- *
- * To access a `ViewContainerRef` of an Element, you can either place a {@link Directive} injected
- * with `ViewContainerRef` on the Element, or you obtain it via
- * {@link AppViewManager#getViewContainer}.
- *
- * <!-- TODO(i): we are also considering ElementRef#viewContainer api -->
- */
- var ViewContainerRef = (function () {
- function ViewContainerRef() {
- }
- /**
- * Destroys all Views in this container.
- */
- ViewContainerRef.prototype.clear = function () {
- for (var i = this.length - 1; i >= 0; i--) {
- this.remove(i);
- }
- };
- Object.defineProperty(ViewContainerRef.prototype, "length", {
- /**
- * Returns the number of Views currently attached to this container.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- return ViewContainerRef;
- })();
- exports.ViewContainerRef = ViewContainerRef;
- var ViewContainerRef_ = (function (_super) {
- __extends(ViewContainerRef_, _super);
- function ViewContainerRef_(viewManager, element) {
- _super.call(this);
- this.viewManager = viewManager;
- this.element = element;
- }
- ViewContainerRef_.prototype._getViews = function () {
- var element = this.element;
- var vc = view_ref_1.internalView(element.parentView).viewContainers[element.boundElementIndex];
- return lang_1.isPresent(vc) ? vc.views : [];
- };
- ViewContainerRef_.prototype.get = function (index) { return this._getViews()[index].ref; };
- Object.defineProperty(ViewContainerRef_.prototype, "length", {
- get: function () { return this._getViews().length; },
- enumerable: true,
- configurable: true
- });
- // TODO(rado): profile and decide whether bounds checks should be added
- // to the methods below.
- ViewContainerRef_.prototype.createEmbeddedView = function (templateRef, index) {
- if (index === void 0) { index = -1; }
- if (index == -1)
- index = this.length;
- return this.viewManager.createEmbeddedViewInContainer(this.element, index, templateRef);
- };
- ViewContainerRef_.prototype.createHostView = function (protoViewRef, index, dynamicallyCreatedProviders) {
- if (protoViewRef === void 0) { protoViewRef = null; }
- if (index === void 0) { index = -1; }
- if (dynamicallyCreatedProviders === void 0) { dynamicallyCreatedProviders = null; }
- if (index == -1)
- index = this.length;
- return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef, dynamicallyCreatedProviders);
- };
- // TODO(i): refactor insert+remove into move
- ViewContainerRef_.prototype.insert = function (viewRef, index) {
- if (index === void 0) { index = -1; }
- if (index == -1)
- index = this.length;
- return this.viewManager.attachViewInContainer(this.element, index, viewRef);
- };
- ViewContainerRef_.prototype.indexOf = function (viewRef) {
- return collection_1.ListWrapper.indexOf(this._getViews(), view_ref_1.internalView(viewRef));
- };
- // TODO(i): rename to destroy
- ViewContainerRef_.prototype.remove = function (index) {
- if (index === void 0) { index = -1; }
- if (index == -1)
- index = this.length - 1;
- this.viewManager.destroyViewInContainer(this.element, index);
- // view is intentionally not returned to the client.
- };
- // TODO(i): refactor insert+remove into move
- ViewContainerRef_.prototype.detach = function (index) {
- if (index === void 0) { index = -1; }
- if (index == -1)
- index = this.length - 1;
- return this.viewManager.detachViewInContainer(this.element, index);
- };
- return ViewContainerRef_;
- })(ViewContainerRef);
- exports.ViewContainerRef_ = ViewContainerRef_;
- /***/ },
- /* 88 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var interfaces_1 = __webpack_require__(89);
- function hasLifecycleHook(lcInterface, token) {
- if (!(token instanceof lang_1.Type))
- return false;
- var proto = token.prototype;
- switch (lcInterface) {
- case interfaces_1.LifecycleHooks.AfterContentInit:
- return !!proto.ngAfterContentInit;
- case interfaces_1.LifecycleHooks.AfterContentChecked:
- return !!proto.ngAfterContentChecked;
- case interfaces_1.LifecycleHooks.AfterViewInit:
- return !!proto.ngAfterViewInit;
- case interfaces_1.LifecycleHooks.AfterViewChecked:
- return !!proto.ngAfterViewChecked;
- case interfaces_1.LifecycleHooks.OnChanges:
- return !!proto.ngOnChanges;
- case interfaces_1.LifecycleHooks.DoCheck:
- return !!proto.ngDoCheck;
- case interfaces_1.LifecycleHooks.OnDestroy:
- return !!proto.ngOnDestroy;
- case interfaces_1.LifecycleHooks.OnInit:
- return !!proto.ngOnInit;
- default:
- return false;
- }
- }
- exports.hasLifecycleHook = hasLifecycleHook;
- /***/ },
- /* 89 */
- /***/ function(module, exports) {
- (function (LifecycleHooks) {
- LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
- LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
- LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
- LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
- LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
- LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
- LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
- LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
- })(exports.LifecycleHooks || (exports.LifecycleHooks = {}));
- var LifecycleHooks = exports.LifecycleHooks;
- /**
- * @internal
- */
- exports.LIFECYCLE_HOOKS_VALUES = [
- LifecycleHooks.OnInit,
- LifecycleHooks.OnDestroy,
- LifecycleHooks.DoCheck,
- LifecycleHooks.OnChanges,
- LifecycleHooks.AfterContentInit,
- LifecycleHooks.AfterContentChecked,
- LifecycleHooks.AfterViewInit,
- LifecycleHooks.AfterViewChecked
- ];
- /***/ },
- /* 90 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- /**
- * An unmodifiable list of items that Angular keeps up to date when the state
- * of the application changes.
- *
- * The type of object that {@link QueryMetadata} and {@link ViewQueryMetadata} provide.
- *
- * Implements an iterable interface, therefore it can be used in both ES6
- * javascript `for (var i of items)` loops as well as in Angular templates with
- * `*ngFor="#i of myList"`.
- *
- * Changes can be observed by subscribing to the changes `Observable`.
- *
- * NOTE: In the future this class will implement an `Observable` interface.
- *
- * ### Example ([live demo](http://plnkr.co/edit/RX8sJnQYl9FWuSCWme5z?p=preview))
- * ```typescript
- * @Component({...})
- * class Container {
- * constructor(@Query(Item) items: QueryList<Item>) {
- * items.changes.subscribe(_ => console.log(items.length));
- * }
- * }
- * ```
- */
- var QueryList = (function () {
- function QueryList() {
- this._results = [];
- this._emitter = new async_1.EventEmitter();
- }
- Object.defineProperty(QueryList.prototype, "changes", {
- get: function () { return this._emitter; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(QueryList.prototype, "length", {
- get: function () { return this._results.length; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(QueryList.prototype, "first", {
- get: function () { return collection_1.ListWrapper.first(this._results); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(QueryList.prototype, "last", {
- get: function () { return collection_1.ListWrapper.last(this._results); },
- enumerable: true,
- configurable: true
- });
- /**
- * returns a new array with the passed in function applied to each element.
- */
- QueryList.prototype.map = function (fn) { return this._results.map(fn); };
- /**
- * returns a filtered array.
- */
- QueryList.prototype.filter = function (fn) { return this._results.filter(fn); };
- /**
- * returns a reduced value.
- */
- QueryList.prototype.reduce = function (fn, init) { return this._results.reduce(fn, init); };
- /**
- * converts QueryList into an array
- */
- QueryList.prototype.toArray = function () { return collection_1.ListWrapper.clone(this._results); };
- QueryList.prototype[lang_1.getSymbolIterator()] = function () { return this._results[lang_1.getSymbolIterator()](); };
- QueryList.prototype.toString = function () { return this._results.toString(); };
- /**
- * @internal
- */
- QueryList.prototype.reset = function (res) { this._results = res; };
- /** @internal */
- QueryList.prototype.notifyOnChanges = function () { this._emitter.emit(this); };
- return QueryList;
- })();
- exports.QueryList = QueryList;
- /***/ },
- /* 91 */
- /***/ function(module, exports) {
- exports.EVENT_TARGET_SEPARATOR = ':';
- var EventConfig = (function () {
- function EventConfig(fieldName, eventName, isLongForm) {
- this.fieldName = fieldName;
- this.eventName = eventName;
- this.isLongForm = isLongForm;
- }
- EventConfig.parse = function (eventConfig) {
- var fieldName = eventConfig, eventName = eventConfig, isLongForm = false;
- var separatorIdx = eventConfig.indexOf(exports.EVENT_TARGET_SEPARATOR);
- if (separatorIdx > -1) {
- // long format: 'fieldName: eventName'
- fieldName = eventConfig.substring(0, separatorIdx).trim();
- eventName = eventConfig.substring(separatorIdx + 1).trim();
- isLongForm = true;
- }
- return new EventConfig(fieldName, eventName, isLongForm);
- };
- EventConfig.prototype.getFullName = function () {
- return this.isLongForm ? "" + this.fieldName + exports.EVENT_TARGET_SEPARATOR + this.eventName :
- this.eventName;
- };
- return EventConfig;
- })();
- exports.EventConfig = EventConfig;
- /***/ },
- /* 92 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var metadata_1 = __webpack_require__(3);
- var reflection_1 = __webpack_require__(16);
- function _isDirectiveMetadata(type) {
- return type instanceof metadata_1.DirectiveMetadata;
- }
- /*
- * Resolve a `Type` for {@link DirectiveMetadata}.
- *
- * This interface can be overridden by the application developer to create custom behavior.
- *
- * See {@link Compiler}
- */
- var DirectiveResolver = (function () {
- function DirectiveResolver() {
- }
- /**
- * Return {@link DirectiveMetadata} for a given `Type`.
- */
- DirectiveResolver.prototype.resolve = function (type) {
- var typeMetadata = reflection_1.reflector.annotations(di_1.resolveForwardRef(type));
- if (lang_1.isPresent(typeMetadata)) {
- var metadata = typeMetadata.find(_isDirectiveMetadata);
- if (lang_1.isPresent(metadata)) {
- var propertyMetadata = reflection_1.reflector.propMetadata(type);
- return this._mergeWithPropertyMetadata(metadata, propertyMetadata);
- }
- }
- throw new exceptions_1.BaseException("No Directive annotation found on " + lang_1.stringify(type));
- };
- DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata) {
- var inputs = [];
- var outputs = [];
- var host = {};
- var queries = {};
- collection_1.StringMapWrapper.forEach(propertyMetadata, function (metadata, propName) {
- metadata.forEach(function (a) {
- if (a instanceof metadata_1.InputMetadata) {
- if (lang_1.isPresent(a.bindingPropertyName)) {
- inputs.push(propName + ": " + a.bindingPropertyName);
- }
- else {
- inputs.push(propName);
- }
- }
- if (a instanceof metadata_1.OutputMetadata) {
- if (lang_1.isPresent(a.bindingPropertyName)) {
- outputs.push(propName + ": " + a.bindingPropertyName);
- }
- else {
- outputs.push(propName);
- }
- }
- if (a instanceof metadata_1.HostBindingMetadata) {
- if (lang_1.isPresent(a.hostPropertyName)) {
- host[("[" + a.hostPropertyName + "]")] = propName;
- }
- else {
- host[("[" + propName + "]")] = propName;
- }
- }
- if (a instanceof metadata_1.HostListenerMetadata) {
- var args = lang_1.isPresent(a.args) ? a.args.join(', ') : '';
- host[("(" + a.eventName + ")")] = propName + "(" + args + ")";
- }
- if (a instanceof metadata_1.ContentChildrenMetadata) {
- queries[propName] = a;
- }
- if (a instanceof metadata_1.ViewChildrenMetadata) {
- queries[propName] = a;
- }
- if (a instanceof metadata_1.ContentChildMetadata) {
- queries[propName] = a;
- }
- if (a instanceof metadata_1.ViewChildMetadata) {
- queries[propName] = a;
- }
- });
- });
- return this._merge(dm, inputs, outputs, host, queries);
- };
- DirectiveResolver.prototype._merge = function (dm, inputs, outputs, host, queries) {
- var mergedInputs = lang_1.isPresent(dm.inputs) ? collection_1.ListWrapper.concat(dm.inputs, inputs) : inputs;
- var mergedOutputs = lang_1.isPresent(dm.outputs) ? collection_1.ListWrapper.concat(dm.outputs, outputs) : outputs;
- var mergedHost = lang_1.isPresent(dm.host) ? collection_1.StringMapWrapper.merge(dm.host, host) : host;
- var mergedQueries = lang_1.isPresent(dm.queries) ? collection_1.StringMapWrapper.merge(dm.queries, queries) : queries;
- if (dm instanceof metadata_1.ComponentMetadata) {
- return new metadata_1.ComponentMetadata({
- selector: dm.selector,
- inputs: mergedInputs,
- outputs: mergedOutputs,
- host: mergedHost,
- exportAs: dm.exportAs,
- moduleId: dm.moduleId,
- queries: mergedQueries,
- changeDetection: dm.changeDetection,
- providers: dm.providers,
- viewProviders: dm.viewProviders
- });
- }
- else {
- return new metadata_1.DirectiveMetadata({
- selector: dm.selector,
- inputs: mergedInputs,
- outputs: mergedOutputs,
- host: mergedHost,
- exportAs: dm.exportAs,
- queries: mergedQueries,
- providers: dm.providers
- });
- }
- };
- DirectiveResolver = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], DirectiveResolver);
- return DirectiveResolver;
- })();
- exports.DirectiveResolver = DirectiveResolver;
- /***/ },
- /* 93 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var view_1 = __webpack_require__(56);
- var directives_1 = __webpack_require__(23);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var reflection_1 = __webpack_require__(16);
- /**
- * Resolves types to {@link ViewMetadata}.
- */
- var ViewResolver = (function () {
- function ViewResolver() {
- /** @internal */
- this._cache = new collection_1.Map();
- }
- ViewResolver.prototype.resolve = function (component) {
- var view = this._cache.get(component);
- if (lang_1.isBlank(view)) {
- view = this._resolve(component);
- this._cache.set(component, view);
- }
- return view;
- };
- /** @internal */
- ViewResolver.prototype._resolve = function (component) {
- var compMeta;
- var viewMeta;
- reflection_1.reflector.annotations(component).forEach(function (m) {
- if (m instanceof view_1.ViewMetadata) {
- viewMeta = m;
- }
- if (m instanceof directives_1.ComponentMetadata) {
- compMeta = m;
- }
- });
- if (lang_1.isPresent(compMeta)) {
- if (lang_1.isBlank(compMeta.template) && lang_1.isBlank(compMeta.templateUrl) && lang_1.isBlank(viewMeta)) {
- throw new exceptions_1.BaseException("Component '" + lang_1.stringify(component) + "' must have either 'template', 'templateUrl', or '@View' set.");
- }
- else if (lang_1.isPresent(compMeta.template) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("template", component);
- }
- else if (lang_1.isPresent(compMeta.templateUrl) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("templateUrl", component);
- }
- else if (lang_1.isPresent(compMeta.directives) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("directives", component);
- }
- else if (lang_1.isPresent(compMeta.pipes) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("pipes", component);
- }
- else if (lang_1.isPresent(compMeta.encapsulation) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("encapsulation", component);
- }
- else if (lang_1.isPresent(compMeta.styles) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("styles", component);
- }
- else if (lang_1.isPresent(compMeta.styleUrls) && lang_1.isPresent(viewMeta)) {
- this._throwMixingViewAndComponent("styleUrls", component);
- }
- else if (lang_1.isPresent(viewMeta)) {
- return viewMeta;
- }
- else {
- return new view_1.ViewMetadata({
- templateUrl: compMeta.templateUrl,
- template: compMeta.template,
- directives: compMeta.directives,
- pipes: compMeta.pipes,
- encapsulation: compMeta.encapsulation,
- styles: compMeta.styles,
- styleUrls: compMeta.styleUrls
- });
- }
- }
- else {
- if (lang_1.isBlank(viewMeta)) {
- throw new exceptions_1.BaseException("No View decorator found on component '" + lang_1.stringify(component) + "'");
- }
- else {
- return viewMeta;
- }
- }
- return null;
- };
- /** @internal */
- ViewResolver.prototype._throwMixingViewAndComponent = function (propertyName, component) {
- throw new exceptions_1.BaseException("Component '" + lang_1.stringify(component) + "' cannot have both '" + propertyName + "' and '@View' set at the same time\"");
- };
- ViewResolver = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], ViewResolver);
- return ViewResolver;
- })();
- exports.ViewResolver = ViewResolver;
- /***/ },
- /* 94 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var metadata_1 = __webpack_require__(3);
- var reflection_1 = __webpack_require__(16);
- function _isPipeMetadata(type) {
- return type instanceof metadata_1.PipeMetadata;
- }
- /**
- * Resolve a `Type` for {@link PipeMetadata}.
- *
- * This interface can be overridden by the application developer to create custom behavior.
- *
- * See {@link Compiler}
- */
- var PipeResolver = (function () {
- function PipeResolver() {
- }
- /**
- * Return {@link PipeMetadata} for a given `Type`.
- */
- PipeResolver.prototype.resolve = function (type) {
- var metas = reflection_1.reflector.annotations(di_1.resolveForwardRef(type));
- if (lang_1.isPresent(metas)) {
- var annotation = metas.find(_isPipeMetadata);
- if (lang_1.isPresent(annotation)) {
- return annotation;
- }
- }
- throw new exceptions_1.BaseException("No Pipe decorator found on " + lang_1.stringify(type));
- };
- PipeResolver = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], PipeResolver);
- return PipeResolver;
- })();
- exports.PipeResolver = PipeResolver;
- /***/ },
- /* 95 */
- /***/ function(module, exports, __webpack_require__) {
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- /**
- * A token that can be provided when bootstraping an application to make an array of directives
- * available in every component of the application.
- *
- * ### Example
- *
- * ```typescript
- * import {PLATFORM_DIRECTIVES} from 'angular2/core';
- * import {OtherDirective} from './myDirectives';
- *
- * @Component({
- * selector: 'my-component',
- * template: `
- * <!-- can use other directive even though the component does not list it in `directives` -->
- * <other-directive></other-directive>
- * `
- * })
- * export class MyComponent {
- * ...
- * }
- *
- * bootstrap(MyComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [OtherDirective], multi:true})]);
- * ```
- */
- exports.PLATFORM_DIRECTIVES = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Directives"));
- /**
- * A token that can be provided when bootstraping an application to make an array of pipes
- * available in every component of the application.
- *
- * ### Example
- *
- * ```typescript
- * import {PLATFORM_PIPES} from 'angular2/core';
- * import {OtherPipe} from './myPipe';
- *
- * @Component({
- * selector: 'my-component',
- * template: `
- * {{123 | other-pipe}}
- * `
- * })
- * export class MyComponent {
- * ...
- * }
- *
- * bootstrap(MyComponent, [provide(PLATFORM_PIPES, {useValue: [OtherPipe], multi:true})]);
- * ```
- */
- exports.PLATFORM_PIPES = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Pipes"));
- /***/ },
- /* 96 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var api_1 = __webpack_require__(72);
- var metadata_1 = __webpack_require__(3);
- // Export ViewEncapsulation so that compiled templates only need to depend
- // on template_commands.
- var metadata_2 = __webpack_require__(3);
- exports.ViewEncapsulation = metadata_2.ViewEncapsulation;
- /**
- * A compiled host template.
- *
- * This is const as we are storing it as annotation
- * for the compiled component type.
- */
- var CompiledHostTemplate = (function () {
- function CompiledHostTemplate(template) {
- this.template = template;
- }
- CompiledHostTemplate = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [CompiledComponentTemplate])
- ], CompiledHostTemplate);
- return CompiledHostTemplate;
- })();
- exports.CompiledHostTemplate = CompiledHostTemplate;
- /**
- * A compiled template.
- */
- var CompiledComponentTemplate = (function () {
- function CompiledComponentTemplate(id, changeDetectorFactory, commands, styles) {
- this.id = id;
- this.changeDetectorFactory = changeDetectorFactory;
- this.commands = commands;
- this.styles = styles;
- }
- CompiledComponentTemplate = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String, Function, Array, Array])
- ], CompiledComponentTemplate);
- return CompiledComponentTemplate;
- })();
- exports.CompiledComponentTemplate = CompiledComponentTemplate;
- var EMPTY_ARR = lang_1.CONST_EXPR([]);
- var TextCmd = (function () {
- function TextCmd(value, isBound, ngContentIndex) {
- this.value = value;
- this.isBound = isBound;
- this.ngContentIndex = ngContentIndex;
- }
- TextCmd.prototype.visit = function (visitor, context) {
- return visitor.visitText(this, context);
- };
- TextCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String, Boolean, Number])
- ], TextCmd);
- return TextCmd;
- })();
- exports.TextCmd = TextCmd;
- var NgContentCmd = (function () {
- function NgContentCmd(index, ngContentIndex) {
- this.index = index;
- this.ngContentIndex = ngContentIndex;
- this.isBound = false;
- }
- NgContentCmd.prototype.visit = function (visitor, context) {
- return visitor.visitNgContent(this, context);
- };
- NgContentCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Number, Number])
- ], NgContentCmd);
- return NgContentCmd;
- })();
- exports.NgContentCmd = NgContentCmd;
- var IBeginElementCmd = (function (_super) {
- __extends(IBeginElementCmd, _super);
- function IBeginElementCmd() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(IBeginElementCmd.prototype, "variableNameAndValues", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(IBeginElementCmd.prototype, "eventTargetAndNames", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(IBeginElementCmd.prototype, "directives", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- return IBeginElementCmd;
- })(api_1.RenderBeginElementCmd);
- exports.IBeginElementCmd = IBeginElementCmd;
- var BeginElementCmd = (function () {
- function BeginElementCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, isBound, ngContentIndex) {
- this.name = name;
- this.attrNameAndValues = attrNameAndValues;
- this.eventTargetAndNames = eventTargetAndNames;
- this.variableNameAndValues = variableNameAndValues;
- this.directives = directives;
- this.isBound = isBound;
- this.ngContentIndex = ngContentIndex;
- }
- BeginElementCmd.prototype.visit = function (visitor, context) {
- return visitor.visitBeginElement(this, context);
- };
- BeginElementCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String, Array, Array, Array, Array, Boolean, Number])
- ], BeginElementCmd);
- return BeginElementCmd;
- })();
- exports.BeginElementCmd = BeginElementCmd;
- var EndElementCmd = (function () {
- function EndElementCmd() {
- }
- EndElementCmd.prototype.visit = function (visitor, context) {
- return visitor.visitEndElement(context);
- };
- EndElementCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], EndElementCmd);
- return EndElementCmd;
- })();
- exports.EndElementCmd = EndElementCmd;
- var BeginComponentCmd = (function () {
- function BeginComponentCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, encapsulation, ngContentIndex,
- // Note: the template needs to be stored as a function
- // so that we can resolve cycles
- templateGetter /*() => CompiledComponentTemplate*/) {
- this.name = name;
- this.attrNameAndValues = attrNameAndValues;
- this.eventTargetAndNames = eventTargetAndNames;
- this.variableNameAndValues = variableNameAndValues;
- this.directives = directives;
- this.encapsulation = encapsulation;
- this.ngContentIndex = ngContentIndex;
- this.templateGetter = templateGetter;
- this.isBound = true;
- }
- Object.defineProperty(BeginComponentCmd.prototype, "templateId", {
- get: function () { return this.templateGetter().id; },
- enumerable: true,
- configurable: true
- });
- BeginComponentCmd.prototype.visit = function (visitor, context) {
- return visitor.visitBeginComponent(this, context);
- };
- BeginComponentCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String, Array, Array, Array, Array, Number, Number, Function])
- ], BeginComponentCmd);
- return BeginComponentCmd;
- })();
- exports.BeginComponentCmd = BeginComponentCmd;
- var EndComponentCmd = (function () {
- function EndComponentCmd() {
- }
- EndComponentCmd.prototype.visit = function (visitor, context) {
- return visitor.visitEndComponent(context);
- };
- EndComponentCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [])
- ], EndComponentCmd);
- return EndComponentCmd;
- })();
- exports.EndComponentCmd = EndComponentCmd;
- var EmbeddedTemplateCmd = (function () {
- function EmbeddedTemplateCmd(attrNameAndValues, variableNameAndValues, directives, isMerged, ngContentIndex, changeDetectorFactory, children) {
- this.attrNameAndValues = attrNameAndValues;
- this.variableNameAndValues = variableNameAndValues;
- this.directives = directives;
- this.isMerged = isMerged;
- this.ngContentIndex = ngContentIndex;
- this.changeDetectorFactory = changeDetectorFactory;
- this.children = children;
- this.isBound = true;
- this.name = null;
- this.eventTargetAndNames = EMPTY_ARR;
- }
- EmbeddedTemplateCmd.prototype.visit = function (visitor, context) {
- return visitor.visitEmbeddedTemplate(this, context);
- };
- EmbeddedTemplateCmd = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Array, Array, Array, Boolean, Number, Function, Array])
- ], EmbeddedTemplateCmd);
- return EmbeddedTemplateCmd;
- })();
- exports.EmbeddedTemplateCmd = EmbeddedTemplateCmd;
- function visitAllCommands(visitor, cmds, context) {
- if (context === void 0) { context = null; }
- for (var i = 0; i < cmds.length; i++) {
- cmds[i].visit(visitor, context);
- }
- }
- exports.visitAllCommands = visitAllCommands;
- /***/ },
- /* 97 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var Console = (function () {
- function Console() {
- }
- Console.prototype.log = function (message) { lang_1.print(message); };
- Console = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], Console);
- return Console;
- })();
- exports.Console = Console;
- /***/ },
- /* 98 */
- /***/ function(module, exports, __webpack_require__) {
- // Public API for Zone
- var ng_zone_1 = __webpack_require__(66);
- exports.NgZone = ng_zone_1.NgZone;
- exports.NgZoneError = ng_zone_1.NgZoneError;
- /***/ },
- /* 99 */
- /***/ function(module, exports, __webpack_require__) {
- // Public API for render
- var api_1 = __webpack_require__(72);
- exports.Renderer = api_1.Renderer;
- exports.RenderViewRef = api_1.RenderViewRef;
- exports.RenderProtoViewRef = api_1.RenderProtoViewRef;
- exports.RenderFragmentRef = api_1.RenderFragmentRef;
- exports.RenderViewWithFragments = api_1.RenderViewWithFragments;
- exports.RenderTemplateCmd = api_1.RenderTemplateCmd;
- exports.RenderTextCmd = api_1.RenderTextCmd;
- exports.RenderNgContentCmd = api_1.RenderNgContentCmd;
- exports.RenderBeginElementCmd = api_1.RenderBeginElementCmd;
- exports.RenderBeginComponentCmd = api_1.RenderBeginComponentCmd;
- exports.RenderEmbeddedTemplateCmd = api_1.RenderEmbeddedTemplateCmd;
- exports.RenderBeginCmd = api_1.RenderBeginCmd;
- exports.RenderComponentTemplate = api_1.RenderComponentTemplate;
- /***/ },
- /* 100 */
- /***/ function(module, exports, __webpack_require__) {
- // Public API for compiler
- var directive_resolver_1 = __webpack_require__(92);
- exports.DirectiveResolver = directive_resolver_1.DirectiveResolver;
- var view_resolver_1 = __webpack_require__(93);
- exports.ViewResolver = view_resolver_1.ViewResolver;
- var compiler_1 = __webpack_require__(70);
- exports.Compiler = compiler_1.Compiler;
- var view_manager_1 = __webpack_require__(81);
- exports.AppViewManager = view_manager_1.AppViewManager;
- var query_list_1 = __webpack_require__(90);
- exports.QueryList = query_list_1.QueryList;
- var dynamic_component_loader_1 = __webpack_require__(69);
- exports.DynamicComponentLoader = dynamic_component_loader_1.DynamicComponentLoader;
- var element_ref_1 = __webpack_require__(83);
- exports.ElementRef = element_ref_1.ElementRef;
- var template_ref_1 = __webpack_require__(84);
- exports.TemplateRef = template_ref_1.TemplateRef;
- var view_ref_1 = __webpack_require__(77);
- exports.ViewRef = view_ref_1.ViewRef;
- exports.ProtoViewRef = view_ref_1.ProtoViewRef;
- var view_container_ref_1 = __webpack_require__(87);
- exports.ViewContainerRef = view_container_ref_1.ViewContainerRef;
- var dynamic_component_loader_2 = __webpack_require__(69);
- exports.ComponentRef = dynamic_component_loader_2.ComponentRef;
- /***/ },
- /* 101 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var view_1 = __webpack_require__(76);
- var view_ref_1 = __webpack_require__(77);
- /**
- * A DebugElement contains information from the Angular compiler about an
- * element and provides access to the corresponding ElementInjector and
- * underlying DOM Element, as well as a way to query for children.
- *
- * A DebugElement can be obtained from a {@link ComponentFixture} or from an
- * {@link ElementRef} via {@link inspectElement}.
- */
- var DebugElement = (function () {
- function DebugElement() {
- }
- Object.defineProperty(DebugElement.prototype, "componentInstance", {
- /**
- * Return the instance of the component associated with this element, if any.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(DebugElement.prototype, "nativeElement", {
- /**
- * Return the native HTML element for this DebugElement.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(DebugElement.prototype, "elementRef", {
- /**
- * Return an Angular {@link ElementRef} for this element.
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(DebugElement.prototype, "children", {
- /**
- * Get child DebugElements from within the Light DOM.
- *
- * @return {DebugElement[]}
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- Object.defineProperty(DebugElement.prototype, "componentViewChildren", {
- /**
- * Get the root DebugElement children of a component. Returns an empty
- * list if the current DebugElement is not a component root.
- *
- * @return {DebugElement[]}
- */
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- ;
- /**
- * Return the first descendant TestElement matching the given predicate
- * and scope.
- *
- * @param {Function: boolean} predicate
- * @param {Scope} scope
- *
- * @return {DebugElement}
- */
- DebugElement.prototype.query = function (predicate, scope) {
- if (scope === void 0) { scope = Scope.all; }
- var results = this.queryAll(predicate, scope);
- return results.length > 0 ? results[0] : null;
- };
- /**
- * Return descendant TestElememts matching the given predicate
- * and scope.
- *
- * @param {Function: boolean} predicate
- * @param {Scope} scope
- *
- * @return {DebugElement[]}
- */
- DebugElement.prototype.queryAll = function (predicate, scope) {
- if (scope === void 0) { scope = Scope.all; }
- var elementsInScope = scope(this);
- return elementsInScope.filter(predicate);
- };
- return DebugElement;
- })();
- exports.DebugElement = DebugElement;
- var DebugElement_ = (function (_super) {
- __extends(DebugElement_, _super);
- function DebugElement_(_parentView, _boundElementIndex) {
- _super.call(this);
- this._parentView = _parentView;
- this._boundElementIndex = _boundElementIndex;
- this._elementInjector = this._parentView.elementInjectors[this._boundElementIndex];
- }
- Object.defineProperty(DebugElement_.prototype, "componentInstance", {
- get: function () {
- if (!lang_1.isPresent(this._elementInjector)) {
- return null;
- }
- return this._elementInjector.getComponent();
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DebugElement_.prototype, "nativeElement", {
- get: function () { return this.elementRef.nativeElement; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DebugElement_.prototype, "elementRef", {
- get: function () { return this._parentView.elementRefs[this._boundElementIndex]; },
- enumerable: true,
- configurable: true
- });
- DebugElement_.prototype.getDirectiveInstance = function (directiveIndex) {
- return this._elementInjector.getDirectiveAtIndex(directiveIndex);
- };
- Object.defineProperty(DebugElement_.prototype, "children", {
- get: function () {
- return this._getChildElements(this._parentView, this._boundElementIndex);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(DebugElement_.prototype, "componentViewChildren", {
- get: function () {
- var shadowView = this._parentView.getNestedView(this._boundElementIndex);
- if (!lang_1.isPresent(shadowView) || shadowView.proto.type !== view_1.ViewType.COMPONENT) {
- // The current element is not a component.
- return [];
- }
- return this._getChildElements(shadowView, null);
- },
- enumerable: true,
- configurable: true
- });
- DebugElement_.prototype.triggerEventHandler = function (eventName, eventObj) {
- this._parentView.triggerEventHandlers(eventName, eventObj, this._boundElementIndex);
- };
- DebugElement_.prototype.hasDirective = function (type) {
- if (!lang_1.isPresent(this._elementInjector)) {
- return false;
- }
- return this._elementInjector.hasDirective(type);
- };
- DebugElement_.prototype.inject = function (type) {
- if (!lang_1.isPresent(this._elementInjector)) {
- return null;
- }
- return this._elementInjector.get(type);
- };
- DebugElement_.prototype.getLocal = function (name) { return this._parentView.locals.get(name); };
- /** @internal */
- DebugElement_.prototype._getChildElements = function (view, parentBoundElementIndex) {
- var _this = this;
- var els = [];
- var parentElementBinder = null;
- if (lang_1.isPresent(parentBoundElementIndex)) {
- parentElementBinder = view.proto.elementBinders[parentBoundElementIndex - view.elementOffset];
- }
- for (var i = 0; i < view.proto.elementBinders.length; ++i) {
- var binder = view.proto.elementBinders[i];
- if (binder.parent == parentElementBinder) {
- els.push(new DebugElement_(view, view.elementOffset + i));
- var views = view.viewContainers[view.elementOffset + i];
- if (lang_1.isPresent(views)) {
- views.views.forEach(function (nextView) { els = els.concat(_this._getChildElements(nextView, null)); });
- }
- }
- }
- return els;
- };
- return DebugElement_;
- })(DebugElement);
- exports.DebugElement_ = DebugElement_;
- /**
- * Returns a {@link DebugElement} for an {@link ElementRef}.
- *
- * @param {ElementRef}: elementRef
- * @return {DebugElement}
- */
- function inspectElement(elementRef) {
- return new DebugElement_(view_ref_1.internalView(elementRef.parentView), elementRef.boundElementIndex);
- }
- exports.inspectElement = inspectElement;
- /**
- * Maps an array of {@link DebugElement}s to an array of native DOM elements.
- */
- function asNativeElements(arr) {
- return arr.map(function (debugEl) { return debugEl.nativeElement; });
- }
- exports.asNativeElements = asNativeElements;
- /**
- * Set of scope functions used with {@link DebugElement}'s query functionality.
- */
- var Scope = (function () {
- function Scope() {
- }
- /**
- * Scope queries to both the light dom and view of an element and its
- * children.
- *
- * ## Example
- *
- * {@example core/debug/ts/debug_element/debug_element.ts region='scope_all'}
- */
- Scope.all = function (debugElement) {
- var scope = [];
- scope.push(debugElement);
- debugElement.children.forEach(function (child) { return scope = scope.concat(Scope.all(child)); });
- debugElement.componentViewChildren.forEach(function (child) { return scope = scope.concat(Scope.all(child)); });
- return scope;
- };
- /**
- * Scope queries to the light dom of an element and its children.
- *
- * ## Example
- *
- * {@example core/debug/ts/debug_element/debug_element.ts region='scope_light'}
- */
- Scope.light = function (debugElement) {
- var scope = [];
- debugElement.children.forEach(function (child) {
- scope.push(child);
- scope = scope.concat(Scope.light(child));
- });
- return scope;
- };
- /**
- * Scope queries to the view of an element of its children.
- *
- * ## Example
- *
- * {@example core/debug/ts/debug_element/debug_element.ts region='scope_view'}
- */
- Scope.view = function (debugElement) {
- var scope = [];
- debugElement.componentViewChildren.forEach(function (child) {
- scope.push(child);
- scope = scope.concat(Scope.light(child));
- });
- return scope;
- };
- return Scope;
- })();
- exports.Scope = Scope;
- /***/ },
- /* 102 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var di_1 = __webpack_require__(6);
- var console_1 = __webpack_require__(97);
- var reflection_1 = __webpack_require__(16);
- var testability_1 = __webpack_require__(68);
- function _reflector() {
- return reflection_1.reflector;
- }
- /**
- * A default set of providers which should be included in any Angular platform.
- */
- exports.PLATFORM_COMMON_PROVIDERS = lang_1.CONST_EXPR([new di_1.Provider(reflection_1.Reflector, { useFactory: _reflector, deps: [] }), testability_1.TestabilityRegistry, console_1.Console]);
- /***/ },
- /* 103 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var di_1 = __webpack_require__(6);
- var application_tokens_1 = __webpack_require__(67);
- var change_detection_1 = __webpack_require__(25);
- var view_pool_1 = __webpack_require__(85);
- var view_manager_1 = __webpack_require__(81);
- var view_manager_2 = __webpack_require__(81);
- var view_manager_utils_1 = __webpack_require__(82);
- var view_resolver_1 = __webpack_require__(93);
- var view_listener_1 = __webpack_require__(86);
- var proto_view_factory_1 = __webpack_require__(71);
- var directive_resolver_1 = __webpack_require__(92);
- var pipe_resolver_1 = __webpack_require__(94);
- var compiler_1 = __webpack_require__(70);
- var compiler_2 = __webpack_require__(70);
- var dynamic_component_loader_1 = __webpack_require__(69);
- var dynamic_component_loader_2 = __webpack_require__(69);
- /**
- * A default set of providers which should be included in any Angular
- * application, regardless of the platform it runs onto.
- */
- exports.APPLICATION_COMMON_PROVIDERS = lang_1.CONST_EXPR([
- new di_1.Provider(compiler_1.Compiler, { useClass: compiler_2.Compiler_ }),
- application_tokens_1.APP_ID_RANDOM_PROVIDER,
- view_pool_1.AppViewPool,
- new di_1.Provider(view_pool_1.APP_VIEW_POOL_CAPACITY, { useValue: 10000 }),
- new di_1.Provider(view_manager_1.AppViewManager, { useClass: view_manager_2.AppViewManager_ }),
- view_manager_utils_1.AppViewManagerUtils,
- view_listener_1.AppViewListener,
- proto_view_factory_1.ProtoViewFactory,
- view_resolver_1.ViewResolver,
- new di_1.Provider(change_detection_1.IterableDiffers, { useValue: change_detection_1.defaultIterableDiffers }),
- new di_1.Provider(change_detection_1.KeyValueDiffers, { useValue: change_detection_1.defaultKeyValueDiffers }),
- directive_resolver_1.DirectiveResolver,
- pipe_resolver_1.PipeResolver,
- new di_1.Provider(dynamic_component_loader_1.DynamicComponentLoader, { useClass: dynamic_component_loader_2.DynamicComponentLoader_ })
- ]);
- /***/ },
- /* 104 */
- /***/ function(module, exports, __webpack_require__) {
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- __export(__webpack_require__(105));
- __export(__webpack_require__(115));
- __export(__webpack_require__(123));
- __export(__webpack_require__(146));
- /***/ },
- /* 105 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * This module provides a set of common Pipes.
- */
- var async_pipe_1 = __webpack_require__(106);
- var uppercase_pipe_1 = __webpack_require__(108);
- var lowercase_pipe_1 = __webpack_require__(109);
- var json_pipe_1 = __webpack_require__(110);
- var slice_pipe_1 = __webpack_require__(111);
- var date_pipe_1 = __webpack_require__(112);
- var number_pipe_1 = __webpack_require__(114);
- var lang_1 = __webpack_require__(5);
- var async_pipe_2 = __webpack_require__(106);
- exports.AsyncPipe = async_pipe_2.AsyncPipe;
- var date_pipe_2 = __webpack_require__(112);
- exports.DatePipe = date_pipe_2.DatePipe;
- var json_pipe_2 = __webpack_require__(110);
- exports.JsonPipe = json_pipe_2.JsonPipe;
- var slice_pipe_2 = __webpack_require__(111);
- exports.SlicePipe = slice_pipe_2.SlicePipe;
- var lowercase_pipe_2 = __webpack_require__(109);
- exports.LowerCasePipe = lowercase_pipe_2.LowerCasePipe;
- var number_pipe_2 = __webpack_require__(114);
- exports.NumberPipe = number_pipe_2.NumberPipe;
- exports.DecimalPipe = number_pipe_2.DecimalPipe;
- exports.PercentPipe = number_pipe_2.PercentPipe;
- exports.CurrencyPipe = number_pipe_2.CurrencyPipe;
- var uppercase_pipe_2 = __webpack_require__(108);
- exports.UpperCasePipe = uppercase_pipe_2.UpperCasePipe;
- /**
- * A collection of Angular core pipes that are likely to be used in each and every
- * application.
- *
- * This collection can be used to quickly enumerate all the built-in pipes in the `pipes`
- * property of the `@Component` or `@View` decorators.
- */
- exports.COMMON_PIPES = lang_1.CONST_EXPR([
- async_pipe_1.AsyncPipe,
- uppercase_pipe_1.UpperCasePipe,
- lowercase_pipe_1.LowerCasePipe,
- json_pipe_1.JsonPipe,
- slice_pipe_1.SlicePipe,
- number_pipe_1.DecimalPipe,
- number_pipe_1.PercentPipe,
- number_pipe_1.CurrencyPipe,
- date_pipe_1.DatePipe
- ]);
- /***/ },
- /* 106 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- var core_1 = __webpack_require__(2);
- var invalid_pipe_argument_exception_1 = __webpack_require__(107);
- var ObservableStrategy = (function () {
- function ObservableStrategy() {
- }
- ObservableStrategy.prototype.createSubscription = function (async, updateLatestValue) {
- return async_1.ObservableWrapper.subscribe(async, updateLatestValue, function (e) { throw e; });
- };
- ObservableStrategy.prototype.dispose = function (subscription) { async_1.ObservableWrapper.dispose(subscription); };
- ObservableStrategy.prototype.onDestroy = function (subscription) { async_1.ObservableWrapper.dispose(subscription); };
- return ObservableStrategy;
- })();
- var PromiseStrategy = (function () {
- function PromiseStrategy() {
- }
- PromiseStrategy.prototype.createSubscription = function (async, updateLatestValue) {
- return async.then(updateLatestValue);
- };
- PromiseStrategy.prototype.dispose = function (subscription) { };
- PromiseStrategy.prototype.onDestroy = function (subscription) { };
- return PromiseStrategy;
- })();
- var _promiseStrategy = new PromiseStrategy();
- var _observableStrategy = new ObservableStrategy();
- /**
- * The `async` pipe subscribes to an Observable or Promise and returns the latest value it has
- * emitted.
- * When a new value is emitted, the `async` pipe marks the component to be checked for changes.
- *
- * ### Example
- *
- * This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
- * promise.
- *
- * {@example core/pipes/ts/async_pipe/async_pipe_example.ts region='AsyncPipe'}
- *
- * It's also possible to use `async` with Observables. The example below binds the `time` Observable
- * to the view. Every 500ms, the `time` Observable updates the view with the current time.
- *
- * ```typescript
- * ```
- */
- var AsyncPipe = (function () {
- function AsyncPipe(_ref) {
- /** @internal */
- this._latestValue = null;
- /** @internal */
- this._latestReturnedValue = null;
- /** @internal */
- this._subscription = null;
- /** @internal */
- this._obj = null;
- this._strategy = null;
- this._ref = _ref;
- }
- AsyncPipe.prototype.ngOnDestroy = function () {
- if (lang_1.isPresent(this._subscription)) {
- this._dispose();
- }
- };
- AsyncPipe.prototype.transform = function (obj, args) {
- if (lang_1.isBlank(this._obj)) {
- if (lang_1.isPresent(obj)) {
- this._subscribe(obj);
- }
- return this._latestValue;
- }
- if (obj !== this._obj) {
- this._dispose();
- return this.transform(obj);
- }
- if (this._latestValue === this._latestReturnedValue) {
- return this._latestReturnedValue;
- }
- else {
- this._latestReturnedValue = this._latestValue;
- return core_1.WrappedValue.wrap(this._latestValue);
- }
- };
- /** @internal */
- AsyncPipe.prototype._subscribe = function (obj) {
- var _this = this;
- this._obj = obj;
- this._strategy = this._selectStrategy(obj);
- this._subscription =
- this._strategy.createSubscription(obj, function (value) { return _this._updateLatestValue(obj, value); });
- };
- /** @internal */
- AsyncPipe.prototype._selectStrategy = function (obj) {
- if (lang_1.isPromise(obj)) {
- return _promiseStrategy;
- }
- else if (async_1.ObservableWrapper.isObservable(obj)) {
- return _observableStrategy;
- }
- else {
- throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(AsyncPipe, obj);
- }
- };
- /** @internal */
- AsyncPipe.prototype._dispose = function () {
- this._strategy.dispose(this._subscription);
- this._latestValue = null;
- this._latestReturnedValue = null;
- this._subscription = null;
- this._obj = null;
- };
- /** @internal */
- AsyncPipe.prototype._updateLatestValue = function (async, value) {
- if (async === this._obj) {
- this._latestValue = value;
- this._ref.markForCheck();
- }
- };
- AsyncPipe = __decorate([
- core_1.Pipe({ name: 'async', pure: false }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [core_1.ChangeDetectorRef])
- ], AsyncPipe);
- return AsyncPipe;
- })();
- exports.AsyncPipe = AsyncPipe;
- /***/ },
- /* 107 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var InvalidPipeArgumentException = (function (_super) {
- __extends(InvalidPipeArgumentException, _super);
- function InvalidPipeArgumentException(type, value) {
- _super.call(this, "Invalid argument '" + value + "' for pipe '" + lang_1.stringify(type) + "'");
- }
- return InvalidPipeArgumentException;
- })(exceptions_1.BaseException);
- exports.InvalidPipeArgumentException = InvalidPipeArgumentException;
- /***/ },
- /* 108 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- var invalid_pipe_argument_exception_1 = __webpack_require__(107);
- /**
- * Implements uppercase transforms to text.
- *
- * ### Example
- *
- * {@example core/pipes/ts/lowerupper_pipe/lowerupper_pipe_example.ts region='LowerUpperPipe'}
- */
- var UpperCasePipe = (function () {
- function UpperCasePipe() {
- }
- UpperCasePipe.prototype.transform = function (value, args) {
- if (args === void 0) { args = null; }
- if (lang_1.isBlank(value))
- return value;
- if (!lang_1.isString(value)) {
- throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(UpperCasePipe, value);
- }
- return value.toUpperCase();
- };
- UpperCasePipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'uppercase' }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], UpperCasePipe);
- return UpperCasePipe;
- })();
- exports.UpperCasePipe = UpperCasePipe;
- /***/ },
- /* 109 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- var invalid_pipe_argument_exception_1 = __webpack_require__(107);
- /**
- * Transforms text to lowercase.
- *
- * ### Example
- *
- * {@example core/pipes/ts/lowerupper_pipe/lowerupper_pipe_example.ts region='LowerUpperPipe'}
- */
- var LowerCasePipe = (function () {
- function LowerCasePipe() {
- }
- LowerCasePipe.prototype.transform = function (value, args) {
- if (args === void 0) { args = null; }
- if (lang_1.isBlank(value))
- return value;
- if (!lang_1.isString(value)) {
- throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(LowerCasePipe, value);
- }
- return value.toLowerCase();
- };
- LowerCasePipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'lowercase' }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], LowerCasePipe);
- return LowerCasePipe;
- })();
- exports.LowerCasePipe = LowerCasePipe;
- /***/ },
- /* 110 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- /**
- * Transforms any input value using `JSON.stringify`. Useful for debugging.
- *
- * ### Example
- * {@example core/pipes/ts/json_pipe/json_pipe_example.ts region='JsonPipe'}
- */
- var JsonPipe = (function () {
- function JsonPipe() {
- }
- JsonPipe.prototype.transform = function (value, args) {
- if (args === void 0) { args = null; }
- return lang_1.Json.stringify(value);
- };
- JsonPipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'json', pure: false }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], JsonPipe);
- return JsonPipe;
- })();
- exports.JsonPipe = JsonPipe;
- /***/ },
- /* 111 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var core_1 = __webpack_require__(2);
- var invalid_pipe_argument_exception_1 = __webpack_require__(107);
- /**
- * Creates a new List or String containing only a subset (slice) of the
- * elements.
- *
- * The starting index of the subset to return is specified by the `start` parameter.
- *
- * The ending index of the subset to return is specified by the optional `end` parameter.
- *
- * ### Usage
- *
- * expression | slice:start[:end]
- *
- * All behavior is based on the expected behavior of the JavaScript API
- * Array.prototype.slice() and String.prototype.slice()
- *
- * Where the input expression is a [List] or [String], and `start` is:
- *
- * - **a positive integer**: return the item at _start_ index and all items after
- * in the list or string expression.
- * - **a negative integer**: return the item at _start_ index from the end and all items after
- * in the list or string expression.
- * - **`|start|` greater than the size of the expression**: return an empty list or string.
- * - **`|start|` negative greater than the size of the expression**: return entire list or
- * string expression.
- *
- * and where `end` is:
- *
- * - **omitted**: return all items until the end of the input
- * - **a positive integer**: return all items before _end_ index of the list or string
- * expression.
- * - **a negative integer**: return all items before _end_ index from the end of the list
- * or string expression.
- *
- * When operating on a [List], the returned list is always a copy even when all
- * the elements are being returned.
- *
- * ## List Example
- *
- * This `ngFor` example:
- *
- * {@example core/pipes/ts/slice_pipe/slice_pipe_example.ts region='SlicePipe_list'}
- *
- * produces the following:
- *
- * <li>b</li>
- * <li>c</li>
- *
- * ## String Examples
- *
- * {@example core/pipes/ts/slice_pipe/slice_pipe_example.ts region='SlicePipe_string'}
- */
- var SlicePipe = (function () {
- function SlicePipe() {
- }
- SlicePipe.prototype.transform = function (value, args) {
- if (args === void 0) { args = null; }
- if (lang_1.isBlank(args) || args.length == 0) {
- throw new exceptions_1.BaseException('Slice pipe requires one argument');
- }
- if (!this.supports(value)) {
- throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(SlicePipe, value);
- }
- if (lang_1.isBlank(value))
- return value;
- var start = args[0];
- var end = args.length > 1 ? args[1] : null;
- if (lang_1.isString(value)) {
- return lang_1.StringWrapper.slice(value, start, end);
- }
- return collection_1.ListWrapper.slice(value, start, end);
- };
- SlicePipe.prototype.supports = function (obj) { return lang_1.isString(obj) || lang_1.isArray(obj); };
- SlicePipe = __decorate([
- core_1.Pipe({ name: 'slice', pure: false }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], SlicePipe);
- return SlicePipe;
- })();
- exports.SlicePipe = SlicePipe;
- /***/ },
- /* 112 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var intl_1 = __webpack_require__(113);
- var core_1 = __webpack_require__(2);
- var collection_1 = __webpack_require__(12);
- var invalid_pipe_argument_exception_1 = __webpack_require__(107);
- // TODO: move to a global configurable location along with other i18n components.
- var defaultLocale = 'en-US';
- /**
- * Formats a date value to a string based on the requested format.
- *
- * WARNINGS:
- * - this pipe is marked as pure hence it will not be re-evaluated when the input is mutated.
- * Instead users should treat the date as an immutable object and change the reference when the
- * pipe needs to re-run (this is to avoid reformatting the date on every change detection run
- * which would be an expensive operation).
- * - this pipe uses the Internationalization API. Therefore it is only reliable in Chrome and Opera
- * browsers.
- *
- * ## Usage
- *
- * expression | date[:format]
- *
- * where `expression` is a date object or a number (milliseconds since UTC epoch) and
- * `format` indicates which date/time components to include:
- *
- * | Component | Symbol | Short Form | Long Form | Numeric | 2-digit |
- * |-----------|:------:|--------------|-------------------|-----------|-----------|
- * | era | G | G (AD) | GGGG (Anno Domini)| - | - |
- * | year | y | - | - | y (2015) | yy (15) |
- * | month | M | MMM (Sep) | MMMM (September) | M (9) | MM (09) |
- * | day | d | - | - | d (3) | dd (03) |
- * | weekday | E | EEE (Sun) | EEEE (Sunday) | - | - |
- * | hour | j | - | - | j (13) | jj (13) |
- * | hour12 | h | - | - | h (1 PM) | hh (01 PM)|
- * | hour24 | H | - | - | H (13) | HH (13) |
- * | minute | m | - | - | m (5) | mm (05) |
- * | second | s | - | - | s (9) | ss (09) |
- * | timezone | z | - | z (Pacific Standard Time)| - | - |
- * | timezone | Z | Z (GMT-8:00) | - | - | - |
- *
- * In javascript, only the components specified will be respected (not the ordering,
- * punctuations, ...) and details of the formatting will be dependent on the locale.
- * On the other hand in Dart version, you can also include quoted text as well as some extra
- * date/time components such as quarter. For more information see:
- * https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/intl/intl.DateFormat.
- *
- * `format` can also be one of the following predefined formats:
- *
- * - `'medium'`: equivalent to `'yMMMdjms'` (e.g. Sep 3, 2010, 12:05:08 PM for en-US)
- * - `'short'`: equivalent to `'yMdjm'` (e.g. 9/3/2010, 12:05 PM for en-US)
- * - `'fullDate'`: equivalent to `'yMMMMEEEEd'` (e.g. Friday, September 3, 2010 for en-US)
- * - `'longDate'`: equivalent to `'yMMMMd'` (e.g. September 3, 2010)
- * - `'mediumDate'`: equivalent to `'yMMMd'` (e.g. Sep 3, 2010 for en-US)
- * - `'shortDate'`: equivalent to `'yMd'` (e.g. 9/3/2010 for en-US)
- * - `'mediumTime'`: equivalent to `'jms'` (e.g. 12:05:08 PM for en-US)
- * - `'shortTime'`: equivalent to `'jm'` (e.g. 12:05 PM for en-US)
- *
- * Timezone of the formatted text will be the local system timezone of the end-users machine.
- *
- * ### Examples
- *
- * Assuming `dateObj` is (year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11)
- * in the _local_ time and locale is 'en-US':
- *
- * ```
- * {{ dateObj | date }} // output is 'Jun 15, 2015'
- * {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
- * {{ dateObj | date:'shortTime' }} // output is '9:43 PM'
- * {{ dateObj | date:'mmss' }} // output is '43:11'
- * ```
- *
- * {@example core/pipes/ts/date_pipe/date_pipe_example.ts region='DatePipe'}
- */
- var DatePipe = (function () {
- function DatePipe() {
- }
- DatePipe.prototype.transform = function (value, args) {
- if (lang_1.isBlank(value))
- return null;
- if (!this.supports(value)) {
- throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(DatePipe, value);
- }
- var pattern = lang_1.isPresent(args) && args.length > 0 ? args[0] : 'mediumDate';
- if (lang_1.isNumber(value)) {
- value = lang_1.DateWrapper.fromMillis(value);
- }
- if (collection_1.StringMapWrapper.contains(DatePipe._ALIASES, pattern)) {
- pattern = collection_1.StringMapWrapper.get(DatePipe._ALIASES, pattern);
- }
- return intl_1.DateFormatter.format(value, defaultLocale, pattern);
- };
- DatePipe.prototype.supports = function (obj) { return lang_1.isDate(obj) || lang_1.isNumber(obj); };
- /** @internal */
- DatePipe._ALIASES = {
- 'medium': 'yMMMdjms',
- 'short': 'yMdjm',
- 'fullDate': 'yMMMMEEEEd',
- 'longDate': 'yMMMMd',
- 'mediumDate': 'yMMMd',
- 'shortDate': 'yMd',
- 'mediumTime': 'jms',
- 'shortTime': 'jm'
- };
- DatePipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'date', pure: true }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], DatePipe);
- return DatePipe;
- })();
- exports.DatePipe = DatePipe;
- /***/ },
- /* 113 */
- /***/ function(module, exports) {
- (function (NumberFormatStyle) {
- NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal";
- NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent";
- NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency";
- })(exports.NumberFormatStyle || (exports.NumberFormatStyle = {}));
- var NumberFormatStyle = exports.NumberFormatStyle;
- var NumberFormatter = (function () {
- function NumberFormatter() {
- }
- NumberFormatter.format = function (num, locale, style, _a) {
- var _b = _a === void 0 ? {} : _a, _c = _b.minimumIntegerDigits, minimumIntegerDigits = _c === void 0 ? 1 : _c, _d = _b.minimumFractionDigits, minimumFractionDigits = _d === void 0 ? 0 : _d, _e = _b.maximumFractionDigits, maximumFractionDigits = _e === void 0 ? 3 : _e, currency = _b.currency, _f = _b.currencyAsSymbol, currencyAsSymbol = _f === void 0 ? false : _f;
- var intlOptions = {
- minimumIntegerDigits: minimumIntegerDigits,
- minimumFractionDigits: minimumFractionDigits,
- maximumFractionDigits: maximumFractionDigits
- };
- intlOptions.style = NumberFormatStyle[style].toLowerCase();
- if (style == NumberFormatStyle.Currency) {
- intlOptions.currency = currency;
- intlOptions.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code';
- }
- return new Intl.NumberFormat(locale, intlOptions).format(num);
- };
- return NumberFormatter;
- })();
- exports.NumberFormatter = NumberFormatter;
- function digitCondition(len) {
- return len == 2 ? '2-digit' : 'numeric';
- }
- function nameCondition(len) {
- return len < 4 ? 'short' : 'long';
- }
- function extractComponents(pattern) {
- var ret = {};
- var i = 0, j;
- while (i < pattern.length) {
- j = i;
- while (j < pattern.length && pattern[j] == pattern[i])
- j++;
- var len = j - i;
- switch (pattern[i]) {
- case 'G':
- ret.era = nameCondition(len);
- break;
- case 'y':
- ret.year = digitCondition(len);
- break;
- case 'M':
- if (len >= 3)
- ret.month = nameCondition(len);
- else
- ret.month = digitCondition(len);
- break;
- case 'd':
- ret.day = digitCondition(len);
- break;
- case 'E':
- ret.weekday = nameCondition(len);
- break;
- case 'j':
- ret.hour = digitCondition(len);
- break;
- case 'h':
- ret.hour = digitCondition(len);
- ret.hour12 = true;
- break;
- case 'H':
- ret.hour = digitCondition(len);
- ret.hour12 = false;
- break;
- case 'm':
- ret.minute = digitCondition(len);
- break;
- case 's':
- ret.second = digitCondition(len);
- break;
- case 'z':
- ret.timeZoneName = 'long';
- break;
- case 'Z':
- ret.timeZoneName = 'short';
- break;
- }
- i = j;
- }
- return ret;
- }
- var dateFormatterCache = new Map();
- var DateFormatter = (function () {
- function DateFormatter() {
- }
- DateFormatter.format = function (date, locale, pattern) {
- var key = locale + pattern;
- if (dateFormatterCache.has(key)) {
- return dateFormatterCache.get(key).format(date);
- }
- var formatter = new Intl.DateTimeFormat(locale, extractComponents(pattern));
- dateFormatterCache.set(key, formatter);
- return formatter.format(date);
- };
- return DateFormatter;
- })();
- exports.DateFormatter = DateFormatter;
- /***/ },
- /* 114 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var intl_1 = __webpack_require__(113);
- var core_1 = __webpack_require__(2);
- var collection_1 = __webpack_require__(12);
- var invalid_pipe_argument_exception_1 = __webpack_require__(107);
- var defaultLocale = 'en-US';
- var _re = lang_1.RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$');
- /**
- * Internal base class for numeric pipes.
- */
- var NumberPipe = (function () {
- function NumberPipe() {
- }
- /** @internal */
- NumberPipe._format = function (value, style, digits, currency, currencyAsSymbol) {
- if (currency === void 0) { currency = null; }
- if (currencyAsSymbol === void 0) { currencyAsSymbol = false; }
- if (lang_1.isBlank(value))
- return null;
- if (!lang_1.isNumber(value)) {
- throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(NumberPipe, value);
- }
- var minInt = 1, minFraction = 0, maxFraction = 3;
- if (lang_1.isPresent(digits)) {
- var parts = lang_1.RegExpWrapper.firstMatch(_re, digits);
- if (lang_1.isBlank(parts)) {
- throw new exceptions_1.BaseException(digits + " is not a valid digit info for number pipes");
- }
- if (lang_1.isPresent(parts[1])) {
- minInt = lang_1.NumberWrapper.parseIntAutoRadix(parts[1]);
- }
- if (lang_1.isPresent(parts[3])) {
- minFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[3]);
- }
- if (lang_1.isPresent(parts[5])) {
- maxFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[5]);
- }
- }
- return intl_1.NumberFormatter.format(value, defaultLocale, style, {
- minimumIntegerDigits: minInt,
- minimumFractionDigits: minFraction,
- maximumFractionDigits: maxFraction,
- currency: currency,
- currencyAsSymbol: currencyAsSymbol
- });
- };
- NumberPipe = __decorate([
- lang_1.CONST(),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], NumberPipe);
- return NumberPipe;
- })();
- exports.NumberPipe = NumberPipe;
- /**
- * WARNING: this pipe uses the Internationalization API.
- * Therefore it is only reliable in Chrome and Opera browsers.
- *
- * Formats a number as local text. i.e. group sizing and separator and other locale-specific
- * configurations are based on the active locale.
- *
- * ### Usage
- *
- * expression | number[:digitInfo]
- *
- * where `expression` is a number and `digitInfo` has the following format:
- *
- * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
- *
- * - minIntegerDigits is the minimum number of integer digits to use. Defaults to 1.
- * - minFractionDigits is the minimum number of digits after fraction. Defaults to 0.
- * - maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
- *
- * For more information on the acceptable range for each of these numbers and other
- * details see your native internationalization library.
- *
- * ### Example
- *
- * {@example core/pipes/ts/number_pipe/number_pipe_example.ts region='NumberPipe'}
- */
- var DecimalPipe = (function (_super) {
- __extends(DecimalPipe, _super);
- function DecimalPipe() {
- _super.apply(this, arguments);
- }
- DecimalPipe.prototype.transform = function (value, args) {
- var digits = collection_1.ListWrapper.first(args);
- return NumberPipe._format(value, intl_1.NumberFormatStyle.Decimal, digits);
- };
- DecimalPipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'number' }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], DecimalPipe);
- return DecimalPipe;
- })(NumberPipe);
- exports.DecimalPipe = DecimalPipe;
- /**
- * WARNING: this pipe uses the Internationalization API.
- * Therefore it is only reliable in Chrome and Opera browsers.
- *
- * Formats a number as local percent.
- *
- * ### Usage
- *
- * expression | percent[:digitInfo]
- *
- * For more information about `digitInfo` see {@link DecimalPipe}
- *
- * ### Example
- *
- * {@example core/pipes/ts/number_pipe/number_pipe_example.ts region='PercentPipe'}
- */
- var PercentPipe = (function (_super) {
- __extends(PercentPipe, _super);
- function PercentPipe() {
- _super.apply(this, arguments);
- }
- PercentPipe.prototype.transform = function (value, args) {
- var digits = collection_1.ListWrapper.first(args);
- return NumberPipe._format(value, intl_1.NumberFormatStyle.Percent, digits);
- };
- PercentPipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'percent' }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], PercentPipe);
- return PercentPipe;
- })(NumberPipe);
- exports.PercentPipe = PercentPipe;
- /**
- * WARNING: this pipe uses the Internationalization API.
- * Therefore it is only reliable in Chrome and Opera browsers.
- *
- * Formats a number as local currency.
- *
- * ### Usage
- *
- * expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]
- *
- * where `currencyCode` is the ISO 4217 currency code, such as "USD" for the US dollar and
- * "EUR" for the euro. `symbolDisplay` is a boolean indicating whether to use the currency
- * symbol (e.g. $) or the currency code (e.g. USD) in the output. The default for this value
- * is `false`.
- * For more information about `digitInfo` see {@link DecimalPipe}
- *
- * ### Example
- *
- * {@example core/pipes/ts/number_pipe/number_pipe_example.ts region='CurrencyPipe'}
- */
- var CurrencyPipe = (function (_super) {
- __extends(CurrencyPipe, _super);
- function CurrencyPipe() {
- _super.apply(this, arguments);
- }
- CurrencyPipe.prototype.transform = function (value, args) {
- var currencyCode = lang_1.isPresent(args) && args.length > 0 ? args[0] : 'USD';
- var symbolDisplay = lang_1.isPresent(args) && args.length > 1 ? args[1] : false;
- var digits = lang_1.isPresent(args) && args.length > 2 ? args[2] : null;
- return NumberPipe._format(value, intl_1.NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay);
- };
- CurrencyPipe = __decorate([
- lang_1.CONST(),
- core_1.Pipe({ name: 'currency' }),
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], CurrencyPipe);
- return CurrencyPipe;
- })(NumberPipe);
- exports.CurrencyPipe = CurrencyPipe;
- /***/ },
- /* 115 */
- /***/ function(module, exports, __webpack_require__) {
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- /**
- * @module
- * @description
- * Common directives shipped with Angular.
- */
- var ng_class_1 = __webpack_require__(116);
- exports.NgClass = ng_class_1.NgClass;
- var ng_for_1 = __webpack_require__(117);
- exports.NgFor = ng_for_1.NgFor;
- var ng_if_1 = __webpack_require__(118);
- exports.NgIf = ng_if_1.NgIf;
- var ng_style_1 = __webpack_require__(119);
- exports.NgStyle = ng_style_1.NgStyle;
- var ng_switch_1 = __webpack_require__(120);
- exports.NgSwitch = ng_switch_1.NgSwitch;
- exports.NgSwitchWhen = ng_switch_1.NgSwitchWhen;
- exports.NgSwitchDefault = ng_switch_1.NgSwitchDefault;
- __export(__webpack_require__(121));
- var core_directives_1 = __webpack_require__(122);
- exports.CORE_DIRECTIVES = core_directives_1.CORE_DIRECTIVES;
- /***/ },
- /* 116 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- var collection_1 = __webpack_require__(12);
- /**
- * The `NgClass` directive conditionally adds and removes CSS classes on an HTML element based on
- * an expression's evaluation result.
- *
- * The result of an expression evaluation is interpreted differently depending on type of
- * the expression evaluation result:
- * - `string` - all the CSS classes listed in a string (space delimited) are added
- * - `Array` - all the CSS classes (Array elements) are added
- * - `Object` - each key corresponds to a CSS class name while values are interpreted as expressions
- * evaluating to `Boolean`. If a given expression evaluates to `true` a corresponding CSS class
- * is added - otherwise it is removed.
- *
- * While the `NgClass` directive can interpret expressions evaluating to `string`, `Array`
- * or `Object`, the `Object`-based version is the most often used and has an advantage of keeping
- * all the CSS class names in a template.
- *
- * ### Example ([live demo](http://plnkr.co/edit/a4YdtmWywhJ33uqfpPPn?p=preview)):
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {NgClass} from 'angular2/common';
- *
- * @Component({
- * selector: 'toggle-button',
- * inputs: ['isDisabled'],
- * template: `
- * <div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
- * (click)="toggle(!isOn)">
- * Click me!
- * </div>`,
- * styles: [`
- * .button {
- * width: 120px;
- * border: medium solid black;
- * }
- *
- * .active {
- * background-color: red;
- * }
- *
- * .disabled {
- * color: gray;
- * border: medium solid gray;
- * }
- * `]
- * directives: [NgClass]
- * })
- * class ToggleButton {
- * isOn = false;
- * isDisabled = false;
- *
- * toggle(newState) {
- * if (!this.isDisabled) {
- * this.isOn = newState;
- * }
- * }
- * }
- * ```
- */
- var NgClass = (function () {
- function NgClass(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) {
- this._iterableDiffers = _iterableDiffers;
- this._keyValueDiffers = _keyValueDiffers;
- this._ngEl = _ngEl;
- this._renderer = _renderer;
- this._initialClasses = [];
- }
- Object.defineProperty(NgClass.prototype, "initialClasses", {
- set: function (v) {
- this._applyInitialClasses(true);
- this._initialClasses = lang_1.isPresent(v) && lang_1.isString(v) ? v.split(' ') : [];
- this._applyInitialClasses(false);
- this._applyClasses(this._rawClass, false);
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgClass.prototype, "rawClass", {
- set: function (v) {
- this._cleanupClasses(this._rawClass);
- if (lang_1.isString(v)) {
- v = v.split(' ');
- }
- this._rawClass = v;
- if (lang_1.isPresent(v)) {
- if (collection_1.isListLikeIterable(v)) {
- this._differ = this._iterableDiffers.find(v).create(null);
- this._mode = 'iterable';
- }
- else {
- this._differ = this._keyValueDiffers.find(v).create(null);
- this._mode = 'keyValue';
- }
- }
- else {
- this._differ = null;
- }
- },
- enumerable: true,
- configurable: true
- });
- NgClass.prototype.ngDoCheck = function () {
- if (lang_1.isPresent(this._differ)) {
- var changes = this._differ.diff(this._rawClass);
- if (lang_1.isPresent(changes)) {
- if (this._mode == 'iterable') {
- this._applyIterableChanges(changes);
- }
- else {
- this._applyKeyValueChanges(changes);
- }
- }
- }
- };
- NgClass.prototype.ngOnDestroy = function () { this._cleanupClasses(this._rawClass); };
- NgClass.prototype._cleanupClasses = function (rawClassVal) {
- this._applyClasses(rawClassVal, true);
- this._applyInitialClasses(false);
- };
- NgClass.prototype._applyKeyValueChanges = function (changes) {
- var _this = this;
- changes.forEachAddedItem(function (record) { _this._toggleClass(record.key, record.currentValue); });
- changes.forEachChangedItem(function (record) { _this._toggleClass(record.key, record.currentValue); });
- changes.forEachRemovedItem(function (record) {
- if (record.previousValue) {
- _this._toggleClass(record.key, false);
- }
- });
- };
- NgClass.prototype._applyIterableChanges = function (changes) {
- var _this = this;
- changes.forEachAddedItem(function (record) { _this._toggleClass(record.item, true); });
- changes.forEachRemovedItem(function (record) { _this._toggleClass(record.item, false); });
- };
- NgClass.prototype._applyInitialClasses = function (isCleanup) {
- var _this = this;
- this._initialClasses.forEach(function (className) { return _this._toggleClass(className, !isCleanup); });
- };
- NgClass.prototype._applyClasses = function (rawClassVal, isCleanup) {
- var _this = this;
- if (lang_1.isPresent(rawClassVal)) {
- if (lang_1.isArray(rawClassVal)) {
- rawClassVal.forEach(function (className) { return _this._toggleClass(className, !isCleanup); });
- }
- else if (rawClassVal instanceof Set) {
- rawClassVal.forEach(function (className) { return _this._toggleClass(className, !isCleanup); });
- }
- else {
- collection_1.StringMapWrapper.forEach(rawClassVal, function (expVal, className) {
- if (expVal)
- _this._toggleClass(className, !isCleanup);
- });
- }
- }
- };
- NgClass.prototype._toggleClass = function (className, enabled) {
- className = className.trim();
- if (className.length > 0) {
- if (className.indexOf(' ') > -1) {
- var classes = className.split(/\s+/g);
- for (var i = 0, len = classes.length; i < len; i++) {
- this._renderer.setElementClass(this._ngEl, classes[i], enabled);
- }
- }
- else {
- this._renderer.setElementClass(this._ngEl, className, enabled);
- }
- }
- };
- NgClass = __decorate([
- core_1.Directive({ selector: '[ngClass]', inputs: ['rawClass: ngClass', 'initialClasses: class'] }),
- __metadata('design:paramtypes', [core_1.IterableDiffers, core_1.KeyValueDiffers, core_1.ElementRef, core_1.Renderer])
- ], NgClass);
- return NgClass;
- })();
- exports.NgClass = NgClass;
- /***/ },
- /* 117 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- /**
- * The `NgFor` directive instantiates a template once per item from an iterable. The context for
- * each instantiated template inherits from the outer context with the given loop variable set
- * to the current item from the iterable.
- *
- * # Local Variables
- *
- * `NgFor` provides several exported values that can be aliased to local variables:
- *
- * * `index` will be set to the current loop iteration for each template context.
- * * `last` will be set to a boolean value indicating whether the item is the last one in the
- * iteration.
- * * `even` will be set to a boolean value indicating whether this item has an even index.
- * * `odd` will be set to a boolean value indicating whether this item has an odd index.
- *
- * # Change Propagation
- *
- * When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
- *
- * * When an item is added, a new instance of the template is added to the DOM.
- * * When an item is removed, its template instance is removed from the DOM.
- * * When items are reordered, their respective templates are reordered in the DOM.
- * * Otherwise, the DOM element for that item will remain the same.
- *
- * Angular uses object identity to track insertions and deletions within the iterator and reproduce
- * those changes in the DOM. This has important implications for animations and any stateful
- * controls
- * (such as `<input>` elements which accept user input) that are present. Inserted rows can be
- * animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such
- * as user input.
- *
- * It is possible for the identities of elements in the iterator to change while the data does not.
- * This can happen, for example, if the iterator produced from an RPC to the server, and that
- * RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
- * different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
- * elements were deleted and all new elements inserted). This is an expensive operation and should
- * be avoided if possible.
- *
- * # Syntax
- *
- * - `<li *ngFor="#item of items; #i = index">...</li>`
- * - `<li template="ngFor #item of items; #i = index">...</li>`
- * - `<template ngFor #item [ngForOf]="items" #i="index"><li>...</li></template>`
- *
- * ### Example
- *
- * See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
- * example.
- */
- var NgFor = (function () {
- function NgFor(_viewContainer, _templateRef, _iterableDiffers, _cdr) {
- this._viewContainer = _viewContainer;
- this._templateRef = _templateRef;
- this._iterableDiffers = _iterableDiffers;
- this._cdr = _cdr;
- }
- Object.defineProperty(NgFor.prototype, "ngForOf", {
- set: function (value) {
- this._ngForOf = value;
- if (lang_1.isBlank(this._differ) && lang_1.isPresent(value)) {
- this._differ = this._iterableDiffers.find(value).create(this._cdr);
- }
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgFor.prototype, "ngForTemplate", {
- set: function (value) {
- if (lang_1.isPresent(value)) {
- this._templateRef = value;
- }
- },
- enumerable: true,
- configurable: true
- });
- NgFor.prototype.ngDoCheck = function () {
- if (lang_1.isPresent(this._differ)) {
- var changes = this._differ.diff(this._ngForOf);
- if (lang_1.isPresent(changes))
- this._applyChanges(changes);
- }
- };
- NgFor.prototype._applyChanges = function (changes) {
- // TODO(rado): check if change detection can produce a change record that is
- // easier to consume than current.
- var recordViewTuples = [];
- changes.forEachRemovedItem(function (removedRecord) {
- return recordViewTuples.push(new RecordViewTuple(removedRecord, null));
- });
- changes.forEachMovedItem(function (movedRecord) {
- return recordViewTuples.push(new RecordViewTuple(movedRecord, null));
- });
- var insertTuples = this._bulkRemove(recordViewTuples);
- changes.forEachAddedItem(function (addedRecord) {
- return insertTuples.push(new RecordViewTuple(addedRecord, null));
- });
- this._bulkInsert(insertTuples);
- for (var i = 0; i < insertTuples.length; i++) {
- this._perViewChange(insertTuples[i].view, insertTuples[i].record);
- }
- for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
- this._viewContainer.get(i).setLocal('last', i === ilen - 1);
- }
- };
- NgFor.prototype._perViewChange = function (view, record) {
- view.setLocal('\$implicit', record.item);
- view.setLocal('index', record.currentIndex);
- view.setLocal('even', (record.currentIndex % 2 == 0));
- view.setLocal('odd', (record.currentIndex % 2 == 1));
- };
- NgFor.prototype._bulkRemove = function (tuples) {
- tuples.sort(function (a, b) { return a.record.previousIndex - b.record.previousIndex; });
- var movedTuples = [];
- for (var i = tuples.length - 1; i >= 0; i--) {
- var tuple = tuples[i];
- // separate moved views from removed views.
- if (lang_1.isPresent(tuple.record.currentIndex)) {
- tuple.view = this._viewContainer.detach(tuple.record.previousIndex);
- movedTuples.push(tuple);
- }
- else {
- this._viewContainer.remove(tuple.record.previousIndex);
- }
- }
- return movedTuples;
- };
- NgFor.prototype._bulkInsert = function (tuples) {
- tuples.sort(function (a, b) { return a.record.currentIndex - b.record.currentIndex; });
- for (var i = 0; i < tuples.length; i++) {
- var tuple = tuples[i];
- if (lang_1.isPresent(tuple.view)) {
- this._viewContainer.insert(tuple.view, tuple.record.currentIndex);
- }
- else {
- tuple.view =
- this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex);
- }
- }
- return tuples;
- };
- NgFor = __decorate([
- core_1.Directive({ selector: '[ngFor][ngForOf]', inputs: ['ngForOf', 'ngForTemplate'] }),
- __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, core_1.IterableDiffers, core_1.ChangeDetectorRef])
- ], NgFor);
- return NgFor;
- })();
- exports.NgFor = NgFor;
- var RecordViewTuple = (function () {
- function RecordViewTuple(record, view) {
- this.record = record;
- this.view = view;
- }
- return RecordViewTuple;
- })();
- /***/ },
- /* 118 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- /**
- * Removes or recreates a portion of the DOM tree based on an {expression}.
- *
- * If the expression assigned to `ngIf` evaluates to a false value then the element
- * is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
- *
- * ### Example ([live demo](http://plnkr.co/edit/fe0kgemFBtmQOY31b4tw?p=preview)):
- *
- * ```
- * <div *ngIf="errorCount > 0" class="error">
- * <!-- Error message displayed when the errorCount property on the current context is greater
- * than 0. -->
- * {{errorCount}} errors detected
- * </div>
- * ```
- *
- * ### Syntax
- *
- * - `<div *ngIf="condition">...</div>`
- * - `<div template="ngIf condition">...</div>`
- * - `<template [ngIf]="condition"><div>...</div></template>`
- */
- var NgIf = (function () {
- function NgIf(_viewContainer, _templateRef) {
- this._viewContainer = _viewContainer;
- this._templateRef = _templateRef;
- this._prevCondition = null;
- }
- Object.defineProperty(NgIf.prototype, "ngIf", {
- set: function (newCondition /* boolean */) {
- if (newCondition && (lang_1.isBlank(this._prevCondition) || !this._prevCondition)) {
- this._prevCondition = true;
- this._viewContainer.createEmbeddedView(this._templateRef);
- }
- else if (!newCondition && (lang_1.isBlank(this._prevCondition) || this._prevCondition)) {
- this._prevCondition = false;
- this._viewContainer.clear();
- }
- },
- enumerable: true,
- configurable: true
- });
- NgIf = __decorate([
- core_1.Directive({ selector: '[ngIf]', inputs: ['ngIf'] }),
- __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef])
- ], NgIf);
- return NgIf;
- })();
- exports.NgIf = NgIf;
- /***/ },
- /* 119 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- /**
- * The `NgStyle` directive changes styles based on a result of expression evaluation.
- *
- * An expression assigned to the `ngStyle` property must evaluate to an object and the
- * corresponding element styles are updated based on changes to this object. Style names to update
- * are taken from the object's keys, and values - from the corresponding object's values.
- *
- * ### Syntax
- *
- * - `<div [ngStyle]="{'font-style': style}"></div>`
- * - `<div [ngStyle]="styleExp"></div>` - here the `styleExp` must evaluate to an object
- *
- * ### Example ([live demo](http://plnkr.co/edit/YamGS6GkUh9GqWNQhCyM?p=preview)):
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {NgStyle} from 'angular2/common';
- *
- * @Component({
- * selector: 'ngStyle-example',
- * template: `
- * <h1 [ngStyle]="{'font-style': style, 'font-size': size, 'font-weight': weight}">
- * Change style of this text!
- * </h1>
- *
- * <hr>
- *
- * <label>Italic: <input type="checkbox" (change)="changeStyle($event)"></label>
- * <label>Bold: <input type="checkbox" (change)="changeWeight($event)"></label>
- * <label>Size: <input type="text" [value]="size" (change)="size = $event.target.value"></label>
- * `,
- * directives: [NgStyle]
- * })
- * export class NgStyleExample {
- * style = 'normal';
- * weight = 'normal';
- * size = '20px';
- *
- * changeStyle($event: any) {
- * this.style = $event.target.checked ? 'italic' : 'normal';
- * }
- *
- * changeWeight($event: any) {
- * this.weight = $event.target.checked ? 'bold' : 'normal';
- * }
- * }
- * ```
- *
- * In this example the `font-style`, `font-size` and `font-weight` styles will be updated
- * based on the `style` property's value changes.
- */
- var NgStyle = (function () {
- function NgStyle(_differs, _ngEl, _renderer) {
- this._differs = _differs;
- this._ngEl = _ngEl;
- this._renderer = _renderer;
- }
- Object.defineProperty(NgStyle.prototype, "rawStyle", {
- set: function (v) {
- this._rawStyle = v;
- if (lang_1.isBlank(this._differ) && lang_1.isPresent(v)) {
- this._differ = this._differs.find(this._rawStyle).create(null);
- }
- },
- enumerable: true,
- configurable: true
- });
- NgStyle.prototype.ngDoCheck = function () {
- if (lang_1.isPresent(this._differ)) {
- var changes = this._differ.diff(this._rawStyle);
- if (lang_1.isPresent(changes)) {
- this._applyChanges(changes);
- }
- }
- };
- NgStyle.prototype._applyChanges = function (changes) {
- var _this = this;
- changes.forEachAddedItem(function (record) { _this._setStyle(record.key, record.currentValue); });
- changes.forEachChangedItem(function (record) { _this._setStyle(record.key, record.currentValue); });
- changes.forEachRemovedItem(function (record) { _this._setStyle(record.key, null); });
- };
- NgStyle.prototype._setStyle = function (name, val) {
- this._renderer.setElementStyle(this._ngEl, name, val);
- };
- NgStyle = __decorate([
- core_1.Directive({ selector: '[ngStyle]', inputs: ['rawStyle: ngStyle'] }),
- __metadata('design:paramtypes', [core_1.KeyValueDiffers, core_1.ElementRef, core_1.Renderer])
- ], NgStyle);
- return NgStyle;
- })();
- exports.NgStyle = NgStyle;
- /***/ },
- /* 120 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var _WHEN_DEFAULT = lang_1.CONST_EXPR(new Object());
- var SwitchView = (function () {
- function SwitchView(_viewContainerRef, _templateRef) {
- this._viewContainerRef = _viewContainerRef;
- this._templateRef = _templateRef;
- }
- SwitchView.prototype.create = function () { this._viewContainerRef.createEmbeddedView(this._templateRef); };
- SwitchView.prototype.destroy = function () { this._viewContainerRef.clear(); };
- return SwitchView;
- })();
- /**
- * Adds or removes DOM sub-trees when their match expressions match the switch expression.
- *
- * Elements within `NgSwitch` but without `NgSwitchWhen` or `NgSwitchDefault` directives will be
- * preserved at the location as specified in the template.
- *
- * `NgSwitch` simply inserts nested elements based on which match expression matches the value
- * obtained from the evaluated switch expression. In other words, you define a container element
- * (where you place the directive with a switch expression on the
- * **`[ngSwitch]="..."` attribute**), define any inner elements inside of the directive and
- * place a `[ngSwitchWhen]` attribute per element.
- *
- * The `ngSwitchWhen` property is used to inform `NgSwitch` which element to display when the
- * expression is evaluated. If a matching expression is not found via a `ngSwitchWhen` property
- * then an element with the `ngSwitchDefault` attribute is displayed.
- *
- * ### Example ([live demo](http://plnkr.co/edit/DQMTII95CbuqWrl3lYAs?p=preview))
- *
- * ```typescript
- * @Component({selector: 'app'})
- * @View({
- * template: `
- * <p>Value = {{value}}</p>
- * <button (click)="inc()">Increment</button>
- *
- * <div [ngSwitch]="value">
- * <p *ngSwitchWhen="'init'">increment to start</p>
- * <p *ngSwitchWhen="0">0, increment again</p>
- * <p *ngSwitchWhen="1">1, increment again</p>
- * <p *ngSwitchWhen="2">2, stop incrementing</p>
- * <p *ngSwitchDefault>> 2, STOP!</p>
- * </div>
- *
- * <!-- alternate syntax -->
- *
- * <p [ngSwitch]="value">
- * <template ngSwitchWhen="init">increment to start</template>
- * <template [ngSwitchWhen]="0">0, increment again</template>
- * <template [ngSwitchWhen]="1">1, increment again</template>
- * <template [ngSwitchWhen]="2">2, stop incrementing</template>
- * <template ngSwitchDefault>> 2, STOP!</template>
- * </p>
- * `,
- * directives: [NgSwitch, NgSwitchWhen, NgSwitchDefault]
- * })
- * export class App {
- * value = 'init';
- *
- * inc() {
- * this.value = this.value === 'init' ? 0 : this.value + 1;
- * }
- * }
- *
- * bootstrap(App).catch(err => console.error(err));
- * ```
- */
- var NgSwitch = (function () {
- function NgSwitch() {
- this._useDefault = false;
- this._valueViews = new collection_1.Map();
- this._activeViews = [];
- }
- Object.defineProperty(NgSwitch.prototype, "ngSwitch", {
- set: function (value) {
- // Empty the currently active ViewContainers
- this._emptyAllActiveViews();
- // Add the ViewContainers matching the value (with a fallback to default)
- this._useDefault = false;
- var views = this._valueViews.get(value);
- if (lang_1.isBlank(views)) {
- this._useDefault = true;
- views = lang_1.normalizeBlank(this._valueViews.get(_WHEN_DEFAULT));
- }
- this._activateViews(views);
- this._switchValue = value;
- },
- enumerable: true,
- configurable: true
- });
- /** @internal */
- NgSwitch.prototype._onWhenValueChanged = function (oldWhen, newWhen, view) {
- this._deregisterView(oldWhen, view);
- this._registerView(newWhen, view);
- if (oldWhen === this._switchValue) {
- view.destroy();
- collection_1.ListWrapper.remove(this._activeViews, view);
- }
- else if (newWhen === this._switchValue) {
- if (this._useDefault) {
- this._useDefault = false;
- this._emptyAllActiveViews();
- }
- view.create();
- this._activeViews.push(view);
- }
- // Switch to default when there is no more active ViewContainers
- if (this._activeViews.length === 0 && !this._useDefault) {
- this._useDefault = true;
- this._activateViews(this._valueViews.get(_WHEN_DEFAULT));
- }
- };
- /** @internal */
- NgSwitch.prototype._emptyAllActiveViews = function () {
- var activeContainers = this._activeViews;
- for (var i = 0; i < activeContainers.length; i++) {
- activeContainers[i].destroy();
- }
- this._activeViews = [];
- };
- /** @internal */
- NgSwitch.prototype._activateViews = function (views) {
- // TODO(vicb): assert(this._activeViews.length === 0);
- if (lang_1.isPresent(views)) {
- for (var i = 0; i < views.length; i++) {
- views[i].create();
- }
- this._activeViews = views;
- }
- };
- /** @internal */
- NgSwitch.prototype._registerView = function (value, view) {
- var views = this._valueViews.get(value);
- if (lang_1.isBlank(views)) {
- views = [];
- this._valueViews.set(value, views);
- }
- views.push(view);
- };
- /** @internal */
- NgSwitch.prototype._deregisterView = function (value, view) {
- // `_WHEN_DEFAULT` is used a marker for non-registered whens
- if (value === _WHEN_DEFAULT)
- return;
- var views = this._valueViews.get(value);
- if (views.length == 1) {
- this._valueViews.delete(value);
- }
- else {
- collection_1.ListWrapper.remove(views, view);
- }
- };
- NgSwitch = __decorate([
- core_1.Directive({ selector: '[ngSwitch]', inputs: ['ngSwitch'] }),
- __metadata('design:paramtypes', [])
- ], NgSwitch);
- return NgSwitch;
- })();
- exports.NgSwitch = NgSwitch;
- /**
- * Insert the sub-tree when the `ngSwitchWhen` expression evaluates to the same value as the
- * enclosing switch expression.
- *
- * If multiple match expression match the switch expression value, all of them are displayed.
- *
- * See {@link NgSwitch} for more details and example.
- */
- var NgSwitchWhen = (function () {
- function NgSwitchWhen(viewContainer, templateRef, ngSwitch) {
- // `_WHEN_DEFAULT` is used as a marker for a not yet initialized value
- /** @internal */
- this._value = _WHEN_DEFAULT;
- this._switch = ngSwitch;
- this._view = new SwitchView(viewContainer, templateRef);
- }
- Object.defineProperty(NgSwitchWhen.prototype, "ngSwitchWhen", {
- set: function (value) {
- this._switch._onWhenValueChanged(this._value, value, this._view);
- this._value = value;
- },
- enumerable: true,
- configurable: true
- });
- NgSwitchWhen = __decorate([
- core_1.Directive({ selector: '[ngSwitchWhen]', inputs: ['ngSwitchWhen'] }),
- __param(2, core_1.Host()),
- __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, NgSwitch])
- ], NgSwitchWhen);
- return NgSwitchWhen;
- })();
- exports.NgSwitchWhen = NgSwitchWhen;
- /**
- * Default case statements are displayed when no match expression matches the switch expression
- * value.
- *
- * See {@link NgSwitch} for more details and example.
- */
- var NgSwitchDefault = (function () {
- function NgSwitchDefault(viewContainer, templateRef, sswitch) {
- sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef));
- }
- NgSwitchDefault = __decorate([
- core_1.Directive({ selector: '[ngSwitchDefault]' }),
- __param(2, core_1.Host()),
- __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, NgSwitch])
- ], NgSwitchDefault);
- return NgSwitchDefault;
- })();
- exports.NgSwitchDefault = NgSwitchDefault;
- /***/ },
- /* 121 */
- /***/ function(module, exports) {
- // TS does not have Observables
- /***/ },
- /* 122 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var ng_class_1 = __webpack_require__(116);
- var ng_for_1 = __webpack_require__(117);
- var ng_if_1 = __webpack_require__(118);
- var ng_style_1 = __webpack_require__(119);
- var ng_switch_1 = __webpack_require__(120);
- /**
- * A collection of Angular core directives that are likely to be used in each and every Angular
- * application.
- *
- * This collection can be used to quickly enumerate all the built-in directives in the `directives`
- * property of the `@View` annotation.
- *
- * ### Example ([live demo](http://plnkr.co/edit/yakGwpCdUkg0qfzX5m8g?p=preview))
- *
- * Instead of writing:
- *
- * ```typescript
- * import {NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault} from 'angular2/common';
- * import {OtherDirective} from './myDirectives';
- *
- * @Component({
- * selector: 'my-component',
- * templateUrl: 'myComponent.html',
- * directives: [NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, OtherDirective]
- * })
- * export class MyComponent {
- * ...
- * }
- * ```
- * one could import all the core directives at once:
- *
- * ```typescript
- * import {CORE_DIRECTIVES} from 'angular2/common';
- * import {OtherDirective} from './myDirectives';
- *
- * @Component({
- * selector: 'my-component',
- * templateUrl: 'myComponent.html',
- * directives: [CORE_DIRECTIVES, OtherDirective]
- * })
- * export class MyComponent {
- * ...
- * }
- * ```
- */
- exports.CORE_DIRECTIVES = lang_1.CONST_EXPR([ng_class_1.NgClass, ng_for_1.NgFor, ng_if_1.NgIf, ng_style_1.NgStyle, ng_switch_1.NgSwitch, ng_switch_1.NgSwitchWhen, ng_switch_1.NgSwitchDefault]);
- /***/ },
- /* 123 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * This module is used for handling user input, by defining and building a {@link ControlGroup} that
- * consists of
- * {@link Control} objects, and mapping them onto the DOM. {@link Control} objects can then be used
- * to read information
- * from the form DOM elements.
- *
- * This module is not included in the `angular2` module; you must import the forms module
- * explicitly.
- *
- */
- var model_1 = __webpack_require__(124);
- exports.AbstractControl = model_1.AbstractControl;
- exports.Control = model_1.Control;
- exports.ControlGroup = model_1.ControlGroup;
- exports.ControlArray = model_1.ControlArray;
- var abstract_control_directive_1 = __webpack_require__(125);
- exports.AbstractControlDirective = abstract_control_directive_1.AbstractControlDirective;
- var control_container_1 = __webpack_require__(126);
- exports.ControlContainer = control_container_1.ControlContainer;
- var ng_control_name_1 = __webpack_require__(127);
- exports.NgControlName = ng_control_name_1.NgControlName;
- var ng_form_control_1 = __webpack_require__(137);
- exports.NgFormControl = ng_form_control_1.NgFormControl;
- var ng_model_1 = __webpack_require__(138);
- exports.NgModel = ng_model_1.NgModel;
- var ng_control_1 = __webpack_require__(128);
- exports.NgControl = ng_control_1.NgControl;
- var ng_control_group_1 = __webpack_require__(139);
- exports.NgControlGroup = ng_control_group_1.NgControlGroup;
- var ng_form_model_1 = __webpack_require__(140);
- exports.NgFormModel = ng_form_model_1.NgFormModel;
- var ng_form_1 = __webpack_require__(141);
- exports.NgForm = ng_form_1.NgForm;
- var control_value_accessor_1 = __webpack_require__(129);
- exports.NG_VALUE_ACCESSOR = control_value_accessor_1.NG_VALUE_ACCESSOR;
- var default_value_accessor_1 = __webpack_require__(132);
- exports.DefaultValueAccessor = default_value_accessor_1.DefaultValueAccessor;
- var ng_control_status_1 = __webpack_require__(142);
- exports.NgControlStatus = ng_control_status_1.NgControlStatus;
- var checkbox_value_accessor_1 = __webpack_require__(134);
- exports.CheckboxControlValueAccessor = checkbox_value_accessor_1.CheckboxControlValueAccessor;
- var select_control_value_accessor_1 = __webpack_require__(135);
- exports.NgSelectOption = select_control_value_accessor_1.NgSelectOption;
- exports.SelectControlValueAccessor = select_control_value_accessor_1.SelectControlValueAccessor;
- var directives_1 = __webpack_require__(143);
- exports.FORM_DIRECTIVES = directives_1.FORM_DIRECTIVES;
- var validators_1 = __webpack_require__(131);
- exports.NG_VALIDATORS = validators_1.NG_VALIDATORS;
- exports.NG_ASYNC_VALIDATORS = validators_1.NG_ASYNC_VALIDATORS;
- exports.Validators = validators_1.Validators;
- var validators_2 = __webpack_require__(144);
- exports.RequiredValidator = validators_2.RequiredValidator;
- exports.MinLengthValidator = validators_2.MinLengthValidator;
- exports.MaxLengthValidator = validators_2.MaxLengthValidator;
- var form_builder_1 = __webpack_require__(145);
- exports.FormBuilder = form_builder_1.FormBuilder;
- exports.FORM_PROVIDERS = form_builder_1.FORM_PROVIDERS;
- exports.FORM_BINDINGS = form_builder_1.FORM_BINDINGS;
- /***/ },
- /* 124 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- var promise_1 = __webpack_require__(61);
- var collection_1 = __webpack_require__(12);
- /**
- * Indicates that a Control is valid, i.e. that no errors exist in the input value.
- */
- exports.VALID = "VALID";
- /**
- * Indicates that a Control is invalid, i.e. that an error exists in the input value.
- */
- exports.INVALID = "INVALID";
- /**
- * Indicates that a Control is pending, i.e. that async validation is occuring and
- * errors are not yet available for the input value.
- */
- exports.PENDING = "PENDING";
- function isControl(control) {
- return control instanceof AbstractControl;
- }
- exports.isControl = isControl;
- function _find(control, path) {
- if (lang_1.isBlank(path))
- return null;
- if (!(path instanceof Array)) {
- path = path.split("/");
- }
- if (path instanceof Array && collection_1.ListWrapper.isEmpty(path))
- return null;
- return path
- .reduce(function (v, name) {
- if (v instanceof ControlGroup) {
- return lang_1.isPresent(v.controls[name]) ? v.controls[name] : null;
- }
- else if (v instanceof ControlArray) {
- var index = name;
- return lang_1.isPresent(v.at(index)) ? v.at(index) : null;
- }
- else {
- return null;
- }
- }, control);
- }
- function toObservable(r) {
- return promise_1.PromiseWrapper.isPromise(r) ? async_1.ObservableWrapper.fromPromise(r) : r;
- }
- /**
- *
- */
- var AbstractControl = (function () {
- function AbstractControl(validator, asyncValidator) {
- this.validator = validator;
- this.asyncValidator = asyncValidator;
- this._pristine = true;
- this._touched = false;
- }
- Object.defineProperty(AbstractControl.prototype, "value", {
- get: function () { return this._value; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "status", {
- get: function () { return this._status; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "valid", {
- get: function () { return this._status === exports.VALID; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "errors", {
- /**
- * Returns the errors of this control.
- */
- get: function () { return this._errors; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "pristine", {
- get: function () { return this._pristine; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "dirty", {
- get: function () { return !this.pristine; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "touched", {
- get: function () { return this._touched; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "untouched", {
- get: function () { return !this._touched; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "valueChanges", {
- get: function () { return this._valueChanges; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "statusChanges", {
- get: function () { return this._statusChanges; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControl.prototype, "pending", {
- get: function () { return this._status == exports.PENDING; },
- enumerable: true,
- configurable: true
- });
- AbstractControl.prototype.markAsTouched = function () { this._touched = true; };
- AbstractControl.prototype.markAsDirty = function (_a) {
- var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
- onlySelf = lang_1.normalizeBool(onlySelf);
- this._pristine = false;
- if (lang_1.isPresent(this._parent) && !onlySelf) {
- this._parent.markAsDirty({ onlySelf: onlySelf });
- }
- };
- AbstractControl.prototype.markAsPending = function (_a) {
- var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
- onlySelf = lang_1.normalizeBool(onlySelf);
- this._status = exports.PENDING;
- if (lang_1.isPresent(this._parent) && !onlySelf) {
- this._parent.markAsPending({ onlySelf: onlySelf });
- }
- };
- AbstractControl.prototype.setParent = function (parent) { this._parent = parent; };
- AbstractControl.prototype.updateValueAndValidity = function (_a) {
- var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
- onlySelf = lang_1.normalizeBool(onlySelf);
- emitEvent = lang_1.isPresent(emitEvent) ? emitEvent : true;
- this._updateValue();
- this._errors = this._runValidator();
- this._status = this._calculateStatus();
- if (this._status == exports.VALID || this._status == exports.PENDING) {
- this._runAsyncValidator(emitEvent);
- }
- if (emitEvent) {
- async_1.ObservableWrapper.callEmit(this._valueChanges, this._value);
- async_1.ObservableWrapper.callEmit(this._statusChanges, this._status);
- }
- if (lang_1.isPresent(this._parent) && !onlySelf) {
- this._parent.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
- }
- };
- AbstractControl.prototype._runValidator = function () { return lang_1.isPresent(this.validator) ? this.validator(this) : null; };
- AbstractControl.prototype._runAsyncValidator = function (emitEvent) {
- var _this = this;
- if (lang_1.isPresent(this.asyncValidator)) {
- this._status = exports.PENDING;
- this._cancelExistingSubscription();
- var obs = toObservable(this.asyncValidator(this));
- this._asyncValidationSubscription =
- async_1.ObservableWrapper.subscribe(obs, function (res) { return _this.setErrors(res, { emitEvent: emitEvent }); });
- }
- };
- AbstractControl.prototype._cancelExistingSubscription = function () {
- if (lang_1.isPresent(this._asyncValidationSubscription)) {
- async_1.ObservableWrapper.dispose(this._asyncValidationSubscription);
- }
- };
- /**
- * Sets errors on a control.
- *
- * This is used when validations are run not automatically, but manually by the user.
- *
- * Calling `setErrors` will also update the validity of the parent control.
- *
- * ## Usage
- *
- * ```
- * var login = new Control("someLogin");
- * login.setErrors({
- * "notUnique": true
- * });
- *
- * expect(login.valid).toEqual(false);
- * expect(login.errors).toEqual({"notUnique": true});
- *
- * login.updateValue("someOtherLogin");
- *
- * expect(login.valid).toEqual(true);
- * ```
- */
- AbstractControl.prototype.setErrors = function (errors, _a) {
- var emitEvent = (_a === void 0 ? {} : _a).emitEvent;
- emitEvent = lang_1.isPresent(emitEvent) ? emitEvent : true;
- this._errors = errors;
- this._status = this._calculateStatus();
- if (emitEvent) {
- async_1.ObservableWrapper.callEmit(this._statusChanges, this._status);
- }
- if (lang_1.isPresent(this._parent)) {
- this._parent._updateControlsErrors();
- }
- };
- AbstractControl.prototype.find = function (path) { return _find(this, path); };
- AbstractControl.prototype.getError = function (errorCode, path) {
- if (path === void 0) { path = null; }
- var control = lang_1.isPresent(path) && !collection_1.ListWrapper.isEmpty(path) ? this.find(path) : this;
- if (lang_1.isPresent(control) && lang_1.isPresent(control._errors)) {
- return collection_1.StringMapWrapper.get(control._errors, errorCode);
- }
- else {
- return null;
- }
- };
- AbstractControl.prototype.hasError = function (errorCode, path) {
- if (path === void 0) { path = null; }
- return lang_1.isPresent(this.getError(errorCode, path));
- };
- /** @internal */
- AbstractControl.prototype._updateControlsErrors = function () {
- this._status = this._calculateStatus();
- if (lang_1.isPresent(this._parent)) {
- this._parent._updateControlsErrors();
- }
- };
- /** @internal */
- AbstractControl.prototype._initObservables = function () {
- this._valueChanges = new async_1.EventEmitter();
- this._statusChanges = new async_1.EventEmitter();
- };
- AbstractControl.prototype._calculateStatus = function () {
- if (lang_1.isPresent(this._errors))
- return exports.INVALID;
- if (this._anyControlsHaveStatus(exports.PENDING))
- return exports.PENDING;
- if (this._anyControlsHaveStatus(exports.INVALID))
- return exports.INVALID;
- return exports.VALID;
- };
- return AbstractControl;
- })();
- exports.AbstractControl = AbstractControl;
- /**
- * Defines a part of a form that cannot be divided into other controls. `Control`s have values and
- * validation state, which is determined by an optional validation function.
- *
- * `Control` is one of the three fundamental building blocks used to define forms in Angular, along
- * with {@link ControlGroup} and {@link ControlArray}.
- *
- * ## Usage
- *
- * By default, a `Control` is created for every `<input>` or other form component.
- * With {@link NgFormControl} or {@link NgFormModel} an existing {@link Control} can be
- * bound to a DOM element instead. This `Control` can be configured with a custom
- * validation function.
- *
- * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
- */
- var Control = (function (_super) {
- __extends(Control, _super);
- function Control(value, validator, asyncValidator) {
- if (value === void 0) { value = null; }
- if (validator === void 0) { validator = null; }
- if (asyncValidator === void 0) { asyncValidator = null; }
- _super.call(this, validator, asyncValidator);
- this._value = value;
- this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
- this._initObservables();
- }
- /**
- * Set the value of the control to `value`.
- *
- * If `onlySelf` is `true`, this change will only affect the validation of this `Control`
- * and not its parent component. If `emitEvent` is `true`, this change will cause a
- * `valueChanges` event on the `Control` to be emitted. Both of these options default to
- * `false`.
- *
- * If `emitModelToViewChange` is `true`, the view will be notified about the new value
- * via an `onChange` event. This is the default behavior if `emitModelToViewChange` is not
- * specified.
- */
- Control.prototype.updateValue = function (value, _a) {
- var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent, emitModelToViewChange = _b.emitModelToViewChange;
- emitModelToViewChange = lang_1.isPresent(emitModelToViewChange) ? emitModelToViewChange : true;
- this._value = value;
- if (lang_1.isPresent(this._onChange) && emitModelToViewChange)
- this._onChange(this._value);
- this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
- };
- /**
- * @internal
- */
- Control.prototype._updateValue = function () { };
- /**
- * @internal
- */
- Control.prototype._anyControlsHaveStatus = function (status) { return false; };
- /**
- * Register a listener for change events.
- */
- Control.prototype.registerOnChange = function (fn) { this._onChange = fn; };
- return Control;
- })(AbstractControl);
- exports.Control = Control;
- /**
- * Defines a part of a form, of fixed length, that can contain other controls.
- *
- * A `ControlGroup` aggregates the values and errors of each {@link Control} in the group. Thus, if
- * one of the controls in a group is invalid, the entire group is invalid. Similarly, if a control
- * changes its value, the entire group changes as well.
- *
- * `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular,
- * along with {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other
- * controls, but is of variable length.
- *
- * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
- */
- var ControlGroup = (function (_super) {
- __extends(ControlGroup, _super);
- function ControlGroup(controls, optionals, validator, asyncValidator) {
- if (optionals === void 0) { optionals = null; }
- if (validator === void 0) { validator = null; }
- if (asyncValidator === void 0) { asyncValidator = null; }
- _super.call(this, validator, asyncValidator);
- this.controls = controls;
- this._optionals = lang_1.isPresent(optionals) ? optionals : {};
- this._initObservables();
- this._setParentForControls();
- this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
- }
- /**
- * Add a control to this group.
- */
- ControlGroup.prototype.addControl = function (name, control) {
- this.controls[name] = control;
- control.setParent(this);
- };
- /**
- * Remove a control from this group.
- */
- ControlGroup.prototype.removeControl = function (name) { collection_1.StringMapWrapper.delete(this.controls, name); };
- /**
- * Mark the named control as non-optional.
- */
- ControlGroup.prototype.include = function (controlName) {
- collection_1.StringMapWrapper.set(this._optionals, controlName, true);
- this.updateValueAndValidity();
- };
- /**
- * Mark the named control as optional.
- */
- ControlGroup.prototype.exclude = function (controlName) {
- collection_1.StringMapWrapper.set(this._optionals, controlName, false);
- this.updateValueAndValidity();
- };
- /**
- * Check whether there is a control with the given name in the group.
- */
- ControlGroup.prototype.contains = function (controlName) {
- var c = collection_1.StringMapWrapper.contains(this.controls, controlName);
- return c && this._included(controlName);
- };
- /** @internal */
- ControlGroup.prototype._setParentForControls = function () {
- var _this = this;
- collection_1.StringMapWrapper.forEach(this.controls, function (control, name) { control.setParent(_this); });
- };
- /** @internal */
- ControlGroup.prototype._updateValue = function () { this._value = this._reduceValue(); };
- /** @internal */
- ControlGroup.prototype._anyControlsHaveStatus = function (status) {
- var _this = this;
- var res = false;
- collection_1.StringMapWrapper.forEach(this.controls, function (control, name) {
- res = res || (_this.contains(name) && control.status == status);
- });
- return res;
- };
- /** @internal */
- ControlGroup.prototype._reduceValue = function () {
- return this._reduceChildren({}, function (acc, control, name) {
- acc[name] = control.value;
- return acc;
- });
- };
- /** @internal */
- ControlGroup.prototype._reduceChildren = function (initValue, fn) {
- var _this = this;
- var res = initValue;
- collection_1.StringMapWrapper.forEach(this.controls, function (control, name) {
- if (_this._included(name)) {
- res = fn(res, control, name);
- }
- });
- return res;
- };
- /** @internal */
- ControlGroup.prototype._included = function (controlName) {
- var isOptional = collection_1.StringMapWrapper.contains(this._optionals, controlName);
- return !isOptional || collection_1.StringMapWrapper.get(this._optionals, controlName);
- };
- return ControlGroup;
- })(AbstractControl);
- exports.ControlGroup = ControlGroup;
- /**
- * Defines a part of a form, of variable length, that can contain other controls.
- *
- * A `ControlArray` aggregates the values and errors of each {@link Control} in the group. Thus, if
- * one of the controls in a group is invalid, the entire group is invalid. Similarly, if a control
- * changes its value, the entire group changes as well.
- *
- * `ControlArray` is one of the three fundamental building blocks used to define forms in Angular,
- * along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain
- * other controls, but is of fixed length.
- *
- * ## Adding or removing controls
- *
- * To change the controls in the array, use the `push`, `insert`, or `removeAt` methods
- * in `ControlArray` itself. These methods ensure the controls are properly tracked in the
- * form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
- * the `ControlArray` directly, as that will result in strange and unexpected behavior such
- * as broken change detection.
- *
- * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
- */
- var ControlArray = (function (_super) {
- __extends(ControlArray, _super);
- function ControlArray(controls, validator, asyncValidator) {
- if (validator === void 0) { validator = null; }
- if (asyncValidator === void 0) { asyncValidator = null; }
- _super.call(this, validator, asyncValidator);
- this.controls = controls;
- this._initObservables();
- this._setParentForControls();
- this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
- }
- /**
- * Get the {@link AbstractControl} at the given `index` in the array.
- */
- ControlArray.prototype.at = function (index) { return this.controls[index]; };
- /**
- * Insert a new {@link AbstractControl} at the end of the array.
- */
- ControlArray.prototype.push = function (control) {
- this.controls.push(control);
- control.setParent(this);
- this.updateValueAndValidity();
- };
- /**
- * Insert a new {@link AbstractControl} at the given `index` in the array.
- */
- ControlArray.prototype.insert = function (index, control) {
- collection_1.ListWrapper.insert(this.controls, index, control);
- control.setParent(this);
- this.updateValueAndValidity();
- };
- /**
- * Remove the control at the given `index` in the array.
- */
- ControlArray.prototype.removeAt = function (index) {
- collection_1.ListWrapper.removeAt(this.controls, index);
- this.updateValueAndValidity();
- };
- Object.defineProperty(ControlArray.prototype, "length", {
- /**
- * Length of the control array.
- */
- get: function () { return this.controls.length; },
- enumerable: true,
- configurable: true
- });
- /** @internal */
- ControlArray.prototype._updateValue = function () { this._value = this.controls.map(function (control) { return control.value; }); };
- /** @internal */
- ControlArray.prototype._anyControlsHaveStatus = function (status) {
- return this.controls.some(function (c) { return c.status == status; });
- };
- /** @internal */
- ControlArray.prototype._setParentForControls = function () {
- var _this = this;
- this.controls.forEach(function (control) { control.setParent(_this); });
- };
- return ControlArray;
- })(AbstractControl);
- exports.ControlArray = ControlArray;
- /***/ },
- /* 125 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- /**
- * Base class for control directives.
- *
- * Only used internally in the forms module.
- */
- var AbstractControlDirective = (function () {
- function AbstractControlDirective() {
- }
- Object.defineProperty(AbstractControlDirective.prototype, "control", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "value", {
- get: function () { return lang_1.isPresent(this.control) ? this.control.value : null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "valid", {
- get: function () { return lang_1.isPresent(this.control) ? this.control.valid : null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "errors", {
- get: function () {
- return lang_1.isPresent(this.control) ? this.control.errors : null;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "pristine", {
- get: function () { return lang_1.isPresent(this.control) ? this.control.pristine : null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "dirty", {
- get: function () { return lang_1.isPresent(this.control) ? this.control.dirty : null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "touched", {
- get: function () { return lang_1.isPresent(this.control) ? this.control.touched : null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "untouched", {
- get: function () { return lang_1.isPresent(this.control) ? this.control.untouched : null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(AbstractControlDirective.prototype, "path", {
- get: function () { return null; },
- enumerable: true,
- configurable: true
- });
- return AbstractControlDirective;
- })();
- exports.AbstractControlDirective = AbstractControlDirective;
- /***/ },
- /* 126 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var abstract_control_directive_1 = __webpack_require__(125);
- /**
- * A directive that contains multiple {@link NgControl}s.
- *
- * Only used by the forms module.
- */
- var ControlContainer = (function (_super) {
- __extends(ControlContainer, _super);
- function ControlContainer() {
- _super.apply(this, arguments);
- }
- Object.defineProperty(ControlContainer.prototype, "formDirective", {
- /**
- * Get the form to which this container belongs.
- */
- get: function () { return null; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(ControlContainer.prototype, "path", {
- /**
- * Get the path to this container.
- */
- get: function () { return null; },
- enumerable: true,
- configurable: true
- });
- return ControlContainer;
- })(abstract_control_directive_1.AbstractControlDirective);
- exports.ControlContainer = ControlContainer;
- /***/ },
- /* 127 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- var core_1 = __webpack_require__(2);
- var control_container_1 = __webpack_require__(126);
- var ng_control_1 = __webpack_require__(128);
- var control_value_accessor_1 = __webpack_require__(129);
- var shared_1 = __webpack_require__(130);
- var validators_1 = __webpack_require__(131);
- var controlNameBinding = lang_1.CONST_EXPR(new core_1.Provider(ng_control_1.NgControl, { useExisting: core_1.forwardRef(function () { return NgControlName; }) }));
- /**
- * Creates and binds a control with a specified name to a DOM element.
- *
- * This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
- * ### Example
- *
- * In this example, we create the login and password controls.
- * We can work with each control separately: check its validity, get its value, listen to its
- * changes.
- *
- * ```
- * @Component({
- * selector: "login-comp",
- * directives: [FORM_DIRECTIVES],
- * template: `
- * <form #f="ngForm" (submit)='onLogIn(f.value)'>
- * Login <input type='text' ngControl='login' #l="form">
- * <div *ngIf="!l.valid">Login is invalid</div>
- *
- * Password <input type='password' ngControl='password'>
- * <button type='submit'>Log in!</button>
- * </form>
- * `})
- * class LoginComp {
- * onLogIn(value): void {
- * // value === {login: 'some login', password: 'some password'}
- * }
- * }
- * ```
- *
- * We can also use ngModel to bind a domain model to the form.
- *
- * ```
- * @Component({
- * selector: "login-comp",
- * directives: [FORM_DIRECTIVES],
- * template: `
- * <form (submit)='onLogIn()'>
- * Login <input type='text' ngControl='login' [(ngModel)]="credentials.login">
- * Password <input type='password' ngControl='password'
- * [(ngModel)]="credentials.password">
- * <button type='submit'>Log in!</button>
- * </form>
- * `})
- * class LoginComp {
- * credentials: {login:string, password:string};
- *
- * onLogIn(): void {
- * // this.credentials.login === "some login"
- * // this.credentials.password === "some password"
- * }
- * }
- * ```
- */
- var NgControlName = (function (_super) {
- __extends(NgControlName, _super);
- function NgControlName(_parent, _validators, _asyncValidators, valueAccessors) {
- _super.call(this);
- this._parent = _parent;
- this._validators = _validators;
- this._asyncValidators = _asyncValidators;
- /** @internal */
- this.update = new async_1.EventEmitter();
- this._added = false;
- this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors);
- }
- NgControlName.prototype.ngOnChanges = function (changes) {
- if (!this._added) {
- this.formDirective.addControl(this);
- this._added = true;
- }
- if (shared_1.isPropertyUpdated(changes, this.viewModel)) {
- this.viewModel = this.model;
- this.formDirective.updateModel(this, this.model);
- }
- };
- NgControlName.prototype.ngOnDestroy = function () { this.formDirective.removeControl(this); };
- NgControlName.prototype.viewToModelUpdate = function (newValue) {
- this.viewModel = newValue;
- async_1.ObservableWrapper.callEmit(this.update, newValue);
- };
- Object.defineProperty(NgControlName.prototype, "path", {
- get: function () { return shared_1.controlPath(this.name, this._parent); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlName.prototype, "formDirective", {
- get: function () { return this._parent.formDirective; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlName.prototype, "validator", {
- get: function () { return shared_1.composeValidators(this._validators); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlName.prototype, "asyncValidator", {
- get: function () { return shared_1.composeAsyncValidators(this._asyncValidators); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlName.prototype, "control", {
- get: function () { return this.formDirective.getControl(this); },
- enumerable: true,
- configurable: true
- });
- NgControlName = __decorate([
- core_1.Directive({
- selector: '[ngControl]',
- bindings: [controlNameBinding],
- inputs: ['name: ngControl', 'model: ngModel'],
- outputs: ['update: ngModelChange'],
- exportAs: 'ngForm'
- }),
- __param(0, core_1.Host()),
- __param(0, core_1.SkipSelf()),
- __param(1, core_1.Optional()),
- __param(1, core_1.Self()),
- __param(1, core_1.Inject(validators_1.NG_VALIDATORS)),
- __param(2, core_1.Optional()),
- __param(2, core_1.Self()),
- __param(2, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)),
- __param(3, core_1.Optional()),
- __param(3, core_1.Self()),
- __param(3, core_1.Inject(control_value_accessor_1.NG_VALUE_ACCESSOR)),
- __metadata('design:paramtypes', [control_container_1.ControlContainer, Array, Array, Array])
- ], NgControlName);
- return NgControlName;
- })(ng_control_1.NgControl);
- exports.NgControlName = NgControlName;
- /***/ },
- /* 128 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var abstract_control_directive_1 = __webpack_require__(125);
- var exceptions_1 = __webpack_require__(14);
- /**
- * A base class that all control directive extend.
- * It binds a {@link Control} object to a DOM element.
- *
- * Used internally by Angular forms.
- */
- var NgControl = (function (_super) {
- __extends(NgControl, _super);
- function NgControl() {
- _super.apply(this, arguments);
- this.name = null;
- this.valueAccessor = null;
- }
- Object.defineProperty(NgControl.prototype, "validator", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControl.prototype, "asyncValidator", {
- get: function () { return exceptions_1.unimplemented(); },
- enumerable: true,
- configurable: true
- });
- return NgControl;
- })(abstract_control_directive_1.AbstractControlDirective);
- exports.NgControl = NgControl;
- /***/ },
- /* 129 */
- /***/ function(module, exports, __webpack_require__) {
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- /**
- * Used to provide a {@link ControlValueAccessor} for form controls.
- *
- * See {@link DefaultValueAccessor} for how to implement one.
- */
- exports.NG_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.OpaqueToken("NgValueAccessor"));
- /***/ },
- /* 130 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var validators_1 = __webpack_require__(131);
- var default_value_accessor_1 = __webpack_require__(132);
- var number_value_accessor_1 = __webpack_require__(133);
- var checkbox_value_accessor_1 = __webpack_require__(134);
- var select_control_value_accessor_1 = __webpack_require__(135);
- var normalize_validator_1 = __webpack_require__(136);
- function controlPath(name, parent) {
- var p = collection_1.ListWrapper.clone(parent.path);
- p.push(name);
- return p;
- }
- exports.controlPath = controlPath;
- function setUpControl(control, dir) {
- if (lang_1.isBlank(control))
- _throwError(dir, "Cannot find control");
- if (lang_1.isBlank(dir.valueAccessor))
- _throwError(dir, "No value accessor for");
- control.validator = validators_1.Validators.compose([control.validator, dir.validator]);
- control.asyncValidator = validators_1.Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
- dir.valueAccessor.writeValue(control.value);
- // view -> model
- dir.valueAccessor.registerOnChange(function (newValue) {
- dir.viewToModelUpdate(newValue);
- control.updateValue(newValue, { emitModelToViewChange: false });
- control.markAsDirty();
- });
- // model -> view
- control.registerOnChange(function (newValue) { return dir.valueAccessor.writeValue(newValue); });
- // touched
- dir.valueAccessor.registerOnTouched(function () { return control.markAsTouched(); });
- }
- exports.setUpControl = setUpControl;
- function setUpControlGroup(control, dir) {
- if (lang_1.isBlank(control))
- _throwError(dir, "Cannot find control");
- control.validator = validators_1.Validators.compose([control.validator, dir.validator]);
- control.asyncValidator = validators_1.Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
- }
- exports.setUpControlGroup = setUpControlGroup;
- function _throwError(dir, message) {
- var path = dir.path.join(" -> ");
- throw new exceptions_1.BaseException(message + " '" + path + "'");
- }
- function composeValidators(validators) {
- return lang_1.isPresent(validators) ? validators_1.Validators.compose(validators.map(normalize_validator_1.normalizeValidator)) : null;
- }
- exports.composeValidators = composeValidators;
- function composeAsyncValidators(validators) {
- return lang_1.isPresent(validators) ? validators_1.Validators.composeAsync(validators.map(normalize_validator_1.normalizeValidator)) : null;
- }
- exports.composeAsyncValidators = composeAsyncValidators;
- function isPropertyUpdated(changes, viewModel) {
- if (!collection_1.StringMapWrapper.contains(changes, "model"))
- return false;
- var change = changes["model"];
- if (change.isFirstChange())
- return true;
- return !lang_1.looseIdentical(viewModel, change.currentValue);
- }
- exports.isPropertyUpdated = isPropertyUpdated;
- // TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
- function selectValueAccessor(dir, valueAccessors) {
- if (lang_1.isBlank(valueAccessors))
- return null;
- var defaultAccessor;
- var builtinAccessor;
- var customAccessor;
- valueAccessors.forEach(function (v) {
- if (v instanceof default_value_accessor_1.DefaultValueAccessor) {
- defaultAccessor = v;
- }
- else if (v instanceof checkbox_value_accessor_1.CheckboxControlValueAccessor || v instanceof number_value_accessor_1.NumberValueAccessor ||
- v instanceof select_control_value_accessor_1.SelectControlValueAccessor) {
- if (lang_1.isPresent(builtinAccessor))
- _throwError(dir, "More than one built-in value accessor matches");
- builtinAccessor = v;
- }
- else {
- if (lang_1.isPresent(customAccessor))
- _throwError(dir, "More than one custom value accessor matches");
- customAccessor = v;
- }
- });
- if (lang_1.isPresent(customAccessor))
- return customAccessor;
- if (lang_1.isPresent(builtinAccessor))
- return builtinAccessor;
- if (lang_1.isPresent(defaultAccessor))
- return defaultAccessor;
- _throwError(dir, "No valid value accessor for");
- return null;
- }
- exports.selectValueAccessor = selectValueAccessor;
- /***/ },
- /* 131 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var promise_1 = __webpack_require__(61);
- var async_1 = __webpack_require__(60);
- var collection_1 = __webpack_require__(12);
- var core_1 = __webpack_require__(2);
- /**
- * Providers for validators to be used for {@link Control}s in a form.
- *
- * Provide this using `multi: true` to add validators.
- *
- * ### Example
- *
- * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'}
- */
- exports.NG_VALIDATORS = lang_1.CONST_EXPR(new core_1.OpaqueToken("NgValidators"));
- /**
- * Providers for asynchronous validators to be used for {@link Control}s
- * in a form.
- *
- * Provide this using `multi: true` to add validators.
- *
- * See {@link NG_VALIDATORS} for more details.
- */
- exports.NG_ASYNC_VALIDATORS = lang_1.CONST_EXPR(new core_1.OpaqueToken("NgAsyncValidators"));
- /**
- * Provides a set of validators used by form controls.
- *
- * A validator is a function that processes a {@link Control} or collection of
- * controls and returns a map of errors. A null map means that validation has passed.
- *
- * ### Example
- *
- * ```typescript
- * var loginControl = new Control("", Validators.required)
- * ```
- */
- var Validators = (function () {
- function Validators() {
- }
- /**
- * Validator that requires controls to have a non-empty value.
- */
- Validators.required = function (control) {
- return lang_1.isBlank(control.value) || control.value == "" ? { "required": true } : null;
- };
- /**
- * Validator that requires controls to have a value of a minimum length.
- */
- Validators.minLength = function (minLength) {
- return function (control) {
- if (lang_1.isPresent(Validators.required(control)))
- return null;
- var v = control.value;
- return v.length < minLength ?
- { "minlength": { "requiredLength": minLength, "actualLength": v.length } } :
- null;
- };
- };
- /**
- * Validator that requires controls to have a value of a maximum length.
- */
- Validators.maxLength = function (maxLength) {
- return function (control) {
- if (lang_1.isPresent(Validators.required(control)))
- return null;
- var v = control.value;
- return v.length > maxLength ?
- { "maxlength": { "requiredLength": maxLength, "actualLength": v.length } } :
- null;
- };
- };
- /**
- * No-op validator.
- */
- Validators.nullValidator = function (c) { return null; };
- /**
- * Compose multiple validators into a single function that returns the union
- * of the individual error maps.
- */
- Validators.compose = function (validators) {
- if (lang_1.isBlank(validators))
- return null;
- var presentValidators = validators.filter(lang_1.isPresent);
- if (presentValidators.length == 0)
- return null;
- return function (control) {
- return _mergeErrors(_executeValidators(control, presentValidators));
- };
- };
- Validators.composeAsync = function (validators) {
- if (lang_1.isBlank(validators))
- return null;
- var presentValidators = validators.filter(lang_1.isPresent);
- if (presentValidators.length == 0)
- return null;
- return function (control) {
- var promises = _executeValidators(control, presentValidators).map(_convertToPromise);
- return promise_1.PromiseWrapper.all(promises).then(_mergeErrors);
- };
- };
- return Validators;
- })();
- exports.Validators = Validators;
- function _convertToPromise(obj) {
- return promise_1.PromiseWrapper.isPromise(obj) ? obj : async_1.ObservableWrapper.toPromise(obj);
- }
- function _executeValidators(control, validators) {
- return validators.map(function (v) { return v(control); });
- }
- function _mergeErrors(arrayOfErrors) {
- var res = arrayOfErrors.reduce(function (res, errors) {
- return lang_1.isPresent(errors) ? collection_1.StringMapWrapper.merge(res, errors) : res;
- }, {});
- return collection_1.StringMapWrapper.isEmpty(res) ? null : res;
- }
- /***/ },
- /* 132 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var control_value_accessor_1 = __webpack_require__(129);
- var lang_1 = __webpack_require__(5);
- var DEFAULT_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { useExisting: core_1.forwardRef(function () { return DefaultValueAccessor; }), multi: true }));
- /**
- * The default accessor for writing a value and listening to changes that is used by the
- * {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives.
- *
- * ### Example
- * ```
- * <input type="text" ngControl="searchQuery">
- * ```
- */
- var DefaultValueAccessor = (function () {
- function DefaultValueAccessor(_renderer, _elementRef) {
- this._renderer = _renderer;
- this._elementRef = _elementRef;
- this.onChange = function (_) { };
- this.onTouched = function () { };
- }
- DefaultValueAccessor.prototype.writeValue = function (value) {
- var normalizedValue = lang_1.isBlank(value) ? '' : value;
- this._renderer.setElementProperty(this._elementRef, 'value', normalizedValue);
- };
- DefaultValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
- DefaultValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
- DefaultValueAccessor = __decorate([
- core_1.Directive({
- selector: 'input:not([type=checkbox])[ngControl],textarea[ngControl],input:not([type=checkbox])[ngFormControl],textarea[ngFormControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
- // TODO: vsavkin replace the above selector with the one below it once
- // https://github.com/angular/angular/issues/3011 is implemented
- // selector: '[ngControl],[ngModel],[ngFormControl]',
- host: { '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
- bindings: [DEFAULT_VALUE_ACCESSOR]
- }),
- __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])
- ], DefaultValueAccessor);
- return DefaultValueAccessor;
- })();
- exports.DefaultValueAccessor = DefaultValueAccessor;
- /***/ },
- /* 133 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var control_value_accessor_1 = __webpack_require__(129);
- var lang_1 = __webpack_require__(5);
- var NUMBER_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { useExisting: core_1.forwardRef(function () { return NumberValueAccessor; }), multi: true }));
- /**
- * The accessor for writing a number value and listening to changes that is used by the
- * {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives.
- *
- * ### Example
- * ```
- * <input type="number" [(ngModel)]="age">
- * ```
- */
- var NumberValueAccessor = (function () {
- function NumberValueAccessor(_renderer, _elementRef) {
- this._renderer = _renderer;
- this._elementRef = _elementRef;
- this.onChange = function (_) { };
- this.onTouched = function () { };
- }
- NumberValueAccessor.prototype.writeValue = function (value) {
- this._renderer.setElementProperty(this._elementRef, 'value', value);
- };
- NumberValueAccessor.prototype.registerOnChange = function (fn) {
- this.onChange = function (value) { fn(lang_1.NumberWrapper.parseFloat(value)); };
- };
- NumberValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
- NumberValueAccessor = __decorate([
- core_1.Directive({
- selector: 'input[type=number][ngControl],input[type=number][ngFormControl],input[type=number][ngModel]',
- host: {
- '(change)': 'onChange($event.target.value)',
- '(input)': 'onChange($event.target.value)',
- '(blur)': 'onTouched()'
- },
- bindings: [NUMBER_VALUE_ACCESSOR]
- }),
- __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])
- ], NumberValueAccessor);
- return NumberValueAccessor;
- })();
- exports.NumberValueAccessor = NumberValueAccessor;
- /***/ },
- /* 134 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var control_value_accessor_1 = __webpack_require__(129);
- var lang_1 = __webpack_require__(5);
- var CHECKBOX_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { useExisting: core_1.forwardRef(function () { return CheckboxControlValueAccessor; }), multi: true }));
- /**
- * The accessor for writing a value and listening to changes on a checkbox input element.
- *
- * ### Example
- * ```
- * <input type="checkbox" ngControl="rememberLogin">
- * ```
- */
- var CheckboxControlValueAccessor = (function () {
- function CheckboxControlValueAccessor(_renderer, _elementRef) {
- this._renderer = _renderer;
- this._elementRef = _elementRef;
- this.onChange = function (_) { };
- this.onTouched = function () { };
- }
- CheckboxControlValueAccessor.prototype.writeValue = function (value) {
- this._renderer.setElementProperty(this._elementRef, 'checked', value);
- };
- CheckboxControlValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
- CheckboxControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
- CheckboxControlValueAccessor = __decorate([
- core_1.Directive({
- selector: 'input[type=checkbox][ngControl],input[type=checkbox][ngFormControl],input[type=checkbox][ngModel]',
- host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' },
- bindings: [CHECKBOX_VALUE_ACCESSOR]
- }),
- __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])
- ], CheckboxControlValueAccessor);
- return CheckboxControlValueAccessor;
- })();
- exports.CheckboxControlValueAccessor = CheckboxControlValueAccessor;
- /***/ },
- /* 135 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var async_1 = __webpack_require__(60);
- var control_value_accessor_1 = __webpack_require__(129);
- var lang_1 = __webpack_require__(5);
- var SELECT_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { useExisting: core_1.forwardRef(function () { return SelectControlValueAccessor; }), multi: true }));
- /**
- * Marks `<option>` as dynamic, so Angular can be notified when options change.
- *
- * ### Example
- *
- * ```
- * <select ngControl="city">
- * <option *ngFor="#c of cities" [value]="c"></option>
- * </select>
- * ```
- */
- var NgSelectOption = (function () {
- function NgSelectOption() {
- }
- NgSelectOption = __decorate([
- core_1.Directive({ selector: 'option' }),
- __metadata('design:paramtypes', [])
- ], NgSelectOption);
- return NgSelectOption;
- })();
- exports.NgSelectOption = NgSelectOption;
- /**
- * The accessor for writing a value and listening to changes on a select element.
- */
- var SelectControlValueAccessor = (function () {
- function SelectControlValueAccessor(_renderer, _elementRef, query) {
- this._renderer = _renderer;
- this._elementRef = _elementRef;
- this.onChange = function (_) { };
- this.onTouched = function () { };
- this._updateValueWhenListOfOptionsChanges(query);
- }
- SelectControlValueAccessor.prototype.writeValue = function (value) {
- this.value = value;
- this._renderer.setElementProperty(this._elementRef, 'value', value);
- };
- SelectControlValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
- SelectControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
- SelectControlValueAccessor.prototype._updateValueWhenListOfOptionsChanges = function (query) {
- var _this = this;
- async_1.ObservableWrapper.subscribe(query.changes, function (_) { return _this.writeValue(_this.value); });
- };
- SelectControlValueAccessor = __decorate([
- core_1.Directive({
- selector: 'select[ngControl],select[ngFormControl],select[ngModel]',
- host: {
- '(change)': 'onChange($event.target.value)',
- '(input)': 'onChange($event.target.value)',
- '(blur)': 'onTouched()'
- },
- bindings: [SELECT_VALUE_ACCESSOR]
- }),
- __param(2, core_1.Query(NgSelectOption, { descendants: true })),
- __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef, core_1.QueryList])
- ], SelectControlValueAccessor);
- return SelectControlValueAccessor;
- })();
- exports.SelectControlValueAccessor = SelectControlValueAccessor;
- /***/ },
- /* 136 */
- /***/ function(module, exports) {
- function normalizeValidator(validator) {
- if (validator.validate !== undefined) {
- return function (c) { return validator.validate(c); };
- }
- else {
- return validator;
- }
- }
- exports.normalizeValidator = normalizeValidator;
- /***/ },
- /* 137 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var async_1 = __webpack_require__(60);
- var core_1 = __webpack_require__(2);
- var ng_control_1 = __webpack_require__(128);
- var validators_1 = __webpack_require__(131);
- var control_value_accessor_1 = __webpack_require__(129);
- var shared_1 = __webpack_require__(130);
- var formControlBinding = lang_1.CONST_EXPR(new core_1.Provider(ng_control_1.NgControl, { useExisting: core_1.forwardRef(function () { return NgFormControl; }) }));
- /**
- * Binds an existing {@link Control} to a DOM element.
- *
- * ### Example ([live demo](http://plnkr.co/edit/jcQlZ2tTh22BZZ2ucNAT?p=preview))
- *
- * In this example, we bind the control to an input element. When the value of the input element
- * changes, the value of the control will reflect that change. Likewise, if the value of the
- * control changes, the input element reflects that change.
- *
- * ```typescript
- * @Component({
- * selector: 'my-app',
- * template: `
- * <div>
- * <h2>NgFormControl Example</h2>
- * <form>
- * <p>Element with existing control: <input type="text"
- * [ngFormControl]="loginControl"></p>
- * <p>Value of existing control: {{loginControl.value}}</p>
- * </form>
- * </div>
- * `,
- * directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
- * })
- * export class App {
- * loginControl: Control = new Control('');
- * }
- * ```
- *
- * ###ngModel
- *
- * We can also use `ngModel` to bind a domain model to the form.
- *
- * ### Example ([live demo](http://plnkr.co/edit/yHMLuHO7DNgT8XvtjTDH?p=preview))
- *
- * ```typescript
- * @Component({
- * selector: "login-comp",
- * directives: [FORM_DIRECTIVES],
- * template: "<input type='text' [ngFormControl]='loginControl' [(ngModel)]='login'>"
- * })
- * class LoginComp {
- * loginControl: Control = new Control('');
- * login:string;
- * }
- * ```
- */
- var NgFormControl = (function (_super) {
- __extends(NgFormControl, _super);
- function NgFormControl(_validators, _asyncValidators, valueAccessors) {
- _super.call(this);
- this._validators = _validators;
- this._asyncValidators = _asyncValidators;
- this.update = new async_1.EventEmitter();
- this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors);
- }
- NgFormControl.prototype.ngOnChanges = function (changes) {
- if (this._isControlChanged(changes)) {
- shared_1.setUpControl(this.form, this);
- this.form.updateValueAndValidity({ emitEvent: false });
- }
- if (shared_1.isPropertyUpdated(changes, this.viewModel)) {
- this.form.updateValue(this.model);
- this.viewModel = this.model;
- }
- };
- Object.defineProperty(NgFormControl.prototype, "path", {
- get: function () { return []; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgFormControl.prototype, "validator", {
- get: function () { return shared_1.composeValidators(this._validators); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgFormControl.prototype, "asyncValidator", {
- get: function () { return shared_1.composeAsyncValidators(this._asyncValidators); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgFormControl.prototype, "control", {
- get: function () { return this.form; },
- enumerable: true,
- configurable: true
- });
- NgFormControl.prototype.viewToModelUpdate = function (newValue) {
- this.viewModel = newValue;
- async_1.ObservableWrapper.callEmit(this.update, newValue);
- };
- NgFormControl.prototype._isControlChanged = function (changes) {
- return collection_1.StringMapWrapper.contains(changes, "form");
- };
- NgFormControl = __decorate([
- core_1.Directive({
- selector: '[ngFormControl]',
- bindings: [formControlBinding],
- inputs: ['form: ngFormControl', 'model: ngModel'],
- outputs: ['update: ngModelChange'],
- exportAs: 'ngForm'
- }),
- __param(0, core_1.Optional()),
- __param(0, core_1.Self()),
- __param(0, core_1.Inject(validators_1.NG_VALIDATORS)),
- __param(1, core_1.Optional()),
- __param(1, core_1.Self()),
- __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)),
- __param(2, core_1.Optional()),
- __param(2, core_1.Self()),
- __param(2, core_1.Inject(control_value_accessor_1.NG_VALUE_ACCESSOR)),
- __metadata('design:paramtypes', [Array, Array, Array])
- ], NgFormControl);
- return NgFormControl;
- })(ng_control_1.NgControl);
- exports.NgFormControl = NgFormControl;
- /***/ },
- /* 138 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- var core_1 = __webpack_require__(2);
- var control_value_accessor_1 = __webpack_require__(129);
- var ng_control_1 = __webpack_require__(128);
- var model_1 = __webpack_require__(124);
- var validators_1 = __webpack_require__(131);
- var shared_1 = __webpack_require__(130);
- var formControlBinding = lang_1.CONST_EXPR(new core_1.Provider(ng_control_1.NgControl, { useExisting: core_1.forwardRef(function () { return NgModel; }) }));
- /**
- * Binds a domain model to a form control.
- *
- * ### Usage
- *
- * `ngModel` binds an existing domain model to a form control. For a
- * two-way binding, use `[(ngModel)]` to ensure the model updates in
- * both directions.
- *
- * ### Example ([live demo](http://plnkr.co/edit/R3UX5qDaUqFO2VYR0UzH?p=preview))
- * ```typescript
- * @Component({
- * selector: "search-comp",
- * directives: [FORM_DIRECTIVES],
- * template: `<input type='text' [(ngModel)]="searchQuery">`
- * })
- * class SearchComp {
- * searchQuery: string;
- * }
- * ```
- */
- var NgModel = (function (_super) {
- __extends(NgModel, _super);
- function NgModel(_validators, _asyncValidators, valueAccessors) {
- _super.call(this);
- this._validators = _validators;
- this._asyncValidators = _asyncValidators;
- /** @internal */
- this._control = new model_1.Control();
- /** @internal */
- this._added = false;
- this.update = new async_1.EventEmitter();
- this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors);
- }
- NgModel.prototype.ngOnChanges = function (changes) {
- if (!this._added) {
- shared_1.setUpControl(this._control, this);
- this._control.updateValueAndValidity({ emitEvent: false });
- this._added = true;
- }
- if (shared_1.isPropertyUpdated(changes, this.viewModel)) {
- this._control.updateValue(this.model);
- this.viewModel = this.model;
- }
- };
- Object.defineProperty(NgModel.prototype, "control", {
- get: function () { return this._control; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgModel.prototype, "path", {
- get: function () { return []; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgModel.prototype, "validator", {
- get: function () { return shared_1.composeValidators(this._validators); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgModel.prototype, "asyncValidator", {
- get: function () { return shared_1.composeAsyncValidators(this._asyncValidators); },
- enumerable: true,
- configurable: true
- });
- NgModel.prototype.viewToModelUpdate = function (newValue) {
- this.viewModel = newValue;
- async_1.ObservableWrapper.callEmit(this.update, newValue);
- };
- NgModel = __decorate([
- core_1.Directive({
- selector: '[ngModel]:not([ngControl]):not([ngFormControl])',
- bindings: [formControlBinding],
- inputs: ['model: ngModel'],
- outputs: ['update: ngModelChange'],
- exportAs: 'ngForm'
- }),
- __param(0, core_1.Optional()),
- __param(0, core_1.Self()),
- __param(0, core_1.Inject(validators_1.NG_VALIDATORS)),
- __param(1, core_1.Optional()),
- __param(1, core_1.Self()),
- __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)),
- __param(2, core_1.Optional()),
- __param(2, core_1.Self()),
- __param(2, core_1.Inject(control_value_accessor_1.NG_VALUE_ACCESSOR)),
- __metadata('design:paramtypes', [Array, Array, Array])
- ], NgModel);
- return NgModel;
- })(ng_control_1.NgControl);
- exports.NgModel = NgModel;
- /***/ },
- /* 139 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var control_container_1 = __webpack_require__(126);
- var shared_1 = __webpack_require__(130);
- var validators_1 = __webpack_require__(131);
- var controlGroupProvider = lang_1.CONST_EXPR(new core_1.Provider(control_container_1.ControlContainer, { useExisting: core_1.forwardRef(function () { return NgControlGroup; }) }));
- /**
- * Creates and binds a control group to a DOM element.
- *
- * This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/7EJ11uGeaggViYM6T5nq?p=preview))
- *
- * ```typescript
- * @Component({
- * selector: 'my-app',
- * directives: [FORM_DIRECTIVES],
- * })
- * @View({
- * template: `
- * <div>
- * <h2>Angular2 Control & ControlGroup Example</h2>
- * <form #f="ngForm">
- * <div ngControlGroup="name" #cg-name="form">
- * <h3>Enter your name:</h3>
- * <p>First: <input ngControl="first" required></p>
- * <p>Middle: <input ngControl="middle"></p>
- * <p>Last: <input ngControl="last" required></p>
- * </div>
- * <h3>Name value:</h3>
- * <pre>{{valueOf(cgName)}}</pre>
- * <p>Name is {{cgName?.control?.valid ? "valid" : "invalid"}}</p>
- * <h3>What's your favorite food?</h3>
- * <p><input ngControl="food"></p>
- * <h3>Form value</h3>
- * <pre>{{valueOf(f)}}</pre>
- * </form>
- * </div>
- * `,
- * directives: [FORM_DIRECTIVES]
- * })
- * export class App {
- * valueOf(cg: NgControlGroup): string {
- * if (cg.control == null) {
- * return null;
- * }
- * return JSON.stringify(cg.control.value, null, 2);
- * }
- * }
- * ```
- *
- * This example declares a control group for a user's name. The value and validation state of
- * this group can be accessed separately from the overall form.
- */
- var NgControlGroup = (function (_super) {
- __extends(NgControlGroup, _super);
- function NgControlGroup(parent, _validators, _asyncValidators) {
- _super.call(this);
- this._validators = _validators;
- this._asyncValidators = _asyncValidators;
- this._parent = parent;
- }
- NgControlGroup.prototype.ngOnInit = function () { this.formDirective.addControlGroup(this); };
- NgControlGroup.prototype.ngOnDestroy = function () { this.formDirective.removeControlGroup(this); };
- Object.defineProperty(NgControlGroup.prototype, "control", {
- /**
- * Get the {@link ControlGroup} backing this binding.
- */
- get: function () { return this.formDirective.getControlGroup(this); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlGroup.prototype, "path", {
- /**
- * Get the path to this control group.
- */
- get: function () { return shared_1.controlPath(this.name, this._parent); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlGroup.prototype, "formDirective", {
- /**
- * Get the {@link Form} to which this group belongs.
- */
- get: function () { return this._parent.formDirective; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlGroup.prototype, "validator", {
- get: function () { return shared_1.composeValidators(this._validators); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlGroup.prototype, "asyncValidator", {
- get: function () { return shared_1.composeAsyncValidators(this._asyncValidators); },
- enumerable: true,
- configurable: true
- });
- NgControlGroup = __decorate([
- core_1.Directive({
- selector: '[ngControlGroup]',
- providers: [controlGroupProvider],
- inputs: ['name: ngControlGroup'],
- exportAs: 'ngForm'
- }),
- __param(0, core_1.Host()),
- __param(0, core_1.SkipSelf()),
- __param(1, core_1.Optional()),
- __param(1, core_1.Self()),
- __param(1, core_1.Inject(validators_1.NG_VALIDATORS)),
- __param(2, core_1.Optional()),
- __param(2, core_1.Self()),
- __param(2, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)),
- __metadata('design:paramtypes', [control_container_1.ControlContainer, Array, Array])
- ], NgControlGroup);
- return NgControlGroup;
- })(control_container_1.ControlContainer);
- exports.NgControlGroup = NgControlGroup;
- /***/ },
- /* 140 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var async_1 = __webpack_require__(60);
- var core_1 = __webpack_require__(2);
- var control_container_1 = __webpack_require__(126);
- var shared_1 = __webpack_require__(130);
- var validators_1 = __webpack_require__(131);
- var formDirectiveProvider = lang_1.CONST_EXPR(new core_1.Provider(control_container_1.ControlContainer, { useExisting: core_1.forwardRef(function () { return NgFormModel; }) }));
- /**
- * Binds an existing control group to a DOM element.
- *
- * ### Example ([live demo](http://plnkr.co/edit/jqrVirudY8anJxTMUjTP?p=preview))
- *
- * In this example, we bind the control group to the form element, and we bind the login and
- * password controls to the login and password elements.
- *
- * ```typescript
- * @Component({
- * selector: 'my-app',
- * template: `
- * <div>
- * <h2>NgFormModel Example</h2>
- * <form [ngFormModel]="loginForm">
- * <p>Login: <input type="text" ngControl="login"></p>
- * <p>Password: <input type="password" ngControl="password"></p>
- * </form>
- * <p>Value:</p>
- * <pre>{{value}}</pre>
- * </div>
- * `,
- * directives: [FORM_DIRECTIVES]
- * })
- * export class App {
- * loginForm: ControlGroup;
- *
- * constructor() {
- * this.loginForm = new ControlGroup({
- * login: new Control(""),
- * password: new Control("")
- * });
- * }
- *
- * get value(): string {
- * return JSON.stringify(this.loginForm.value, null, 2);
- * }
- * }
- * ```
- *
- * We can also use ngModel to bind a domain model to the form.
- *
- * ```typescript
- * @Component({
- * selector: "login-comp",
- * directives: [FORM_DIRECTIVES],
- * template: `
- * <form [ngFormModel]='loginForm'>
- * Login <input type='text' ngControl='login' [(ngModel)]='credentials.login'>
- * Password <input type='password' ngControl='password'
- * [(ngModel)]='credentials.password'>
- * <button (click)="onLogin()">Login</button>
- * </form>`
- * })
- * class LoginComp {
- * credentials: {login: string, password: string};
- * loginForm: ControlGroup;
- *
- * constructor() {
- * this.loginForm = new ControlGroup({
- * login: new Control(""),
- * password: new Control("")
- * });
- * }
- *
- * onLogin(): void {
- * // this.credentials.login === 'some login'
- * // this.credentials.password === 'some password'
- * }
- * }
- * ```
- */
- var NgFormModel = (function (_super) {
- __extends(NgFormModel, _super);
- function NgFormModel(_validators, _asyncValidators) {
- _super.call(this);
- this._validators = _validators;
- this._asyncValidators = _asyncValidators;
- this.form = null;
- this.directives = [];
- this.ngSubmit = new async_1.EventEmitter();
- }
- NgFormModel.prototype.ngOnChanges = function (changes) {
- if (collection_1.StringMapWrapper.contains(changes, "form")) {
- var sync = shared_1.composeValidators(this._validators);
- this.form.validator = validators_1.Validators.compose([this.form.validator, sync]);
- var async = shared_1.composeAsyncValidators(this._asyncValidators);
- this.form.asyncValidator = validators_1.Validators.composeAsync([this.form.asyncValidator, async]);
- this.form.updateValueAndValidity({ onlySelf: true, emitEvent: false });
- }
- this._updateDomValue();
- };
- Object.defineProperty(NgFormModel.prototype, "formDirective", {
- get: function () { return this; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgFormModel.prototype, "control", {
- get: function () { return this.form; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgFormModel.prototype, "path", {
- get: function () { return []; },
- enumerable: true,
- configurable: true
- });
- NgFormModel.prototype.addControl = function (dir) {
- var ctrl = this.form.find(dir.path);
- shared_1.setUpControl(ctrl, dir);
- ctrl.updateValueAndValidity({ emitEvent: false });
- this.directives.push(dir);
- };
- NgFormModel.prototype.getControl = function (dir) { return this.form.find(dir.path); };
- NgFormModel.prototype.removeControl = function (dir) { collection_1.ListWrapper.remove(this.directives, dir); };
- NgFormModel.prototype.addControlGroup = function (dir) {
- var ctrl = this.form.find(dir.path);
- shared_1.setUpControlGroup(ctrl, dir);
- ctrl.updateValueAndValidity({ emitEvent: false });
- };
- NgFormModel.prototype.removeControlGroup = function (dir) { };
- NgFormModel.prototype.getControlGroup = function (dir) {
- return this.form.find(dir.path);
- };
- NgFormModel.prototype.updateModel = function (dir, value) {
- var ctrl = this.form.find(dir.path);
- ctrl.updateValue(value);
- };
- NgFormModel.prototype.onSubmit = function () {
- async_1.ObservableWrapper.callEmit(this.ngSubmit, null);
- return false;
- };
- /** @internal */
- NgFormModel.prototype._updateDomValue = function () {
- var _this = this;
- this.directives.forEach(function (dir) {
- var ctrl = _this.form.find(dir.path);
- dir.valueAccessor.writeValue(ctrl.value);
- });
- };
- NgFormModel = __decorate([
- core_1.Directive({
- selector: '[ngFormModel]',
- bindings: [formDirectiveProvider],
- inputs: ['form: ngFormModel'],
- host: { '(submit)': 'onSubmit()' },
- outputs: ['ngSubmit'],
- exportAs: 'ngForm'
- }),
- __param(0, core_1.Optional()),
- __param(0, core_1.Self()),
- __param(0, core_1.Inject(validators_1.NG_VALIDATORS)),
- __param(1, core_1.Optional()),
- __param(1, core_1.Self()),
- __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)),
- __metadata('design:paramtypes', [Array, Array])
- ], NgFormModel);
- return NgFormModel;
- })(control_container_1.ControlContainer);
- exports.NgFormModel = NgFormModel;
- /***/ },
- /* 141 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var async_1 = __webpack_require__(60);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- var control_container_1 = __webpack_require__(126);
- var model_1 = __webpack_require__(124);
- var shared_1 = __webpack_require__(130);
- var validators_1 = __webpack_require__(131);
- var formDirectiveProvider = lang_1.CONST_EXPR(new core_1.Provider(control_container_1.ControlContainer, { useExisting: core_1.forwardRef(function () { return NgForm; }) }));
- /**
- * If `NgForm` is bound in a component, `<form>` elements in that component will be
- * upgraded to use the Angular form system.
- *
- * ### Typical Use
- *
- * Include `FORM_DIRECTIVES` in the `directives` section of a {@link View} annotation
- * to use `NgForm` and its associated controls.
- *
- * ### Structure
- *
- * An Angular form is a collection of `Control`s in some hierarchy.
- * `Control`s can be at the top level or can be organized in `ControlGroup`s
- * or `ControlArray`s. This hierarchy is reflected in the form's `value`, a
- * JSON object that mirrors the form structure.
- *
- * ### Submission
- *
- * The `ngSubmit` event signals when the user triggers a form submission.
- *
- * ### Example ([live demo](http://plnkr.co/edit/ltdgYj4P0iY64AR71EpL?p=preview))
- *
- * ```typescript
- * @Component({
- * selector: 'my-app',
- * template: `
- * <div>
- * <p>Submit the form to see the data object Angular builds</p>
- * <h2>NgForm demo</h2>
- * <form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
- * <h3>Control group: credentials</h3>
- * <div ngControlGroup="credentials">
- * <p>Login: <input type="text" ngControl="login"></p>
- * <p>Password: <input type="password" ngControl="password"></p>
- * </div>
- * <h3>Control group: person</h3>
- * <div ngControlGroup="person">
- * <p>First name: <input type="text" ngControl="firstName"></p>
- * <p>Last name: <input type="text" ngControl="lastName"></p>
- * </div>
- * <button type="submit">Submit Form</button>
- * <p>Form data submitted:</p>
- * </form>
- * <pre>{{data}}</pre>
- * </div>
- * `,
- * directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
- * })
- * export class App {
- * constructor() {}
- *
- * data: string;
- *
- * onSubmit(data) {
- * this.data = JSON.stringify(data, null, 2);
- * }
- * }
- * ```
- */
- var NgForm = (function (_super) {
- __extends(NgForm, _super);
- function NgForm(validators, asyncValidators) {
- _super.call(this);
- this.ngSubmit = new async_1.EventEmitter();
- this.form = new model_1.ControlGroup({}, null, shared_1.composeValidators(validators), shared_1.composeAsyncValidators(asyncValidators));
- }
- Object.defineProperty(NgForm.prototype, "formDirective", {
- get: function () { return this; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgForm.prototype, "control", {
- get: function () { return this.form; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgForm.prototype, "path", {
- get: function () { return []; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgForm.prototype, "controls", {
- get: function () { return this.form.controls; },
- enumerable: true,
- configurable: true
- });
- NgForm.prototype.addControl = function (dir) {
- var _this = this;
- async_1.PromiseWrapper.scheduleMicrotask(function () {
- var container = _this._findContainer(dir.path);
- var ctrl = new model_1.Control();
- shared_1.setUpControl(ctrl, dir);
- container.addControl(dir.name, ctrl);
- ctrl.updateValueAndValidity({ emitEvent: false });
- });
- };
- NgForm.prototype.getControl = function (dir) { return this.form.find(dir.path); };
- NgForm.prototype.removeControl = function (dir) {
- var _this = this;
- async_1.PromiseWrapper.scheduleMicrotask(function () {
- var container = _this._findContainer(dir.path);
- if (lang_1.isPresent(container)) {
- container.removeControl(dir.name);
- container.updateValueAndValidity({ emitEvent: false });
- }
- });
- };
- NgForm.prototype.addControlGroup = function (dir) {
- var _this = this;
- async_1.PromiseWrapper.scheduleMicrotask(function () {
- var container = _this._findContainer(dir.path);
- var group = new model_1.ControlGroup({});
- shared_1.setUpControlGroup(group, dir);
- container.addControl(dir.name, group);
- group.updateValueAndValidity({ emitEvent: false });
- });
- };
- NgForm.prototype.removeControlGroup = function (dir) {
- var _this = this;
- async_1.PromiseWrapper.scheduleMicrotask(function () {
- var container = _this._findContainer(dir.path);
- if (lang_1.isPresent(container)) {
- container.removeControl(dir.name);
- container.updateValueAndValidity({ emitEvent: false });
- }
- });
- };
- NgForm.prototype.getControlGroup = function (dir) {
- return this.form.find(dir.path);
- };
- NgForm.prototype.updateModel = function (dir, value) {
- var _this = this;
- async_1.PromiseWrapper.scheduleMicrotask(function () {
- var ctrl = _this.form.find(dir.path);
- ctrl.updateValue(value);
- });
- };
- NgForm.prototype.onSubmit = function () {
- async_1.ObservableWrapper.callEmit(this.ngSubmit, null);
- return false;
- };
- /** @internal */
- NgForm.prototype._findContainer = function (path) {
- path.pop();
- return collection_1.ListWrapper.isEmpty(path) ? this.form : this.form.find(path);
- };
- NgForm = __decorate([
- core_1.Directive({
- selector: 'form:not([ngNoForm]):not([ngFormModel]),ngForm,[ngForm]',
- bindings: [formDirectiveProvider],
- host: {
- '(submit)': 'onSubmit()',
- },
- outputs: ['ngSubmit'],
- exportAs: 'ngForm'
- }),
- __param(0, core_1.Optional()),
- __param(0, core_1.Self()),
- __param(0, core_1.Inject(validators_1.NG_VALIDATORS)),
- __param(1, core_1.Optional()),
- __param(1, core_1.Self()),
- __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)),
- __metadata('design:paramtypes', [Array, Array])
- ], NgForm);
- return NgForm;
- })(control_container_1.ControlContainer);
- exports.NgForm = NgForm;
- /***/ },
- /* 142 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var ng_control_1 = __webpack_require__(128);
- var lang_1 = __webpack_require__(5);
- /**
- * Directive automatically applied to Angular forms that sets CSS classes
- * based on control status (valid/invalid/dirty/etc).
- */
- var NgControlStatus = (function () {
- function NgControlStatus(cd) {
- this._cd = cd;
- }
- Object.defineProperty(NgControlStatus.prototype, "ngClassUntouched", {
- get: function () {
- return lang_1.isPresent(this._cd.control) ? this._cd.control.untouched : false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlStatus.prototype, "ngClassTouched", {
- get: function () {
- return lang_1.isPresent(this._cd.control) ? this._cd.control.touched : false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlStatus.prototype, "ngClassPristine", {
- get: function () {
- return lang_1.isPresent(this._cd.control) ? this._cd.control.pristine : false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlStatus.prototype, "ngClassDirty", {
- get: function () {
- return lang_1.isPresent(this._cd.control) ? this._cd.control.dirty : false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlStatus.prototype, "ngClassValid", {
- get: function () {
- return lang_1.isPresent(this._cd.control) ? this._cd.control.valid : false;
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(NgControlStatus.prototype, "ngClassInvalid", {
- get: function () {
- return lang_1.isPresent(this._cd.control) ? !this._cd.control.valid : false;
- },
- enumerable: true,
- configurable: true
- });
- NgControlStatus = __decorate([
- core_1.Directive({
- selector: '[ngControl],[ngModel],[ngFormControl]',
- host: {
- '[class.ng-untouched]': 'ngClassUntouched',
- '[class.ng-touched]': 'ngClassTouched',
- '[class.ng-pristine]': 'ngClassPristine',
- '[class.ng-dirty]': 'ngClassDirty',
- '[class.ng-valid]': 'ngClassValid',
- '[class.ng-invalid]': 'ngClassInvalid'
- }
- }),
- __param(0, core_1.Self()),
- __metadata('design:paramtypes', [ng_control_1.NgControl])
- ], NgControlStatus);
- return NgControlStatus;
- })();
- exports.NgControlStatus = NgControlStatus;
- /***/ },
- /* 143 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var ng_control_name_1 = __webpack_require__(127);
- var ng_form_control_1 = __webpack_require__(137);
- var ng_model_1 = __webpack_require__(138);
- var ng_control_group_1 = __webpack_require__(139);
- var ng_form_model_1 = __webpack_require__(140);
- var ng_form_1 = __webpack_require__(141);
- var default_value_accessor_1 = __webpack_require__(132);
- var checkbox_value_accessor_1 = __webpack_require__(134);
- var number_value_accessor_1 = __webpack_require__(133);
- var ng_control_status_1 = __webpack_require__(142);
- var select_control_value_accessor_1 = __webpack_require__(135);
- var validators_1 = __webpack_require__(144);
- var ng_control_name_2 = __webpack_require__(127);
- exports.NgControlName = ng_control_name_2.NgControlName;
- var ng_form_control_2 = __webpack_require__(137);
- exports.NgFormControl = ng_form_control_2.NgFormControl;
- var ng_model_2 = __webpack_require__(138);
- exports.NgModel = ng_model_2.NgModel;
- var ng_control_group_2 = __webpack_require__(139);
- exports.NgControlGroup = ng_control_group_2.NgControlGroup;
- var ng_form_model_2 = __webpack_require__(140);
- exports.NgFormModel = ng_form_model_2.NgFormModel;
- var ng_form_2 = __webpack_require__(141);
- exports.NgForm = ng_form_2.NgForm;
- var default_value_accessor_2 = __webpack_require__(132);
- exports.DefaultValueAccessor = default_value_accessor_2.DefaultValueAccessor;
- var checkbox_value_accessor_2 = __webpack_require__(134);
- exports.CheckboxControlValueAccessor = checkbox_value_accessor_2.CheckboxControlValueAccessor;
- var number_value_accessor_2 = __webpack_require__(133);
- exports.NumberValueAccessor = number_value_accessor_2.NumberValueAccessor;
- var ng_control_status_2 = __webpack_require__(142);
- exports.NgControlStatus = ng_control_status_2.NgControlStatus;
- var select_control_value_accessor_2 = __webpack_require__(135);
- exports.SelectControlValueAccessor = select_control_value_accessor_2.SelectControlValueAccessor;
- exports.NgSelectOption = select_control_value_accessor_2.NgSelectOption;
- var validators_2 = __webpack_require__(144);
- exports.RequiredValidator = validators_2.RequiredValidator;
- exports.MinLengthValidator = validators_2.MinLengthValidator;
- exports.MaxLengthValidator = validators_2.MaxLengthValidator;
- var ng_control_1 = __webpack_require__(128);
- exports.NgControl = ng_control_1.NgControl;
- /**
- *
- * A list of all the form directives used as part of a `@View` annotation.
- *
- * This is a shorthand for importing them each individually.
- *
- * ### Example
- *
- * ```typescript
- * @Component({
- * selector: 'my-app',
- * directives: [FORM_DIRECTIVES]
- * })
- * class MyApp {}
- * ```
- */
- exports.FORM_DIRECTIVES = lang_1.CONST_EXPR([
- ng_control_name_1.NgControlName,
- ng_control_group_1.NgControlGroup,
- ng_form_control_1.NgFormControl,
- ng_model_1.NgModel,
- ng_form_model_1.NgFormModel,
- ng_form_1.NgForm,
- select_control_value_accessor_1.NgSelectOption,
- default_value_accessor_1.DefaultValueAccessor,
- number_value_accessor_1.NumberValueAccessor,
- checkbox_value_accessor_1.CheckboxControlValueAccessor,
- select_control_value_accessor_1.SelectControlValueAccessor,
- ng_control_status_1.NgControlStatus,
- validators_1.RequiredValidator,
- validators_1.MinLengthValidator,
- validators_1.MaxLengthValidator
- ]);
- /***/ },
- /* 144 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var validators_1 = __webpack_require__(131);
- var lang_2 = __webpack_require__(5);
- var REQUIRED_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { useValue: validators_1.Validators.required, multi: true }));
- /**
- * A Directive that adds the `required` validator to any controls marked with the
- * `required` attribute, via the {@link NG_VALIDATORS} binding.
- *
- * ### Example
- *
- * ```
- * <input ngControl="fullName" required>
- * ```
- */
- var RequiredValidator = (function () {
- function RequiredValidator() {
- }
- RequiredValidator = __decorate([
- core_1.Directive({
- selector: '[required][ngControl],[required][ngFormControl],[required][ngModel]',
- providers: [REQUIRED_VALIDATOR]
- }),
- __metadata('design:paramtypes', [])
- ], RequiredValidator);
- return RequiredValidator;
- })();
- exports.RequiredValidator = RequiredValidator;
- /**
- * Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
- *
- * ## Example:
- *
- * {@example common/forms/ts/validators/validators.ts region='min'}
- */
- var MIN_LENGTH_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { useExisting: core_1.forwardRef(function () { return MinLengthValidator; }), multi: true }));
- /**
- * A directive which installs the {@link MinLengthValidator} for any `ngControl`,
- * `ngFormControl`, or control with `ngModel` that also has a `minlength` attribute.
- */
- var MinLengthValidator = (function () {
- function MinLengthValidator(minLength) {
- this._validator = validators_1.Validators.minLength(lang_2.NumberWrapper.parseInt(minLength, 10));
- }
- MinLengthValidator.prototype.validate = function (c) { return this._validator(c); };
- MinLengthValidator = __decorate([
- core_1.Directive({
- selector: '[minlength][ngControl],[minlength][ngFormControl],[minlength][ngModel]',
- providers: [MIN_LENGTH_VALIDATOR]
- }),
- __param(0, core_1.Attribute("minlength")),
- __metadata('design:paramtypes', [String])
- ], MinLengthValidator);
- return MinLengthValidator;
- })();
- exports.MinLengthValidator = MinLengthValidator;
- /**
- * Provider which adds {@link MaxLengthValidator} to {@link NG_VALIDATORS}.
- *
- * ## Example:
- *
- * {@example common/forms/ts/validators/validators.ts region='max'}
- */
- var MAX_LENGTH_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { useExisting: core_1.forwardRef(function () { return MaxLengthValidator; }), multi: true }));
- /**
- * A directive which installs the {@link MaxLengthValidator} for any `ngControl, `ngFormControl`,
- * or control with `ngModel` that also has a `maxlength` attribute.
- */
- var MaxLengthValidator = (function () {
- function MaxLengthValidator(maxLength) {
- this._validator = validators_1.Validators.maxLength(lang_2.NumberWrapper.parseInt(maxLength, 10));
- }
- MaxLengthValidator.prototype.validate = function (c) { return this._validator(c); };
- MaxLengthValidator = __decorate([
- core_1.Directive({
- selector: '[maxlength][ngControl],[maxlength][ngFormControl],[maxlength][ngModel]',
- providers: [MAX_LENGTH_VALIDATOR]
- }),
- __param(0, core_1.Attribute("maxlength")),
- __metadata('design:paramtypes', [String])
- ], MaxLengthValidator);
- return MaxLengthValidator;
- })();
- exports.MaxLengthValidator = MaxLengthValidator;
- /***/ },
- /* 145 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var modelModule = __webpack_require__(124);
- /**
- * Creates a form object from a user-specified configuration.
- *
- * ### Example ([live demo](http://plnkr.co/edit/ENgZo8EuIECZNensZCVr?p=preview))
- *
- * ```typescript
- * @Component({
- * selector: 'my-app',
- * viewBindings: [FORM_BINDINGS]
- * template: `
- * <form [ngFormModel]="loginForm">
- * <p>Login <input ngControl="login"></p>
- * <div ngControlGroup="passwordRetry">
- * <p>Password <input type="password" ngControl="password"></p>
- * <p>Confirm password <input type="password" ngControl="passwordConfirmation"></p>
- * </div>
- * </form>
- * <h3>Form value:</h3>
- * <pre>{{value}}</pre>
- * `,
- * directives: [FORM_DIRECTIVES]
- * })
- * export class App {
- * loginForm: ControlGroup;
- *
- * constructor(builder: FormBuilder) {
- * this.loginForm = builder.group({
- * login: ["", Validators.required],
- * passwordRetry: builder.group({
- * password: ["", Validators.required],
- * passwordConfirmation: ["", Validators.required, asyncValidator]
- * })
- * });
- * }
- *
- * get value(): string {
- * return JSON.stringify(this.loginForm.value, null, 2);
- * }
- * }
- * ```
- */
- var FormBuilder = (function () {
- function FormBuilder() {
- }
- /**
- * Construct a new {@link ControlGroup} with the given map of configuration.
- * Valid keys for the `extra` parameter map are `optionals` and `validator`.
- *
- * See the {@link ControlGroup} constructor for more details.
- */
- FormBuilder.prototype.group = function (controlsConfig, extra) {
- if (extra === void 0) { extra = null; }
- var controls = this._reduceControls(controlsConfig);
- var optionals = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "optionals") : null;
- var validator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "validator") : null;
- var asyncValidator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "asyncValidator") : null;
- return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator);
- };
- /**
- * Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`.
- */
- FormBuilder.prototype.control = function (value, validator, asyncValidator) {
- if (validator === void 0) { validator = null; }
- if (asyncValidator === void 0) { asyncValidator = null; }
- return new modelModule.Control(value, validator, asyncValidator);
- };
- /**
- * Construct an array of {@link Control}s from the given `controlsConfig` array of
- * configuration, with the given optional `validator` and `asyncValidator`.
- */
- FormBuilder.prototype.array = function (controlsConfig, validator, asyncValidator) {
- var _this = this;
- if (validator === void 0) { validator = null; }
- if (asyncValidator === void 0) { asyncValidator = null; }
- var controls = controlsConfig.map(function (c) { return _this._createControl(c); });
- return new modelModule.ControlArray(controls, validator, asyncValidator);
- };
- /** @internal */
- FormBuilder.prototype._reduceControls = function (controlsConfig) {
- var _this = this;
- var controls = {};
- collection_1.StringMapWrapper.forEach(controlsConfig, function (controlConfig, controlName) {
- controls[controlName] = _this._createControl(controlConfig);
- });
- return controls;
- };
- /** @internal */
- FormBuilder.prototype._createControl = function (controlConfig) {
- if (controlConfig instanceof modelModule.Control ||
- controlConfig instanceof modelModule.ControlGroup ||
- controlConfig instanceof modelModule.ControlArray) {
- return controlConfig;
- }
- else if (lang_1.isArray(controlConfig)) {
- var value = controlConfig[0];
- var validator = controlConfig.length > 1 ? controlConfig[1] : null;
- var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
- return this.control(value, validator, asyncValidator);
- }
- else {
- return this.control(controlConfig);
- }
- };
- FormBuilder = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], FormBuilder);
- return FormBuilder;
- })();
- exports.FormBuilder = FormBuilder;
- /**
- * Shorthand set of providers used for building Angular forms.
- *
- * ### Example
- *
- * ```typescript
- * bootstrap(MyApp, [FORM_PROVIDERS]);
- * ```
- */
- exports.FORM_PROVIDERS = lang_1.CONST_EXPR([FormBuilder]);
- /**
- * See {@link FORM_PROVIDERS} instead.
- *
- * @deprecated
- */
- exports.FORM_BINDINGS = exports.FORM_PROVIDERS;
- /***/ },
- /* 146 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var forms_1 = __webpack_require__(123);
- var directives_1 = __webpack_require__(115);
- /**
- * A collection of Angular core directives that are likely to be used in each and every Angular
- * application. This includes core directives (e.g., NgIf and NgFor), and forms directives (e.g.,
- * NgModel).
- *
- * This collection can be used to quickly enumerate all the built-in directives in the `directives`
- * property of the `@Component` or `@View` decorators.
- *
- * ### Example
- *
- * Instead of writing:
- *
- * ```typescript
- * import {NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgModel, NgForm} from
- * 'angular2/common';
- * import {OtherDirective} from './myDirectives';
- *
- * @Component({
- * selector: 'my-component',
- * templateUrl: 'myComponent.html',
- * directives: [NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgModel, NgForm,
- * OtherDirective]
- * })
- * export class MyComponent {
- * ...
- * }
- * ```
- * one could import all the common directives at once:
- *
- * ```typescript
- * import {COMMON_DIRECTIVES} from 'angular2/common';
- * import {OtherDirective} from './myDirectives';
- *
- * @Component({
- * selector: 'my-component',
- * templateUrl: 'myComponent.html',
- * directives: [COMMON_DIRECTIVES, OtherDirective]
- * })
- * export class MyComponent {
- * ...
- * }
- * ```
- */
- exports.COMMON_DIRECTIVES = lang_1.CONST_EXPR([directives_1.CORE_DIRECTIVES, forms_1.FORM_DIRECTIVES]);
- /***/ },
- /* 147 */
- /***/ function(module, exports, __webpack_require__) {
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- /**
- * @module
- * @description
- * Starting point to import all compiler APIs.
- */
- __export(__webpack_require__(148));
- __export(__webpack_require__(149));
- __export(__webpack_require__(150));
- /***/ },
- /* 148 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var application_tokens_1 = __webpack_require__(67);
- var di_2 = __webpack_require__(6);
- /**
- * Create a {@link UrlResolver} with no package prefix.
- */
- function createWithoutPackagePrefix() {
- return new UrlResolver();
- }
- exports.createWithoutPackagePrefix = createWithoutPackagePrefix;
- /**
- * A default provider for {@link PACKAGE_ROOT_URL} that maps to '/'.
- */
- exports.DEFAULT_PACKAGE_URL_PROVIDER = new di_2.Provider(application_tokens_1.PACKAGE_ROOT_URL, { useValue: "/" });
- /**
- * Used by the {@link Compiler} when resolving HTML and CSS template URLs.
- *
- * This class can be overridden by the application developer to create custom behavior.
- *
- * See {@link Compiler}
- *
- * ## Example
- *
- * {@example compiler/ts/url_resolver/url_resolver.ts region='url_resolver'}
- */
- var UrlResolver = (function () {
- function UrlResolver(packagePrefix) {
- if (packagePrefix === void 0) { packagePrefix = null; }
- if (lang_1.isPresent(packagePrefix)) {
- this._packagePrefix = lang_1.StringWrapper.stripRight(packagePrefix, "/") + "/";
- }
- }
- /**
- * Resolves the `url` given the `baseUrl`:
- * - when the `url` is null, the `baseUrl` is returned,
- * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
- * `baseUrl` and `url`,
- * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
- * returned as is (ignoring the `baseUrl`)
- *
- * @param {string} baseUrl
- * @param {string} url
- * @returns {string} the resolved URL
- */
- UrlResolver.prototype.resolve = function (baseUrl, url) {
- var resolvedUrl = url;
- if (lang_1.isPresent(baseUrl) && baseUrl.length > 0) {
- resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
- }
- if (lang_1.isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == "package") {
- resolvedUrl = resolvedUrl.replace("package:", this._packagePrefix);
- }
- return resolvedUrl;
- };
- UrlResolver = __decorate([
- di_1.Injectable(),
- __param(0, di_1.Inject(application_tokens_1.PACKAGE_ROOT_URL)),
- __metadata('design:paramtypes', [String])
- ], UrlResolver);
- return UrlResolver;
- })();
- exports.UrlResolver = UrlResolver;
- /**
- * Extract the scheme of a URL.
- */
- function getUrlScheme(url) {
- var match = _split(url);
- return (match && match[_ComponentIndex.Scheme]) || "";
- }
- exports.getUrlScheme = getUrlScheme;
- // The code below is adapted from Traceur:
- // https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
- /**
- * Builds a URI string from already-encoded parts.
- *
- * No encoding is performed. Any component may be omitted as either null or
- * undefined.
- *
- * @param {?string=} opt_scheme The scheme such as 'http'.
- * @param {?string=} opt_userInfo The user name before the '@'.
- * @param {?string=} opt_domain The domain such as 'www.google.com', already
- * URI-encoded.
- * @param {(string|null)=} opt_port The port number.
- * @param {?string=} opt_path The path, already URI-encoded. If it is not
- * empty, it must begin with a slash.
- * @param {?string=} opt_queryData The URI-encoded query data.
- * @param {?string=} opt_fragment The URI-encoded fragment identifier.
- * @return {string} The fully combined URI.
- */
- function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
- var out = [];
- if (lang_1.isPresent(opt_scheme)) {
- out.push(opt_scheme + ':');
- }
- if (lang_1.isPresent(opt_domain)) {
- out.push('//');
- if (lang_1.isPresent(opt_userInfo)) {
- out.push(opt_userInfo + '@');
- }
- out.push(opt_domain);
- if (lang_1.isPresent(opt_port)) {
- out.push(':' + opt_port);
- }
- }
- if (lang_1.isPresent(opt_path)) {
- out.push(opt_path);
- }
- if (lang_1.isPresent(opt_queryData)) {
- out.push('?' + opt_queryData);
- }
- if (lang_1.isPresent(opt_fragment)) {
- out.push('#' + opt_fragment);
- }
- return out.join('');
- }
- /**
- * A regular expression for breaking a URI into its component parts.
- *
- * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
- * As the "first-match-wins" algorithm is identical to the "greedy"
- * disambiguation method used by POSIX regular expressions, it is natural and
- * commonplace to use a regular expression for parsing the potential five
- * components of a URI reference.
- *
- * The following line is the regular expression for breaking-down a
- * well-formed URI reference into its components.
- *
- * <pre>
- * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
- * 12 3 4 5 6 7 8 9
- * </pre>
- *
- * The numbers in the second line above are only to assist readability; they
- * indicate the reference points for each subexpression (i.e., each paired
- * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
- * For example, matching the above expression to
- * <pre>
- * http://www.ics.uci.edu/pub/ietf/uri/#Related
- * </pre>
- * results in the following subexpression matches:
- * <pre>
- * $1 = http:
- * $2 = http
- * $3 = //www.ics.uci.edu
- * $4 = www.ics.uci.edu
- * $5 = /pub/ietf/uri/
- * $6 = <undefined>
- * $7 = <undefined>
- * $8 = #Related
- * $9 = Related
- * </pre>
- * where <undefined> indicates that the component is not present, as is the
- * case for the query component in the above example. Therefore, we can
- * determine the value of the five components as
- * <pre>
- * scheme = $2
- * authority = $4
- * path = $5
- * query = $7
- * fragment = $9
- * </pre>
- *
- * The regular expression has been modified slightly to expose the
- * userInfo, domain, and port separately from the authority.
- * The modified version yields
- * <pre>
- * $1 = http scheme
- * $2 = <undefined> userInfo -\
- * $3 = www.ics.uci.edu domain | authority
- * $4 = <undefined> port -/
- * $5 = /pub/ietf/uri/ path
- * $6 = <undefined> query without ?
- * $7 = Related fragment without #
- * </pre>
- * @type {!RegExp}
- * @internal
- */
- var _splitRe = lang_1.RegExpWrapper.create('^' +
- '(?:' +
- '([^:/?#.]+)' +
- // used by other URL parts such as :,
- // ?, /, #, and .
- ':)?' +
- '(?://' +
- '(?:([^/?#]*)@)?' +
- '([\\w\\d\\-\\u0100-\\uffff.%]*)' +
- // digits, dashes, dots, percent
- // escapes, and unicode characters.
- '(?::([0-9]+))?' +
- ')?' +
- '([^?#]+)?' +
- '(?:\\?([^#]*))?' +
- '(?:#(.*))?' +
- '$');
- /**
- * The index of each URI component in the return value of goog.uri.utils.split.
- * @enum {number}
- */
- var _ComponentIndex;
- (function (_ComponentIndex) {
- _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
- _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
- _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
- _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
- _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
- _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
- _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
- })(_ComponentIndex || (_ComponentIndex = {}));
- /**
- * Splits a URI into its component parts.
- *
- * Each component can be accessed via the component indices; for example:
- * <pre>
- * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
- * </pre>
- *
- * @param {string} uri The URI string to examine.
- * @return {!Array.<string|undefined>} Each component still URI-encoded.
- * Each component that is present will contain the encoded value, whereas
- * components that are not present will be undefined or empty, depending
- * on the browser's regular expression implementation. Never null, since
- * arbitrary strings may still look like path names.
- */
- function _split(uri) {
- return lang_1.RegExpWrapper.firstMatch(_splitRe, uri);
- }
- /**
- * Removes dot segments in given path component, as described in
- * RFC 3986, section 5.2.4.
- *
- * @param {string} path A non-empty path component.
- * @return {string} Path component with removed dot segments.
- */
- function _removeDotSegments(path) {
- if (path == '/')
- return '/';
- var leadingSlash = path[0] == '/' ? '/' : '';
- var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
- var segments = path.split('/');
- var out = [];
- var up = 0;
- for (var pos = 0; pos < segments.length; pos++) {
- var segment = segments[pos];
- switch (segment) {
- case '':
- case '.':
- break;
- case '..':
- if (out.length > 0) {
- out.pop();
- }
- else {
- up++;
- }
- break;
- default:
- out.push(segment);
- }
- }
- if (leadingSlash == '') {
- while (up-- > 0) {
- out.unshift('..');
- }
- if (out.length === 0)
- out.push('.');
- }
- return leadingSlash + out.join('/') + trailingSlash;
- }
- /**
- * Takes an array of the parts from split and canonicalizes the path part
- * and then joins all the parts.
- * @param {Array.<string?>} parts
- * @return {string}
- */
- function _joinAndCanonicalizePath(parts) {
- var path = parts[_ComponentIndex.Path];
- path = lang_1.isBlank(path) ? '' : _removeDotSegments(path);
- parts[_ComponentIndex.Path] = path;
- return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
- }
- /**
- * Resolves a URL.
- * @param {string} base The URL acting as the base URL.
- * @param {string} to The URL to resolve.
- * @return {string}
- */
- function _resolveUrl(base, url) {
- var parts = _split(encodeURI(url));
- var baseParts = _split(base);
- if (lang_1.isPresent(parts[_ComponentIndex.Scheme])) {
- return _joinAndCanonicalizePath(parts);
- }
- else {
- parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
- }
- for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
- if (lang_1.isBlank(parts[i])) {
- parts[i] = baseParts[i];
- }
- }
- if (parts[_ComponentIndex.Path][0] == '/') {
- return _joinAndCanonicalizePath(parts);
- }
- var path = baseParts[_ComponentIndex.Path];
- if (lang_1.isBlank(path))
- path = '/';
- var index = path.lastIndexOf('/');
- path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
- parts[_ComponentIndex.Path] = path;
- return _joinAndCanonicalizePath(parts);
- }
- /***/ },
- /* 149 */
- /***/ function(module, exports) {
- // TODO: vsavkin rename it into TemplateLoader
- /**
- * An interface for retrieving documents by URL that the compiler uses
- * to load templates.
- */
- var XHR = (function () {
- function XHR() {
- }
- XHR.prototype.get = function (url) { return null; };
- return XHR;
- })();
- exports.XHR = XHR;
- /***/ },
- /* 150 */
- /***/ function(module, exports, __webpack_require__) {
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- var runtime_compiler_1 = __webpack_require__(151);
- var template_compiler_1 = __webpack_require__(152);
- exports.TemplateCompiler = template_compiler_1.TemplateCompiler;
- var directive_metadata_1 = __webpack_require__(153);
- exports.CompileDirectiveMetadata = directive_metadata_1.CompileDirectiveMetadata;
- exports.CompileTypeMetadata = directive_metadata_1.CompileTypeMetadata;
- exports.CompileTemplateMetadata = directive_metadata_1.CompileTemplateMetadata;
- var source_module_1 = __webpack_require__(156);
- exports.SourceModule = source_module_1.SourceModule;
- exports.SourceWithImports = source_module_1.SourceWithImports;
- var platform_directives_and_pipes_1 = __webpack_require__(95);
- exports.PLATFORM_DIRECTIVES = platform_directives_and_pipes_1.PLATFORM_DIRECTIVES;
- exports.PLATFORM_PIPES = platform_directives_and_pipes_1.PLATFORM_PIPES;
- __export(__webpack_require__(159));
- var template_parser_1 = __webpack_require__(167);
- exports.TEMPLATE_TRANSFORMS = template_parser_1.TEMPLATE_TRANSFORMS;
- var lang_1 = __webpack_require__(5);
- var di_1 = __webpack_require__(6);
- var template_parser_2 = __webpack_require__(167);
- var html_parser_1 = __webpack_require__(168);
- var template_normalizer_1 = __webpack_require__(175);
- var runtime_metadata_1 = __webpack_require__(176);
- var change_detector_compiler_1 = __webpack_require__(157);
- var style_compiler_1 = __webpack_require__(161);
- var command_compiler_1 = __webpack_require__(166);
- var template_compiler_2 = __webpack_require__(152);
- var change_detection_1 = __webpack_require__(25);
- var compiler_1 = __webpack_require__(70);
- var runtime_compiler_2 = __webpack_require__(151);
- var element_schema_registry_1 = __webpack_require__(173);
- var dom_element_schema_registry_1 = __webpack_require__(177);
- var url_resolver_1 = __webpack_require__(148);
- var change_detection_2 = __webpack_require__(25);
- function _createChangeDetectorGenConfig() {
- return new change_detection_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), false, true);
- }
- /**
- * A set of providers that provide `RuntimeCompiler` and its dependencies to use for
- * template compilation.
- */
- exports.COMPILER_PROVIDERS = lang_1.CONST_EXPR([
- change_detection_2.Lexer,
- change_detection_2.Parser,
- html_parser_1.HtmlParser,
- template_parser_2.TemplateParser,
- template_normalizer_1.TemplateNormalizer,
- runtime_metadata_1.RuntimeMetadataResolver,
- url_resolver_1.DEFAULT_PACKAGE_URL_PROVIDER,
- style_compiler_1.StyleCompiler,
- command_compiler_1.CommandCompiler,
- change_detector_compiler_1.ChangeDetectionCompiler,
- new di_1.Provider(change_detection_1.ChangeDetectorGenConfig, { useFactory: _createChangeDetectorGenConfig, deps: [] }),
- template_compiler_2.TemplateCompiler,
- new di_1.Provider(runtime_compiler_2.RuntimeCompiler, { useClass: runtime_compiler_1.RuntimeCompiler_ }),
- new di_1.Provider(compiler_1.Compiler, { useExisting: runtime_compiler_2.RuntimeCompiler }),
- dom_element_schema_registry_1.DomElementSchemaRegistry,
- new di_1.Provider(element_schema_registry_1.ElementSchemaRegistry, { useExisting: dom_element_schema_registry_1.DomElementSchemaRegistry }),
- url_resolver_1.UrlResolver
- ]);
- /***/ },
- /* 151 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var compiler_1 = __webpack_require__(70);
- var proto_view_factory_1 = __webpack_require__(71);
- var template_compiler_1 = __webpack_require__(152);
- var di_1 = __webpack_require__(6);
- var RuntimeCompiler = (function (_super) {
- __extends(RuntimeCompiler, _super);
- function RuntimeCompiler() {
- _super.apply(this, arguments);
- }
- return RuntimeCompiler;
- })(compiler_1.Compiler);
- exports.RuntimeCompiler = RuntimeCompiler;
- var RuntimeCompiler_ = (function (_super) {
- __extends(RuntimeCompiler_, _super);
- function RuntimeCompiler_(_protoViewFactory, _templateCompiler) {
- _super.call(this, _protoViewFactory);
- this._templateCompiler = _templateCompiler;
- }
- RuntimeCompiler_.prototype.compileInHost = function (componentType) {
- var _this = this;
- return this._templateCompiler.compileHostComponentRuntime(componentType)
- .then(function (compiledHostTemplate) { return compiler_1.internalCreateProtoView(_this, compiledHostTemplate); });
- };
- RuntimeCompiler_.prototype.clearCache = function () {
- _super.prototype.clearCache.call(this);
- this._templateCompiler.clearCache();
- };
- RuntimeCompiler_ = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [proto_view_factory_1.ProtoViewFactory, template_compiler_1.TemplateCompiler])
- ], RuntimeCompiler_);
- return RuntimeCompiler_;
- })(compiler_1.Compiler_);
- exports.RuntimeCompiler_ = RuntimeCompiler_;
- /***/ },
- /* 152 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var async_1 = __webpack_require__(60);
- var template_commands_1 = __webpack_require__(96);
- var directive_metadata_1 = __webpack_require__(153);
- var di_1 = __webpack_require__(6);
- var source_module_1 = __webpack_require__(156);
- var change_detector_compiler_1 = __webpack_require__(157);
- var style_compiler_1 = __webpack_require__(161);
- var command_compiler_1 = __webpack_require__(166);
- var template_parser_1 = __webpack_require__(167);
- var template_normalizer_1 = __webpack_require__(175);
- var runtime_metadata_1 = __webpack_require__(176);
- var command_compiler_2 = __webpack_require__(166);
- var util_1 = __webpack_require__(155);
- /**
- * An internal module of the Angular compiler that begins with component types,
- * extracts templates, and eventually produces a compiled version of the component
- * ready for linking into an application.
- */
- var TemplateCompiler = (function () {
- function TemplateCompiler(_runtimeMetadataResolver, _templateNormalizer, _templateParser, _styleCompiler, _commandCompiler, _cdCompiler) {
- this._runtimeMetadataResolver = _runtimeMetadataResolver;
- this._templateNormalizer = _templateNormalizer;
- this._templateParser = _templateParser;
- this._styleCompiler = _styleCompiler;
- this._commandCompiler = _commandCompiler;
- this._cdCompiler = _cdCompiler;
- this._hostCacheKeys = new Map();
- this._compiledTemplateCache = new Map();
- this._compiledTemplateDone = new Map();
- this._nextTemplateId = 0;
- }
- TemplateCompiler.prototype.normalizeDirectiveMetadata = function (directive) {
- if (!directive.isComponent) {
- // For non components there is nothing to be normalized yet.
- return async_1.PromiseWrapper.resolve(directive);
- }
- return this._templateNormalizer.normalizeTemplate(directive.type, directive.template)
- .then(function (normalizedTemplate) { return new directive_metadata_1.CompileDirectiveMetadata({
- type: directive.type,
- isComponent: directive.isComponent,
- dynamicLoadable: directive.dynamicLoadable,
- selector: directive.selector,
- exportAs: directive.exportAs,
- changeDetection: directive.changeDetection,
- inputs: directive.inputs,
- outputs: directive.outputs,
- hostListeners: directive.hostListeners,
- hostProperties: directive.hostProperties,
- hostAttributes: directive.hostAttributes,
- lifecycleHooks: directive.lifecycleHooks,
- template: normalizedTemplate
- }); });
- };
- TemplateCompiler.prototype.compileHostComponentRuntime = function (type) {
- var hostCacheKey = this._hostCacheKeys.get(type);
- if (lang_1.isBlank(hostCacheKey)) {
- hostCacheKey = new Object();
- this._hostCacheKeys.set(type, hostCacheKey);
- var compMeta = this._runtimeMetadataResolver.getMetadata(type);
- assertComponent(compMeta);
- var hostMeta = directive_metadata_1.createHostComponentMeta(compMeta.type, compMeta.selector);
- this._compileComponentRuntime(hostCacheKey, hostMeta, [compMeta], new Set());
- }
- return this._compiledTemplateDone.get(hostCacheKey)
- .then(function (compiledTemplate) { return new template_commands_1.CompiledHostTemplate(compiledTemplate); });
- };
- TemplateCompiler.prototype.clearCache = function () {
- this._hostCacheKeys.clear();
- this._styleCompiler.clearCache();
- this._compiledTemplateCache.clear();
- this._compiledTemplateDone.clear();
- };
- TemplateCompiler.prototype._compileComponentRuntime = function (cacheKey, compMeta, viewDirectives, compilingComponentCacheKeys) {
- var _this = this;
- var uniqViewDirectives = removeDuplicates(viewDirectives);
- var compiledTemplate = this._compiledTemplateCache.get(cacheKey);
- var done = this._compiledTemplateDone.get(cacheKey);
- if (lang_1.isBlank(compiledTemplate)) {
- var styles = [];
- var changeDetectorFactory;
- var commands = [];
- var templateId = lang_1.stringify(compMeta.type.runtime) + "Template" + this._nextTemplateId++;
- compiledTemplate = new template_commands_1.CompiledComponentTemplate(templateId, function (dispatcher) { return changeDetectorFactory(dispatcher); }, commands, styles);
- this._compiledTemplateCache.set(cacheKey, compiledTemplate);
- compilingComponentCacheKeys.add(cacheKey);
- done = async_1.PromiseWrapper
- .all([this._styleCompiler.compileComponentRuntime(compMeta.template)].concat(uniqViewDirectives.map(function (dirMeta) { return _this.normalizeDirectiveMetadata(dirMeta); })))
- .then(function (stylesAndNormalizedViewDirMetas) {
- var childPromises = [];
- var normalizedViewDirMetas = stylesAndNormalizedViewDirMetas.slice(1);
- var parsedTemplate = _this._templateParser.parse(compMeta.template.template, normalizedViewDirMetas, compMeta.type.name);
- var changeDetectorFactories = _this._cdCompiler.compileComponentRuntime(compMeta.type, compMeta.changeDetection, parsedTemplate);
- changeDetectorFactory = changeDetectorFactories[0];
- var tmpStyles = stylesAndNormalizedViewDirMetas[0];
- tmpStyles.forEach(function (style) { return styles.push(style); });
- var tmpCommands = _this._compileCommandsRuntime(compMeta, parsedTemplate, changeDetectorFactories, compilingComponentCacheKeys, childPromises);
- tmpCommands.forEach(function (cmd) { return commands.push(cmd); });
- return async_1.PromiseWrapper.all(childPromises);
- })
- .then(function (_) {
- collection_1.SetWrapper.delete(compilingComponentCacheKeys, cacheKey);
- return compiledTemplate;
- });
- this._compiledTemplateDone.set(cacheKey, done);
- }
- return compiledTemplate;
- };
- TemplateCompiler.prototype._compileCommandsRuntime = function (compMeta, parsedTemplate, changeDetectorFactories, compilingComponentCacheKeys, childPromises) {
- var _this = this;
- var cmds = this._commandCompiler.compileComponentRuntime(compMeta, parsedTemplate, changeDetectorFactories, function (childComponentDir) {
- var childCacheKey = childComponentDir.type.runtime;
- var childViewDirectives = _this._runtimeMetadataResolver.getViewDirectivesMetadata(childComponentDir.type.runtime);
- var childIsRecursive = collection_1.SetWrapper.has(compilingComponentCacheKeys, childCacheKey);
- var childTemplate = _this._compileComponentRuntime(childCacheKey, childComponentDir, childViewDirectives, compilingComponentCacheKeys);
- if (!childIsRecursive) {
- // Only wait for a child if it is not a cycle
- childPromises.push(_this._compiledTemplateDone.get(childCacheKey));
- }
- return function () { return childTemplate; };
- });
- cmds.forEach(function (cmd) {
- if (cmd instanceof template_commands_1.BeginComponentCmd) {
- cmd.templateGetter();
- }
- });
- return cmds;
- };
- TemplateCompiler.prototype.compileTemplatesCodeGen = function (components) {
- var _this = this;
- if (components.length === 0) {
- throw new exceptions_1.BaseException('No components given');
- }
- var declarations = [];
- var templateArguments = [];
- var componentMetas = [];
- components.forEach(function (componentWithDirs) {
- var compMeta = componentWithDirs.component;
- assertComponent(compMeta);
- componentMetas.push(compMeta);
- _this._processTemplateCodeGen(compMeta, componentWithDirs.directives, declarations, templateArguments);
- if (compMeta.dynamicLoadable) {
- var hostMeta = directive_metadata_1.createHostComponentMeta(compMeta.type, compMeta.selector);
- componentMetas.push(hostMeta);
- _this._processTemplateCodeGen(hostMeta, [compMeta], declarations, templateArguments);
- }
- });
- collection_1.ListWrapper.forEachWithIndex(componentMetas, function (compMeta, index) {
- var templateId = compMeta.type.moduleUrl + "|" + compMeta.type.name;
- var constructionKeyword = lang_1.IS_DART ? 'const' : 'new';
- var compiledTemplateExpr = constructionKeyword + " " + command_compiler_2.TEMPLATE_COMMANDS_MODULE_REF + "CompiledComponentTemplate('" + templateId + "'," + templateArguments[index].join(',') + ")";
- var variableValueExpr;
- if (compMeta.type.isHost) {
- variableValueExpr =
- constructionKeyword + " " + command_compiler_2.TEMPLATE_COMMANDS_MODULE_REF + "CompiledHostTemplate(" + compiledTemplateExpr + ")";
- }
- else {
- variableValueExpr = compiledTemplateExpr;
- }
- var varName = templateVariableName(compMeta.type);
- declarations.push("" + util_1.codeGenExportVariable(varName) + variableValueExpr + ";");
- declarations.push(util_1.codeGenValueFn([], varName, templateGetterName(compMeta.type)) + ";");
- });
- var moduleUrl = components[0].component.type.moduleUrl;
- return new source_module_1.SourceModule("" + templateModuleUrl(moduleUrl), declarations.join('\n'));
- };
- TemplateCompiler.prototype.compileStylesheetCodeGen = function (stylesheetUrl, cssText) {
- return this._styleCompiler.compileStylesheetCodeGen(stylesheetUrl, cssText);
- };
- TemplateCompiler.prototype._processTemplateCodeGen = function (compMeta, directives, targetDeclarations, targetTemplateArguments) {
- var uniqueDirectives = removeDuplicates(directives);
- var styleExpr = this._styleCompiler.compileComponentCodeGen(compMeta.template);
- var parsedTemplate = this._templateParser.parse(compMeta.template.template, uniqueDirectives, compMeta.type.name);
- var changeDetectorsExprs = this._cdCompiler.compileComponentCodeGen(compMeta.type, compMeta.changeDetection, parsedTemplate);
- var commandsExpr = this._commandCompiler.compileComponentCodeGen(compMeta, parsedTemplate, changeDetectorsExprs.expressions, codeGenComponentTemplateFactory);
- addAll(styleExpr.declarations, targetDeclarations);
- addAll(changeDetectorsExprs.declarations, targetDeclarations);
- addAll(commandsExpr.declarations, targetDeclarations);
- targetTemplateArguments.push([changeDetectorsExprs.expressions[0], commandsExpr.expression, styleExpr.expression]);
- };
- TemplateCompiler = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [runtime_metadata_1.RuntimeMetadataResolver, template_normalizer_1.TemplateNormalizer, template_parser_1.TemplateParser, style_compiler_1.StyleCompiler, command_compiler_1.CommandCompiler, change_detector_compiler_1.ChangeDetectionCompiler])
- ], TemplateCompiler);
- return TemplateCompiler;
- })();
- exports.TemplateCompiler = TemplateCompiler;
- var NormalizedComponentWithViewDirectives = (function () {
- function NormalizedComponentWithViewDirectives(component, directives) {
- this.component = component;
- this.directives = directives;
- }
- return NormalizedComponentWithViewDirectives;
- })();
- exports.NormalizedComponentWithViewDirectives = NormalizedComponentWithViewDirectives;
- function assertComponent(meta) {
- if (!meta.isComponent) {
- throw new exceptions_1.BaseException("Could not compile '" + meta.type.name + "' because it is not a component.");
- }
- }
- function templateVariableName(type) {
- return type.name + "Template";
- }
- function templateGetterName(type) {
- return templateVariableName(type) + "Getter";
- }
- function templateModuleUrl(moduleUrl) {
- var urlWithoutSuffix = moduleUrl.substring(0, moduleUrl.length - util_1.MODULE_SUFFIX.length);
- return urlWithoutSuffix + ".template" + util_1.MODULE_SUFFIX;
- }
- function addAll(source, target) {
- for (var i = 0; i < source.length; i++) {
- target.push(source[i]);
- }
- }
- function codeGenComponentTemplateFactory(nestedCompType) {
- return "" + source_module_1.moduleRef(templateModuleUrl(nestedCompType.type.moduleUrl)) + templateGetterName(nestedCompType.type);
- }
- function removeDuplicates(items) {
- var res = [];
- items.forEach(function (item) {
- var hasMatch = res.filter(function (r) { return r.type.name == item.type.name && r.type.moduleUrl == item.type.moduleUrl &&
- r.type.runtime == item.type.runtime; })
- .length > 0;
- if (!hasMatch) {
- res.push(item);
- }
- });
- return res;
- }
- /***/ },
- /* 153 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var change_detection_1 = __webpack_require__(25);
- var view_1 = __webpack_require__(56);
- var selector_1 = __webpack_require__(154);
- var util_1 = __webpack_require__(155);
- var interfaces_1 = __webpack_require__(89);
- // group 1: "property" from "[property]"
- // group 2: "event" from "(event)"
- var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))$/g;
- /**
- * Metadata regarding compilation of a type.
- */
- var CompileTypeMetadata = (function () {
- function CompileTypeMetadata(_a) {
- var _b = _a === void 0 ? {} : _a, runtime = _b.runtime, name = _b.name, moduleUrl = _b.moduleUrl, isHost = _b.isHost;
- this.runtime = runtime;
- this.name = name;
- this.moduleUrl = moduleUrl;
- this.isHost = lang_1.normalizeBool(isHost);
- }
- CompileTypeMetadata.fromJson = function (data) {
- return new CompileTypeMetadata({ name: data['name'], moduleUrl: data['moduleUrl'], isHost: data['isHost'] });
- };
- CompileTypeMetadata.prototype.toJson = function () {
- return {
- // Note: Runtime type can't be serialized...
- 'name': this.name,
- 'moduleUrl': this.moduleUrl,
- 'isHost': this.isHost
- };
- };
- return CompileTypeMetadata;
- })();
- exports.CompileTypeMetadata = CompileTypeMetadata;
- /**
- * Metadata regarding compilation of a template.
- */
- var CompileTemplateMetadata = (function () {
- function CompileTemplateMetadata(_a) {
- var _b = _a === void 0 ? {} : _a, encapsulation = _b.encapsulation, template = _b.template, templateUrl = _b.templateUrl, styles = _b.styles, styleUrls = _b.styleUrls, ngContentSelectors = _b.ngContentSelectors;
- this.encapsulation = lang_1.isPresent(encapsulation) ? encapsulation : view_1.ViewEncapsulation.Emulated;
- this.template = template;
- this.templateUrl = templateUrl;
- this.styles = lang_1.isPresent(styles) ? styles : [];
- this.styleUrls = lang_1.isPresent(styleUrls) ? styleUrls : [];
- this.ngContentSelectors = lang_1.isPresent(ngContentSelectors) ? ngContentSelectors : [];
- }
- CompileTemplateMetadata.fromJson = function (data) {
- return new CompileTemplateMetadata({
- encapsulation: lang_1.isPresent(data['encapsulation']) ?
- view_1.VIEW_ENCAPSULATION_VALUES[data['encapsulation']] :
- data['encapsulation'],
- template: data['template'],
- templateUrl: data['templateUrl'],
- styles: data['styles'],
- styleUrls: data['styleUrls'],
- ngContentSelectors: data['ngContentSelectors']
- });
- };
- CompileTemplateMetadata.prototype.toJson = function () {
- return {
- 'encapsulation': lang_1.isPresent(this.encapsulation) ? lang_1.serializeEnum(this.encapsulation) : this.encapsulation,
- 'template': this.template,
- 'templateUrl': this.templateUrl,
- 'styles': this.styles,
- 'styleUrls': this.styleUrls,
- 'ngContentSelectors': this.ngContentSelectors
- };
- };
- return CompileTemplateMetadata;
- })();
- exports.CompileTemplateMetadata = CompileTemplateMetadata;
- /**
- * Metadata regarding compilation of a directive.
- */
- var CompileDirectiveMetadata = (function () {
- function CompileDirectiveMetadata(_a) {
- var _b = _a === void 0 ? {} : _a, type = _b.type, isComponent = _b.isComponent, dynamicLoadable = _b.dynamicLoadable, selector = _b.selector, exportAs = _b.exportAs, changeDetection = _b.changeDetection, inputs = _b.inputs, outputs = _b.outputs, hostListeners = _b.hostListeners, hostProperties = _b.hostProperties, hostAttributes = _b.hostAttributes, lifecycleHooks = _b.lifecycleHooks, template = _b.template;
- this.type = type;
- this.isComponent = isComponent;
- this.dynamicLoadable = dynamicLoadable;
- this.selector = selector;
- this.exportAs = exportAs;
- this.changeDetection = changeDetection;
- this.inputs = inputs;
- this.outputs = outputs;
- this.hostListeners = hostListeners;
- this.hostProperties = hostProperties;
- this.hostAttributes = hostAttributes;
- this.lifecycleHooks = lifecycleHooks;
- this.template = template;
- }
- CompileDirectiveMetadata.create = function (_a) {
- var _b = _a === void 0 ? {} : _a, type = _b.type, isComponent = _b.isComponent, dynamicLoadable = _b.dynamicLoadable, selector = _b.selector, exportAs = _b.exportAs, changeDetection = _b.changeDetection, inputs = _b.inputs, outputs = _b.outputs, host = _b.host, lifecycleHooks = _b.lifecycleHooks, template = _b.template;
- var hostListeners = {};
- var hostProperties = {};
- var hostAttributes = {};
- if (lang_1.isPresent(host)) {
- collection_1.StringMapWrapper.forEach(host, function (value, key) {
- var matches = lang_1.RegExpWrapper.firstMatch(HOST_REG_EXP, key);
- if (lang_1.isBlank(matches)) {
- hostAttributes[key] = value;
- }
- else if (lang_1.isPresent(matches[1])) {
- hostProperties[matches[1]] = value;
- }
- else if (lang_1.isPresent(matches[2])) {
- hostListeners[matches[2]] = value;
- }
- });
- }
- var inputsMap = {};
- if (lang_1.isPresent(inputs)) {
- inputs.forEach(function (bindConfig) {
- // canonical syntax: `dirProp: elProp`
- // if there is no `:`, use dirProp = elProp
- var parts = util_1.splitAtColon(bindConfig, [bindConfig, bindConfig]);
- inputsMap[parts[0]] = parts[1];
- });
- }
- var outputsMap = {};
- if (lang_1.isPresent(outputs)) {
- outputs.forEach(function (bindConfig) {
- // canonical syntax: `dirProp: elProp`
- // if there is no `:`, use dirProp = elProp
- var parts = util_1.splitAtColon(bindConfig, [bindConfig, bindConfig]);
- outputsMap[parts[0]] = parts[1];
- });
- }
- return new CompileDirectiveMetadata({
- type: type,
- isComponent: lang_1.normalizeBool(isComponent),
- dynamicLoadable: lang_1.normalizeBool(dynamicLoadable),
- selector: selector,
- exportAs: exportAs,
- changeDetection: changeDetection,
- inputs: inputsMap,
- outputs: outputsMap,
- hostListeners: hostListeners,
- hostProperties: hostProperties,
- hostAttributes: hostAttributes,
- lifecycleHooks: lang_1.isPresent(lifecycleHooks) ? lifecycleHooks : [],
- template: template
- });
- };
- CompileDirectiveMetadata.fromJson = function (data) {
- return new CompileDirectiveMetadata({
- isComponent: data['isComponent'],
- dynamicLoadable: data['dynamicLoadable'],
- selector: data['selector'],
- exportAs: data['exportAs'],
- type: lang_1.isPresent(data['type']) ? CompileTypeMetadata.fromJson(data['type']) : data['type'],
- changeDetection: lang_1.isPresent(data['changeDetection']) ?
- change_detection_1.CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] :
- data['changeDetection'],
- inputs: data['inputs'],
- outputs: data['outputs'],
- hostListeners: data['hostListeners'],
- hostProperties: data['hostProperties'],
- hostAttributes: data['hostAttributes'],
- lifecycleHooks: data['lifecycleHooks'].map(function (hookValue) { return interfaces_1.LIFECYCLE_HOOKS_VALUES[hookValue]; }),
- template: lang_1.isPresent(data['template']) ? CompileTemplateMetadata.fromJson(data['template']) :
- data['template']
- });
- };
- CompileDirectiveMetadata.prototype.toJson = function () {
- return {
- 'isComponent': this.isComponent,
- 'dynamicLoadable': this.dynamicLoadable,
- 'selector': this.selector,
- 'exportAs': this.exportAs,
- 'type': lang_1.isPresent(this.type) ? this.type.toJson() : this.type,
- 'changeDetection': lang_1.isPresent(this.changeDetection) ? lang_1.serializeEnum(this.changeDetection) :
- this.changeDetection,
- 'inputs': this.inputs,
- 'outputs': this.outputs,
- 'hostListeners': this.hostListeners,
- 'hostProperties': this.hostProperties,
- 'hostAttributes': this.hostAttributes,
- 'lifecycleHooks': this.lifecycleHooks.map(function (hook) { return lang_1.serializeEnum(hook); }),
- 'template': lang_1.isPresent(this.template) ? this.template.toJson() : this.template
- };
- };
- return CompileDirectiveMetadata;
- })();
- exports.CompileDirectiveMetadata = CompileDirectiveMetadata;
- /**
- * Construct {@link CompileDirectiveMetadata} from {@link ComponentTypeMetadata} and a selector.
- */
- function createHostComponentMeta(componentType, componentSelector) {
- var template = selector_1.CssSelector.parse(componentSelector)[0].getMatchingElementTemplate();
- return CompileDirectiveMetadata.create({
- type: new CompileTypeMetadata({
- runtime: Object,
- name: "Host" + componentType.name,
- moduleUrl: componentType.moduleUrl,
- isHost: true
- }),
- template: new CompileTemplateMetadata({ template: template, templateUrl: '', styles: [], styleUrls: [], ngContentSelectors: [] }),
- changeDetection: change_detection_1.ChangeDetectionStrategy.Default,
- inputs: [],
- outputs: [],
- host: {},
- lifecycleHooks: [],
- isComponent: true,
- dynamicLoadable: false,
- selector: '*'
- });
- }
- exports.createHostComponentMeta = createHostComponentMeta;
- /***/ },
- /* 154 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var _EMPTY_ATTR_VALUE = '';
- // TODO: Can't use `const` here as
- // in Dart this is not transpiled into `final` yet...
- var _SELECTOR_REGEXP = lang_1.RegExpWrapper.create('(\\:not\\()|' +
- '([-\\w]+)|' +
- '(?:\\.([-\\w]+))|' +
- '(?:\\[([-\\w*]+)(?:=([^\\]]*))?\\])|' +
- '(\\))|' +
- '(\\s*,\\s*)'); // ","
- /**
- * A css selector contains an element name,
- * css classes and attribute/value pairs with the purpose
- * of selecting subsets out of them.
- */
- var CssSelector = (function () {
- function CssSelector() {
- this.element = null;
- this.classNames = [];
- this.attrs = [];
- this.notSelectors = [];
- }
- CssSelector.parse = function (selector) {
- var results = [];
- var _addResult = function (res, cssSel) {
- if (cssSel.notSelectors.length > 0 && lang_1.isBlank(cssSel.element) &&
- collection_1.ListWrapper.isEmpty(cssSel.classNames) && collection_1.ListWrapper.isEmpty(cssSel.attrs)) {
- cssSel.element = "*";
- }
- res.push(cssSel);
- };
- var cssSelector = new CssSelector();
- var matcher = lang_1.RegExpWrapper.matcher(_SELECTOR_REGEXP, selector);
- var match;
- var current = cssSelector;
- var inNot = false;
- while (lang_1.isPresent(match = lang_1.RegExpMatcherWrapper.next(matcher))) {
- if (lang_1.isPresent(match[1])) {
- if (inNot) {
- throw new exceptions_1.BaseException('Nesting :not is not allowed in a selector');
- }
- inNot = true;
- current = new CssSelector();
- cssSelector.notSelectors.push(current);
- }
- if (lang_1.isPresent(match[2])) {
- current.setElement(match[2]);
- }
- if (lang_1.isPresent(match[3])) {
- current.addClassName(match[3]);
- }
- if (lang_1.isPresent(match[4])) {
- current.addAttribute(match[4], match[5]);
- }
- if (lang_1.isPresent(match[6])) {
- inNot = false;
- current = cssSelector;
- }
- if (lang_1.isPresent(match[7])) {
- if (inNot) {
- throw new exceptions_1.BaseException('Multiple selectors in :not are not supported');
- }
- _addResult(results, cssSelector);
- cssSelector = current = new CssSelector();
- }
- }
- _addResult(results, cssSelector);
- return results;
- };
- CssSelector.prototype.isElementSelector = function () {
- return lang_1.isPresent(this.element) && collection_1.ListWrapper.isEmpty(this.classNames) &&
- collection_1.ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0;
- };
- CssSelector.prototype.setElement = function (element) {
- if (element === void 0) { element = null; }
- this.element = element;
- };
- /** Gets a template string for an element that matches the selector. */
- CssSelector.prototype.getMatchingElementTemplate = function () {
- var tagName = lang_1.isPresent(this.element) ? this.element : 'div';
- var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
- var attrs = '';
- for (var i = 0; i < this.attrs.length; i += 2) {
- var attrName = this.attrs[i];
- var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
- attrs += " " + attrName + attrValue;
- }
- return "<" + tagName + classAttr + attrs + "></" + tagName + ">";
- };
- CssSelector.prototype.addAttribute = function (name, value) {
- if (value === void 0) { value = _EMPTY_ATTR_VALUE; }
- this.attrs.push(name);
- if (lang_1.isPresent(value)) {
- value = value.toLowerCase();
- }
- else {
- value = _EMPTY_ATTR_VALUE;
- }
- this.attrs.push(value);
- };
- CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
- CssSelector.prototype.toString = function () {
- var res = '';
- if (lang_1.isPresent(this.element)) {
- res += this.element;
- }
- if (lang_1.isPresent(this.classNames)) {
- for (var i = 0; i < this.classNames.length; i++) {
- res += '.' + this.classNames[i];
- }
- }
- if (lang_1.isPresent(this.attrs)) {
- for (var i = 0; i < this.attrs.length;) {
- var attrName = this.attrs[i++];
- var attrValue = this.attrs[i++];
- res += '[' + attrName;
- if (attrValue.length > 0) {
- res += '=' + attrValue;
- }
- res += ']';
- }
- }
- this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
- return res;
- };
- return CssSelector;
- })();
- exports.CssSelector = CssSelector;
- /**
- * Reads a list of CssSelectors and allows to calculate which ones
- * are contained in a given CssSelector.
- */
- var SelectorMatcher = (function () {
- function SelectorMatcher() {
- this._elementMap = new collection_1.Map();
- this._elementPartialMap = new collection_1.Map();
- this._classMap = new collection_1.Map();
- this._classPartialMap = new collection_1.Map();
- this._attrValueMap = new collection_1.Map();
- this._attrValuePartialMap = new collection_1.Map();
- this._listContexts = [];
- }
- SelectorMatcher.createNotMatcher = function (notSelectors) {
- var notMatcher = new SelectorMatcher();
- notMatcher.addSelectables(notSelectors, null);
- return notMatcher;
- };
- SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
- var listContext = null;
- if (cssSelectors.length > 1) {
- listContext = new SelectorListContext(cssSelectors);
- this._listContexts.push(listContext);
- }
- for (var i = 0; i < cssSelectors.length; i++) {
- this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
- }
- };
- /**
- * Add an object that can be found later on by calling `match`.
- * @param cssSelector A css selector
- * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
- */
- SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
- var matcher = this;
- var element = cssSelector.element;
- var classNames = cssSelector.classNames;
- var attrs = cssSelector.attrs;
- var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
- if (lang_1.isPresent(element)) {
- var isTerminal = attrs.length === 0 && classNames.length === 0;
- if (isTerminal) {
- this._addTerminal(matcher._elementMap, element, selectable);
- }
- else {
- matcher = this._addPartial(matcher._elementPartialMap, element);
- }
- }
- if (lang_1.isPresent(classNames)) {
- for (var index = 0; index < classNames.length; index++) {
- var isTerminal = attrs.length === 0 && index === classNames.length - 1;
- var className = classNames[index];
- if (isTerminal) {
- this._addTerminal(matcher._classMap, className, selectable);
- }
- else {
- matcher = this._addPartial(matcher._classPartialMap, className);
- }
- }
- }
- if (lang_1.isPresent(attrs)) {
- for (var index = 0; index < attrs.length;) {
- var isTerminal = index === attrs.length - 2;
- var attrName = attrs[index++];
- var attrValue = attrs[index++];
- if (isTerminal) {
- var terminalMap = matcher._attrValueMap;
- var terminalValuesMap = terminalMap.get(attrName);
- if (lang_1.isBlank(terminalValuesMap)) {
- terminalValuesMap = new collection_1.Map();
- terminalMap.set(attrName, terminalValuesMap);
- }
- this._addTerminal(terminalValuesMap, attrValue, selectable);
- }
- else {
- var parttialMap = matcher._attrValuePartialMap;
- var partialValuesMap = parttialMap.get(attrName);
- if (lang_1.isBlank(partialValuesMap)) {
- partialValuesMap = new collection_1.Map();
- parttialMap.set(attrName, partialValuesMap);
- }
- matcher = this._addPartial(partialValuesMap, attrValue);
- }
- }
- }
- };
- SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
- var terminalList = map.get(name);
- if (lang_1.isBlank(terminalList)) {
- terminalList = [];
- map.set(name, terminalList);
- }
- terminalList.push(selectable);
- };
- SelectorMatcher.prototype._addPartial = function (map, name) {
- var matcher = map.get(name);
- if (lang_1.isBlank(matcher)) {
- matcher = new SelectorMatcher();
- map.set(name, matcher);
- }
- return matcher;
- };
- /**
- * Find the objects that have been added via `addSelectable`
- * whose css selector is contained in the given css selector.
- * @param cssSelector A css selector
- * @param matchedCallback This callback will be called with the object handed into `addSelectable`
- * @return boolean true if a match was found
- */
- SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
- var result = false;
- var element = cssSelector.element;
- var classNames = cssSelector.classNames;
- var attrs = cssSelector.attrs;
- for (var i = 0; i < this._listContexts.length; i++) {
- this._listContexts[i].alreadyMatched = false;
- }
- result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
- result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
- result;
- if (lang_1.isPresent(classNames)) {
- for (var index = 0; index < classNames.length; index++) {
- var className = classNames[index];
- result =
- this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
- result =
- this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
- result;
- }
- }
- if (lang_1.isPresent(attrs)) {
- for (var index = 0; index < attrs.length;) {
- var attrName = attrs[index++];
- var attrValue = attrs[index++];
- var terminalValuesMap = this._attrValueMap.get(attrName);
- if (!lang_1.StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) {
- result = this._matchTerminal(terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) ||
- result;
- }
- result = this._matchTerminal(terminalValuesMap, attrValue, cssSelector, matchedCallback) ||
- result;
- var partialValuesMap = this._attrValuePartialMap.get(attrName);
- if (!lang_1.StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) {
- result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) ||
- result;
- }
- result =
- this._matchPartial(partialValuesMap, attrValue, cssSelector, matchedCallback) || result;
- }
- }
- return result;
- };
- /** @internal */
- SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
- if (lang_1.isBlank(map) || lang_1.isBlank(name)) {
- return false;
- }
- var selectables = map.get(name);
- var starSelectables = map.get("*");
- if (lang_1.isPresent(starSelectables)) {
- selectables = selectables.concat(starSelectables);
- }
- if (lang_1.isBlank(selectables)) {
- return false;
- }
- var selectable;
- var result = false;
- for (var index = 0; index < selectables.length; index++) {
- selectable = selectables[index];
- result = selectable.finalize(cssSelector, matchedCallback) || result;
- }
- return result;
- };
- /** @internal */
- SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback /*: (c: CssSelector, a: any) => void*/) {
- if (lang_1.isBlank(map) || lang_1.isBlank(name)) {
- return false;
- }
- var nestedSelector = map.get(name);
- if (lang_1.isBlank(nestedSelector)) {
- return false;
- }
- // TODO(perf): get rid of recursion and measure again
- // TODO(perf): don't pass the whole selector into the recursion,
- // but only the not processed parts
- return nestedSelector.match(cssSelector, matchedCallback);
- };
- return SelectorMatcher;
- })();
- exports.SelectorMatcher = SelectorMatcher;
- var SelectorListContext = (function () {
- function SelectorListContext(selectors) {
- this.selectors = selectors;
- this.alreadyMatched = false;
- }
- return SelectorListContext;
- })();
- exports.SelectorListContext = SelectorListContext;
- // Store context to pass back selector and context when a selector is matched
- var SelectorContext = (function () {
- function SelectorContext(selector, cbContext, listContext) {
- this.selector = selector;
- this.cbContext = cbContext;
- this.listContext = listContext;
- this.notSelectors = selector.notSelectors;
- }
- SelectorContext.prototype.finalize = function (cssSelector, callback) {
- var result = true;
- if (this.notSelectors.length > 0 &&
- (lang_1.isBlank(this.listContext) || !this.listContext.alreadyMatched)) {
- var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
- result = !notMatcher.match(cssSelector, null);
- }
- if (result && lang_1.isPresent(callback) &&
- (lang_1.isBlank(this.listContext) || !this.listContext.alreadyMatched)) {
- if (lang_1.isPresent(this.listContext)) {
- this.listContext.alreadyMatched = true;
- }
- callback(this.selector, this.cbContext);
- }
- return result;
- };
- return SelectorContext;
- })();
- exports.SelectorContext = SelectorContext;
- /***/ },
- /* 155 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var CAMEL_CASE_REGEXP = /([A-Z])/g;
- var DASH_CASE_REGEXP = /-([a-z])/g;
- var SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
- var DOUBLE_QUOTE_ESCAPE_STRING_RE = /"|\\|\n|\r|\$/g;
- exports.MODULE_SUFFIX = lang_1.IS_DART ? '.dart' : '.js';
- function camelCaseToDashCase(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function (m) { return '-' + m[1].toLowerCase(); });
- }
- exports.camelCaseToDashCase = camelCaseToDashCase;
- function dashCaseToCamelCase(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function (m) { return m[1].toUpperCase(); });
- }
- exports.dashCaseToCamelCase = dashCaseToCamelCase;
- function escapeSingleQuoteString(input) {
- if (lang_1.isBlank(input)) {
- return null;
- }
- return "'" + escapeString(input, SINGLE_QUOTE_ESCAPE_STRING_RE) + "'";
- }
- exports.escapeSingleQuoteString = escapeSingleQuoteString;
- function escapeDoubleQuoteString(input) {
- if (lang_1.isBlank(input)) {
- return null;
- }
- return "\"" + escapeString(input, DOUBLE_QUOTE_ESCAPE_STRING_RE) + "\"";
- }
- exports.escapeDoubleQuoteString = escapeDoubleQuoteString;
- function escapeString(input, re) {
- return lang_1.StringWrapper.replaceAllMapped(input, re, function (match) {
- if (match[0] == '$') {
- return lang_1.IS_DART ? '\\$' : '$';
- }
- else if (match[0] == '\n') {
- return '\\n';
- }
- else if (match[0] == '\r') {
- return '\\r';
- }
- else {
- return "\\" + match[0];
- }
- });
- }
- function codeGenExportVariable(name) {
- if (lang_1.IS_DART) {
- return "const " + name + " = ";
- }
- else {
- return "var " + name + " = exports['" + name + "'] = ";
- }
- }
- exports.codeGenExportVariable = codeGenExportVariable;
- function codeGenConstConstructorCall(name) {
- if (lang_1.IS_DART) {
- return "const " + name;
- }
- else {
- return "new " + name;
- }
- }
- exports.codeGenConstConstructorCall = codeGenConstConstructorCall;
- function codeGenValueFn(params, value, fnName) {
- if (fnName === void 0) { fnName = ''; }
- if (lang_1.IS_DART) {
- return fnName + "(" + params.join(',') + ") => " + value;
- }
- else {
- return "function " + fnName + "(" + params.join(',') + ") { return " + value + "; }";
- }
- }
- exports.codeGenValueFn = codeGenValueFn;
- function codeGenToString(expr) {
- if (lang_1.IS_DART) {
- return "'${" + expr + "}'";
- }
- else {
- // JS automatically convets to string...
- return expr;
- }
- }
- exports.codeGenToString = codeGenToString;
- function splitAtColon(input, defaultValues) {
- var parts = lang_1.StringWrapper.split(input.trim(), /\s*:\s*/g);
- if (parts.length > 1) {
- return parts;
- }
- else {
- return defaultValues;
- }
- }
- exports.splitAtColon = splitAtColon;
- /***/ },
- /* 156 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var MODULE_REGEXP = /#MODULE\[([^\]]*)\]/g;
- function moduleRef(moduleUrl) {
- return "#MODULE[" + moduleUrl + "]";
- }
- exports.moduleRef = moduleRef;
- /**
- * Represents generated source code with module references. Internal to the Angular compiler.
- */
- var SourceModule = (function () {
- function SourceModule(moduleUrl, sourceWithModuleRefs) {
- this.moduleUrl = moduleUrl;
- this.sourceWithModuleRefs = sourceWithModuleRefs;
- }
- SourceModule.prototype.getSourceWithImports = function () {
- var _this = this;
- var moduleAliases = {};
- var imports = [];
- var newSource = lang_1.StringWrapper.replaceAllMapped(this.sourceWithModuleRefs, MODULE_REGEXP, function (match) {
- var moduleUrl = match[1];
- var alias = moduleAliases[moduleUrl];
- if (lang_1.isBlank(alias)) {
- if (moduleUrl == _this.moduleUrl) {
- alias = '';
- }
- else {
- alias = "import" + imports.length;
- imports.push([moduleUrl, alias]);
- }
- moduleAliases[moduleUrl] = alias;
- }
- return alias.length > 0 ? alias + "." : '';
- });
- return new SourceWithImports(newSource, imports);
- };
- return SourceModule;
- })();
- exports.SourceModule = SourceModule;
- var SourceExpression = (function () {
- function SourceExpression(declarations, expression) {
- this.declarations = declarations;
- this.expression = expression;
- }
- return SourceExpression;
- })();
- exports.SourceExpression = SourceExpression;
- var SourceExpressions = (function () {
- function SourceExpressions(declarations, expressions) {
- this.declarations = declarations;
- this.expressions = expressions;
- }
- return SourceExpressions;
- })();
- exports.SourceExpressions = SourceExpressions;
- /**
- * Represents generated source code with imports. Internal to the Angular compiler.
- */
- var SourceWithImports = (function () {
- function SourceWithImports(source, imports) {
- this.source = source;
- this.imports = imports;
- }
- return SourceWithImports;
- })();
- exports.SourceWithImports = SourceWithImports;
- /***/ },
- /* 157 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var source_module_1 = __webpack_require__(156);
- var change_detection_jit_generator_1 = __webpack_require__(52);
- var change_definition_factory_1 = __webpack_require__(158);
- var lang_1 = __webpack_require__(5);
- var change_detection_1 = __webpack_require__(25);
- var change_detector_codegen_1 = __webpack_require__(160);
- var util_1 = __webpack_require__(155);
- var di_1 = __webpack_require__(6);
- var ABSTRACT_CHANGE_DETECTOR = "AbstractChangeDetector";
- var UTIL = "ChangeDetectionUtil";
- var CHANGE_DETECTOR_STATE = "ChangeDetectorState";
- var ABSTRACT_CHANGE_DETECTOR_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/abstract_change_detector" + util_1.MODULE_SUFFIX);
- var UTIL_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/change_detection_util" + util_1.MODULE_SUFFIX);
- var PREGEN_PROTO_CHANGE_DETECTOR_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/pregen_proto_change_detector" + util_1.MODULE_SUFFIX);
- var CONSTANTS_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/constants" + util_1.MODULE_SUFFIX);
- var ChangeDetectionCompiler = (function () {
- function ChangeDetectionCompiler(_genConfig) {
- this._genConfig = _genConfig;
- }
- ChangeDetectionCompiler.prototype.compileComponentRuntime = function (componentType, strategy, parsedTemplate) {
- var _this = this;
- var changeDetectorDefinitions = change_definition_factory_1.createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate);
- return changeDetectorDefinitions.map(function (definition) {
- return _this._createChangeDetectorFactory(definition);
- });
- };
- ChangeDetectionCompiler.prototype._createChangeDetectorFactory = function (definition) {
- if (lang_1.IS_DART || !this._genConfig.useJit) {
- var proto = new change_detection_1.DynamicProtoChangeDetector(definition);
- return function (dispatcher) { return proto.instantiate(dispatcher); };
- }
- else {
- return new change_detection_jit_generator_1.ChangeDetectorJITGenerator(definition, UTIL, ABSTRACT_CHANGE_DETECTOR, CHANGE_DETECTOR_STATE)
- .generate();
- }
- };
- ChangeDetectionCompiler.prototype.compileComponentCodeGen = function (componentType, strategy, parsedTemplate) {
- var changeDetectorDefinitions = change_definition_factory_1.createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate);
- var factories = [];
- var index = 0;
- var sourceParts = changeDetectorDefinitions.map(function (definition) {
- var codegen;
- var sourcePart;
- // TODO(tbosch): move the 2 code generators to the same place, one with .dart and one with .ts
- // suffix
- // and have the same API for calling them!
- if (lang_1.IS_DART) {
- codegen = new change_detector_codegen_1.Codegen(PREGEN_PROTO_CHANGE_DETECTOR_MODULE);
- var className = "_" + definition.id;
- var typeRef = (index === 0 && componentType.isHost) ?
- 'dynamic' :
- "" + source_module_1.moduleRef(componentType.moduleUrl) + componentType.name;
- codegen.generate(typeRef, className, definition);
- factories.push(className + ".newChangeDetector");
- sourcePart = codegen.toString();
- }
- else {
- codegen = new change_detection_jit_generator_1.ChangeDetectorJITGenerator(definition, "" + UTIL_MODULE + UTIL, "" + ABSTRACT_CHANGE_DETECTOR_MODULE + ABSTRACT_CHANGE_DETECTOR, "" + CONSTANTS_MODULE + CHANGE_DETECTOR_STATE);
- factories.push("function(dispatcher) { return new " + codegen.typeName + "(dispatcher); }");
- sourcePart = codegen.generateSource();
- }
- index++;
- return sourcePart;
- });
- return new source_module_1.SourceExpressions(sourceParts, factories);
- };
- ChangeDetectionCompiler = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [change_detection_1.ChangeDetectorGenConfig])
- ], ChangeDetectionCompiler);
- return ChangeDetectionCompiler;
- })();
- exports.ChangeDetectionCompiler = ChangeDetectionCompiler;
- /***/ },
- /* 158 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var reflection_1 = __webpack_require__(16);
- var change_detection_1 = __webpack_require__(25);
- var template_ast_1 = __webpack_require__(159);
- var interfaces_1 = __webpack_require__(89);
- function createChangeDetectorDefinitions(componentType, componentStrategy, genConfig, parsedTemplate) {
- var pvVisitors = [];
- var visitor = new ProtoViewVisitor(null, pvVisitors, componentStrategy);
- template_ast_1.templateVisitAll(visitor, parsedTemplate);
- return createChangeDefinitions(pvVisitors, componentType, genConfig);
- }
- exports.createChangeDetectorDefinitions = createChangeDetectorDefinitions;
- var ProtoViewVisitor = (function () {
- function ProtoViewVisitor(parent, allVisitors, strategy) {
- this.parent = parent;
- this.allVisitors = allVisitors;
- this.strategy = strategy;
- this.boundTextCount = 0;
- this.boundElementCount = 0;
- this.variableNames = [];
- this.bindingRecords = [];
- this.eventRecords = [];
- this.directiveRecords = [];
- this.viewIndex = allVisitors.length;
- allVisitors.push(this);
- }
- ProtoViewVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
- this.boundElementCount++;
- template_ast_1.templateVisitAll(this, ast.outputs);
- for (var i = 0; i < ast.directives.length; i++) {
- ast.directives[i].visit(this, i);
- }
- var childVisitor = new ProtoViewVisitor(this, this.allVisitors, change_detection_1.ChangeDetectionStrategy.Default);
- // Attention: variables present on an embedded template count towards
- // the embedded template and not the template anchor!
- template_ast_1.templateVisitAll(childVisitor, ast.vars);
- template_ast_1.templateVisitAll(childVisitor, ast.children);
- return null;
- };
- ProtoViewVisitor.prototype.visitElement = function (ast, context) {
- if (ast.isBound()) {
- this.boundElementCount++;
- }
- template_ast_1.templateVisitAll(this, ast.inputs, null);
- template_ast_1.templateVisitAll(this, ast.outputs);
- template_ast_1.templateVisitAll(this, ast.exportAsVars);
- for (var i = 0; i < ast.directives.length; i++) {
- ast.directives[i].visit(this, i);
- }
- template_ast_1.templateVisitAll(this, ast.children);
- return null;
- };
- ProtoViewVisitor.prototype.visitNgContent = function (ast, context) { return null; };
- ProtoViewVisitor.prototype.visitVariable = function (ast, context) {
- this.variableNames.push(ast.name);
- return null;
- };
- ProtoViewVisitor.prototype.visitEvent = function (ast, directiveRecord) {
- var bindingRecord = lang_1.isPresent(directiveRecord) ?
- change_detection_1.BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) :
- change_detection_1.BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1);
- this.eventRecords.push(bindingRecord);
- return null;
- };
- ProtoViewVisitor.prototype.visitElementProperty = function (ast, directiveRecord) {
- var boundElementIndex = this.boundElementCount - 1;
- var dirIndex = lang_1.isPresent(directiveRecord) ? directiveRecord.directiveIndex : null;
- var bindingRecord;
- if (ast.type === template_ast_1.PropertyBindingType.Property) {
- bindingRecord =
- lang_1.isPresent(dirIndex) ?
- change_detection_1.BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) :
- change_detection_1.BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name);
- }
- else if (ast.type === template_ast_1.PropertyBindingType.Attribute) {
- bindingRecord =
- lang_1.isPresent(dirIndex) ?
- change_detection_1.BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) :
- change_detection_1.BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name);
- }
- else if (ast.type === template_ast_1.PropertyBindingType.Class) {
- bindingRecord =
- lang_1.isPresent(dirIndex) ?
- change_detection_1.BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) :
- change_detection_1.BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name);
- }
- else if (ast.type === template_ast_1.PropertyBindingType.Style) {
- bindingRecord =
- lang_1.isPresent(dirIndex) ?
- change_detection_1.BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) :
- change_detection_1.BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit);
- }
- this.bindingRecords.push(bindingRecord);
- return null;
- };
- ProtoViewVisitor.prototype.visitAttr = function (ast, context) { return null; };
- ProtoViewVisitor.prototype.visitBoundText = function (ast, context) {
- var boundTextIndex = this.boundTextCount++;
- this.bindingRecords.push(change_detection_1.BindingRecord.createForTextNode(ast.value, boundTextIndex));
- return null;
- };
- ProtoViewVisitor.prototype.visitText = function (ast, context) { return null; };
- ProtoViewVisitor.prototype.visitDirective = function (ast, directiveIndexAsNumber) {
- var directiveIndex = new change_detection_1.DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber);
- var directiveMetadata = ast.directive;
- var directiveRecord = new change_detection_1.DirectiveRecord({
- directiveIndex: directiveIndex,
- callAfterContentInit: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterContentInit) !== -1,
- callAfterContentChecked: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterContentChecked) !== -1,
- callAfterViewInit: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterViewInit) !== -1,
- callAfterViewChecked: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterViewChecked) !== -1,
- callOnChanges: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.OnChanges) !== -1,
- callDoCheck: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.DoCheck) !== -1,
- callOnInit: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.OnInit) !== -1,
- changeDetection: directiveMetadata.changeDetection
- });
- this.directiveRecords.push(directiveRecord);
- template_ast_1.templateVisitAll(this, ast.inputs, directiveRecord);
- var bindingRecords = this.bindingRecords;
- if (directiveRecord.callOnChanges) {
- bindingRecords.push(change_detection_1.BindingRecord.createDirectiveOnChanges(directiveRecord));
- }
- if (directiveRecord.callOnInit) {
- bindingRecords.push(change_detection_1.BindingRecord.createDirectiveOnInit(directiveRecord));
- }
- if (directiveRecord.callDoCheck) {
- bindingRecords.push(change_detection_1.BindingRecord.createDirectiveDoCheck(directiveRecord));
- }
- template_ast_1.templateVisitAll(this, ast.hostProperties, directiveRecord);
- template_ast_1.templateVisitAll(this, ast.hostEvents, directiveRecord);
- template_ast_1.templateVisitAll(this, ast.exportAsVars);
- return null;
- };
- ProtoViewVisitor.prototype.visitDirectiveProperty = function (ast, directiveRecord) {
- // TODO: these setters should eventually be created by change detection, to make
- // it monomorphic!
- var setter = reflection_1.reflector.setter(ast.directiveName);
- this.bindingRecords.push(change_detection_1.BindingRecord.createForDirective(ast.value, ast.directiveName, setter, directiveRecord));
- return null;
- };
- return ProtoViewVisitor;
- })();
- function createChangeDefinitions(pvVisitors, componentType, genConfig) {
- var pvVariableNames = _collectNestedProtoViewsVariableNames(pvVisitors);
- return pvVisitors.map(function (pvVisitor) {
- var id = componentType.name + "_" + pvVisitor.viewIndex;
- return new change_detection_1.ChangeDetectorDefinition(id, pvVisitor.strategy, pvVariableNames[pvVisitor.viewIndex], pvVisitor.bindingRecords, pvVisitor.eventRecords, pvVisitor.directiveRecords, genConfig);
- });
- }
- function _collectNestedProtoViewsVariableNames(pvVisitors) {
- var nestedPvVariableNames = collection_1.ListWrapper.createFixedSize(pvVisitors.length);
- pvVisitors.forEach(function (pv) {
- var parentVariableNames = lang_1.isPresent(pv.parent) ? nestedPvVariableNames[pv.parent.viewIndex] : [];
- nestedPvVariableNames[pv.viewIndex] = parentVariableNames.concat(pv.variableNames);
- });
- return nestedPvVariableNames;
- }
- /***/ },
- /* 159 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- /**
- * A segment of text within the template.
- */
- var TextAst = (function () {
- function TextAst(value, ngContentIndex, sourceSpan) {
- this.value = value;
- this.ngContentIndex = ngContentIndex;
- this.sourceSpan = sourceSpan;
- }
- TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
- return TextAst;
- })();
- exports.TextAst = TextAst;
- /**
- * A bound expression within the text of a template.
- */
- var BoundTextAst = (function () {
- function BoundTextAst(value, ngContentIndex, sourceSpan) {
- this.value = value;
- this.ngContentIndex = ngContentIndex;
- this.sourceSpan = sourceSpan;
- }
- BoundTextAst.prototype.visit = function (visitor, context) {
- return visitor.visitBoundText(this, context);
- };
- return BoundTextAst;
- })();
- exports.BoundTextAst = BoundTextAst;
- /**
- * A plain attribute on an element.
- */
- var AttrAst = (function () {
- function AttrAst(name, value, sourceSpan) {
- this.name = name;
- this.value = value;
- this.sourceSpan = sourceSpan;
- }
- AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
- return AttrAst;
- })();
- exports.AttrAst = AttrAst;
- /**
- * A binding for an element property (e.g. `[property]="expression"`).
- */
- var BoundElementPropertyAst = (function () {
- function BoundElementPropertyAst(name, type, value, unit, sourceSpan) {
- this.name = name;
- this.type = type;
- this.value = value;
- this.unit = unit;
- this.sourceSpan = sourceSpan;
- }
- BoundElementPropertyAst.prototype.visit = function (visitor, context) {
- return visitor.visitElementProperty(this, context);
- };
- return BoundElementPropertyAst;
- })();
- exports.BoundElementPropertyAst = BoundElementPropertyAst;
- /**
- * A binding for an element event (e.g. `(event)="handler()"`).
- */
- var BoundEventAst = (function () {
- function BoundEventAst(name, target, handler, sourceSpan) {
- this.name = name;
- this.target = target;
- this.handler = handler;
- this.sourceSpan = sourceSpan;
- }
- BoundEventAst.prototype.visit = function (visitor, context) {
- return visitor.visitEvent(this, context);
- };
- Object.defineProperty(BoundEventAst.prototype, "fullName", {
- get: function () {
- if (lang_1.isPresent(this.target)) {
- return this.target + ":" + this.name;
- }
- else {
- return this.name;
- }
- },
- enumerable: true,
- configurable: true
- });
- return BoundEventAst;
- })();
- exports.BoundEventAst = BoundEventAst;
- /**
- * A variable declaration on an element (e.g. `#var="expression"`).
- */
- var VariableAst = (function () {
- function VariableAst(name, value, sourceSpan) {
- this.name = name;
- this.value = value;
- this.sourceSpan = sourceSpan;
- }
- VariableAst.prototype.visit = function (visitor, context) {
- return visitor.visitVariable(this, context);
- };
- return VariableAst;
- })();
- exports.VariableAst = VariableAst;
- /**
- * An element declaration in a template.
- */
- var ElementAst = (function () {
- function ElementAst(name, attrs, inputs, outputs, exportAsVars, directives, children, ngContentIndex, sourceSpan) {
- this.name = name;
- this.attrs = attrs;
- this.inputs = inputs;
- this.outputs = outputs;
- this.exportAsVars = exportAsVars;
- this.directives = directives;
- this.children = children;
- this.ngContentIndex = ngContentIndex;
- this.sourceSpan = sourceSpan;
- }
- ElementAst.prototype.visit = function (visitor, context) {
- return visitor.visitElement(this, context);
- };
- /**
- * Whether the element has any active bindings (inputs, outputs, vars, or directives).
- */
- ElementAst.prototype.isBound = function () {
- return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 ||
- this.directives.length > 0);
- };
- /**
- * Get the component associated with this element, if any.
- */
- ElementAst.prototype.getComponent = function () {
- return this.directives.length > 0 && this.directives[0].directive.isComponent ?
- this.directives[0].directive :
- null;
- };
- return ElementAst;
- })();
- exports.ElementAst = ElementAst;
- /**
- * A `<template>` element included in an Angular template.
- */
- var EmbeddedTemplateAst = (function () {
- function EmbeddedTemplateAst(attrs, outputs, vars, directives, children, ngContentIndex, sourceSpan) {
- this.attrs = attrs;
- this.outputs = outputs;
- this.vars = vars;
- this.directives = directives;
- this.children = children;
- this.ngContentIndex = ngContentIndex;
- this.sourceSpan = sourceSpan;
- }
- EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
- return visitor.visitEmbeddedTemplate(this, context);
- };
- return EmbeddedTemplateAst;
- })();
- exports.EmbeddedTemplateAst = EmbeddedTemplateAst;
- /**
- * A directive property with a bound value (e.g. `*ngIf="condition").
- */
- var BoundDirectivePropertyAst = (function () {
- function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
- this.directiveName = directiveName;
- this.templateName = templateName;
- this.value = value;
- this.sourceSpan = sourceSpan;
- }
- BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
- return visitor.visitDirectiveProperty(this, context);
- };
- return BoundDirectivePropertyAst;
- })();
- exports.BoundDirectivePropertyAst = BoundDirectivePropertyAst;
- /**
- * A directive declared on an element.
- */
- var DirectiveAst = (function () {
- function DirectiveAst(directive, inputs, hostProperties, hostEvents, exportAsVars, sourceSpan) {
- this.directive = directive;
- this.inputs = inputs;
- this.hostProperties = hostProperties;
- this.hostEvents = hostEvents;
- this.exportAsVars = exportAsVars;
- this.sourceSpan = sourceSpan;
- }
- DirectiveAst.prototype.visit = function (visitor, context) {
- return visitor.visitDirective(this, context);
- };
- return DirectiveAst;
- })();
- exports.DirectiveAst = DirectiveAst;
- /**
- * Position where content is to be projected (instance of `<ng-content>` in a template).
- */
- var NgContentAst = (function () {
- function NgContentAst(index, ngContentIndex, sourceSpan) {
- this.index = index;
- this.ngContentIndex = ngContentIndex;
- this.sourceSpan = sourceSpan;
- }
- NgContentAst.prototype.visit = function (visitor, context) {
- return visitor.visitNgContent(this, context);
- };
- return NgContentAst;
- })();
- exports.NgContentAst = NgContentAst;
- /**
- * Enumeration of types of property bindings.
- */
- (function (PropertyBindingType) {
- /**
- * A normal binding to a property (e.g. `[property]="expression"`).
- */
- PropertyBindingType[PropertyBindingType["Property"] = 0] = "Property";
- /**
- * A binding to an element attribute (e.g. `[attr.name]="expression"`).
- */
- PropertyBindingType[PropertyBindingType["Attribute"] = 1] = "Attribute";
- /**
- * A binding to a CSS class (e.g. `[class.name]="condition"`).
- */
- PropertyBindingType[PropertyBindingType["Class"] = 2] = "Class";
- /**
- * A binding to a style rule (e.g. `[style.rule]="expression"`).
- */
- PropertyBindingType[PropertyBindingType["Style"] = 3] = "Style";
- })(exports.PropertyBindingType || (exports.PropertyBindingType = {}));
- var PropertyBindingType = exports.PropertyBindingType;
- /**
- * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
- */
- function templateVisitAll(visitor, asts, context) {
- if (context === void 0) { context = null; }
- var result = [];
- asts.forEach(function (ast) {
- var astResult = ast.visit(visitor, context);
- if (lang_1.isPresent(astResult)) {
- result.push(astResult);
- }
- });
- return result;
- }
- exports.templateVisitAll = templateVisitAll;
- /***/ },
- /* 160 */
- /***/ function(module, exports) {
- // Note: This class is only here so that we can reference it from TypeScript code.
- // The actual implementation lives under modules_dart.
- // TODO(tbosch): Move the corresponding code into angular2/src/compiler once
- // the new compiler is done.
- var Codegen = (function () {
- function Codegen(moduleAlias) {
- }
- Codegen.prototype.generate = function (typeName, changeDetectorTypeName, def) {
- throw "Not implemented in JS";
- };
- Codegen.prototype.toString = function () { throw "Not implemented in JS"; };
- return Codegen;
- })();
- exports.Codegen = Codegen;
- /***/ },
- /* 161 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var source_module_1 = __webpack_require__(156);
- var view_1 = __webpack_require__(56);
- var xhr_1 = __webpack_require__(149);
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- var shadow_css_1 = __webpack_require__(162);
- var url_resolver_1 = __webpack_require__(148);
- var style_url_resolver_1 = __webpack_require__(163);
- var util_1 = __webpack_require__(155);
- var di_1 = __webpack_require__(6);
- var view_factory_1 = __webpack_require__(164);
- var StyleCompiler = (function () {
- function StyleCompiler(_xhr, _urlResolver) {
- this._xhr = _xhr;
- this._urlResolver = _urlResolver;
- this._styleCache = new Map();
- this._shadowCss = new shadow_css_1.ShadowCss();
- }
- StyleCompiler.prototype.compileComponentRuntime = function (template) {
- var styles = template.styles;
- var styleAbsUrls = template.styleUrls;
- return this._loadStyles(styles, styleAbsUrls, template.encapsulation === view_1.ViewEncapsulation.Emulated);
- };
- StyleCompiler.prototype.compileComponentCodeGen = function (template) {
- var shim = template.encapsulation === view_1.ViewEncapsulation.Emulated;
- return this._styleCodeGen(template.styles, template.styleUrls, shim);
- };
- StyleCompiler.prototype.compileStylesheetCodeGen = function (stylesheetUrl, cssText) {
- var styleWithImports = style_url_resolver_1.extractStyleUrls(this._urlResolver, stylesheetUrl, cssText);
- return [
- this._styleModule(stylesheetUrl, false, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, false)),
- this._styleModule(stylesheetUrl, true, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, true))
- ];
- };
- StyleCompiler.prototype.clearCache = function () { this._styleCache.clear(); };
- StyleCompiler.prototype._loadStyles = function (plainStyles, absUrls, encapsulate) {
- var _this = this;
- var promises = absUrls.map(function (absUrl) {
- var cacheKey = "" + absUrl + (encapsulate ? '.shim' : '');
- var result = _this._styleCache.get(cacheKey);
- if (lang_1.isBlank(result)) {
- result = _this._xhr.get(absUrl).then(function (style) {
- var styleWithImports = style_url_resolver_1.extractStyleUrls(_this._urlResolver, absUrl, style);
- return _this._loadStyles([styleWithImports.style], styleWithImports.styleUrls, encapsulate);
- });
- _this._styleCache.set(cacheKey, result);
- }
- return result;
- });
- return async_1.PromiseWrapper.all(promises).then(function (nestedStyles) {
- var result = plainStyles.map(function (plainStyle) { return _this._shimIfNeeded(plainStyle, encapsulate); });
- nestedStyles.forEach(function (styles) { return result.push(styles); });
- return result;
- });
- };
- StyleCompiler.prototype._styleCodeGen = function (plainStyles, absUrls, shim) {
- var _this = this;
- var arrayPrefix = lang_1.IS_DART ? "const" : '';
- var styleExpressions = plainStyles.map(function (plainStyle) { return util_1.escapeSingleQuoteString(_this._shimIfNeeded(plainStyle, shim)); });
- for (var i = 0; i < absUrls.length; i++) {
- var moduleUrl = this._createModuleUrl(absUrls[i], shim);
- styleExpressions.push(source_module_1.moduleRef(moduleUrl) + "STYLES");
- }
- var expressionSource = arrayPrefix + " [" + styleExpressions.join(',') + "]";
- return new source_module_1.SourceExpression([], expressionSource);
- };
- StyleCompiler.prototype._styleModule = function (stylesheetUrl, shim, expression) {
- var moduleSource = "\n " + expression.declarations.join('\n') + "\n " + util_1.codeGenExportVariable('STYLES') + expression.expression + ";\n ";
- return new source_module_1.SourceModule(this._createModuleUrl(stylesheetUrl, shim), moduleSource);
- };
- StyleCompiler.prototype._shimIfNeeded = function (style, shim) {
- return shim ? this._shadowCss.shimCssText(style, view_factory_1.CONTENT_ATTR, view_factory_1.HOST_ATTR) : style;
- };
- StyleCompiler.prototype._createModuleUrl = function (stylesheetUrl, shim) {
- return shim ? stylesheetUrl + ".shim" + util_1.MODULE_SUFFIX : "" + stylesheetUrl + util_1.MODULE_SUFFIX;
- };
- StyleCompiler = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [xhr_1.XHR, url_resolver_1.UrlResolver])
- ], StyleCompiler);
- return StyleCompiler;
- })();
- exports.StyleCompiler = StyleCompiler;
- /***/ },
- /* 162 */
- /***/ function(module, exports, __webpack_require__) {
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- /**
- * This file is a port of shadowCSS from webcomponents.js to TypeScript.
- *
- * Please make sure to keep to edits in sync with the source file.
- *
- * Source:
- * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
- *
- * The original file level comment is reproduced below
- */
- /*
- This is a limited shim for ShadowDOM css styling.
- https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
- The intention here is to support only the styling features which can be
- relatively simply implemented. The goal is to allow users to avoid the
- most obvious pitfalls and do so without compromising performance significantly.
- For ShadowDOM styling that's not covered here, a set of best practices
- can be provided that should allow users to accomplish more complex styling.
- The following is a list of specific ShadowDOM styling features and a brief
- discussion of the approach used to shim.
- Shimmed features:
- * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
- element using the :host rule. To shim this feature, the :host styles are
- reformatted and prefixed with a given scope name and promoted to a
- document level stylesheet.
- For example, given a scope name of .foo, a rule like this:
- :host {
- background: red;
- }
- }
- becomes:
- .foo {
- background: red;
- }
- * encapsultion: Styles defined within ShadowDOM, apply only to
- dom inside the ShadowDOM. Polymer uses one of two techniques to imlement
- this feature.
- By default, rules are prefixed with the host element tag name
- as a descendant selector. This ensures styling does not leak out of the 'top'
- of the element's ShadowDOM. For example,
- div {
- font-weight: bold;
- }
- becomes:
- x-foo div {
- font-weight: bold;
- }
- becomes:
- Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
- selectors are scoped by adding an attribute selector suffix to each
- simple selector that contains the host element tag name. Each element
- in the element's ShadowDOM template is also given the scope attribute.
- Thus, these rules match only elements that have the scope attribute.
- For example, given a scope name of x-foo, a rule like this:
- div {
- font-weight: bold;
- }
- becomes:
- div[x-foo] {
- font-weight: bold;
- }
- Note that elements that are dynamically added to a scope must have the scope
- selector added to them manually.
- * upper/lower bound encapsulation: Styles which are defined outside a
- shadowRoot should not cross the ShadowDOM boundary and should not apply
- inside a shadowRoot.
- This styling behavior is not emulated. Some possible ways to do this that
- were rejected due to complexity and/or performance concerns include: (1) reset
- every possible property for every possible selector for a given scope name;
- (2) re-implement css in javascript.
- As an alternative, users should make sure to use selectors
- specific to the scope in which they are working.
- * ::distributed: This behavior is not emulated. It's often not necessary
- to style the contents of a specific insertion point and instead, descendants
- of the host element can be styled selectively. Users can also create an
- extra node around an insertion point and style that node's contents
- via descendent selectors. For example, with a shadowRoot like this:
- <style>
- ::content(div) {
- background: red;
- }
- </style>
- <content></content>
- could become:
- <style>
- / *@polyfill .content-container div * /
- ::content(div) {
- background: red;
- }
- </style>
- <div class="content-container">
- <content></content>
- </div>
- Note the use of @polyfill in the comment above a ShadowDOM specific style
- declaration. This is a directive to the styling shim to use the selector
- in comments in lieu of the next selector when running under polyfill.
- */
- var ShadowCss = (function () {
- function ShadowCss() {
- this.strictStyling = true;
- }
- /*
- * Shim some cssText with the given selector. Returns cssText that can
- * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
- *
- * When strictStyling is true:
- * - selector is the attribute added to all elements inside the host,
- * - hostSelector is the attribute added to the host itself.
- */
- ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
- if (hostSelector === void 0) { hostSelector = ''; }
- cssText = stripComments(cssText);
- cssText = this._insertDirectives(cssText);
- return this._scopeCssText(cssText, selector, hostSelector);
- };
- ShadowCss.prototype._insertDirectives = function (cssText) {
- cssText = this._insertPolyfillDirectivesInCssText(cssText);
- return this._insertPolyfillRulesInCssText(cssText);
- };
- /*
- * Process styles to convert native ShadowDOM rules that will trip
- * up the css parser; we rely on decorating the stylesheet with inert rules.
- *
- * For example, we convert this rule:
- *
- * polyfill-next-selector { content: ':host menu-item'; }
- * ::content menu-item {
- *
- * to this:
- *
- * scopeName menu-item {
- *
- **/
- ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
- // Difference with webcomponents.js: does not handle comments
- return lang_1.StringWrapper.replaceAllMapped(cssText, _cssContentNextSelectorRe, function (m) { return m[1] + '{'; });
- };
- /*
- * Process styles to add rules which will only apply under the polyfill
- *
- * For example, we convert this rule:
- *
- * polyfill-rule {
- * content: ':host menu-item';
- * ...
- * }
- *
- * to this:
- *
- * scopeName menu-item {...}
- *
- **/
- ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
- // Difference with webcomponents.js: does not handle comments
- return lang_1.StringWrapper.replaceAllMapped(cssText, _cssContentRuleRe, function (m) {
- var rule = m[0];
- rule = lang_1.StringWrapper.replace(rule, m[1], '');
- rule = lang_1.StringWrapper.replace(rule, m[2], '');
- return m[3] + rule;
- });
- };
- /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
- *
- * .foo {... }
- *
- * and converts this to
- *
- * scopeName .foo { ... }
- */
- ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
- var unscoped = this._extractUnscopedRulesFromCssText(cssText);
- cssText = this._insertPolyfillHostInCssText(cssText);
- cssText = this._convertColonHost(cssText);
- cssText = this._convertColonHostContext(cssText);
- cssText = this._convertShadowDOMSelectors(cssText);
- if (lang_1.isPresent(scopeSelector)) {
- cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
- }
- cssText = cssText + '\n' + unscoped;
- return cssText.trim();
- };
- /*
- * Process styles to add rules which will only apply under the polyfill
- * and do not process via CSSOM. (CSSOM is destructive to rules on rare
- * occasions, e.g. -webkit-calc on Safari.)
- * For example, we convert this rule:
- *
- * @polyfill-unscoped-rule {
- * content: 'menu-item';
- * ... }
- *
- * to this:
- *
- * menu-item {...}
- *
- **/
- ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
- // Difference with webcomponents.js: does not handle comments
- var r = '', m;
- var matcher = lang_1.RegExpWrapper.matcher(_cssContentUnscopedRuleRe, cssText);
- while (lang_1.isPresent(m = lang_1.RegExpMatcherWrapper.next(matcher))) {
- var rule = m[0];
- rule = lang_1.StringWrapper.replace(rule, m[2], '');
- rule = lang_1.StringWrapper.replace(rule, m[1], m[3]);
- r += rule + '\n\n';
- }
- return r;
- };
- /*
- * convert a rule like :host(.foo) > .bar { }
- *
- * to
- *
- * scopeName.foo > .bar
- */
- ShadowCss.prototype._convertColonHost = function (cssText) {
- return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
- };
- /*
- * convert a rule like :host-context(.foo) > .bar { }
- *
- * to
- *
- * scopeName.foo > .bar, .foo scopeName > .bar { }
- *
- * and
- *
- * :host-context(.foo:host) .bar { ... }
- *
- * to
- *
- * scopeName.foo .bar { ... }
- */
- ShadowCss.prototype._convertColonHostContext = function (cssText) {
- return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
- };
- ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) {
- // p1 = :host, p2 = contents of (), p3 rest of rule
- return lang_1.StringWrapper.replaceAllMapped(cssText, regExp, function (m) {
- if (lang_1.isPresent(m[2])) {
- var parts = m[2].split(','), r = [];
- for (var i = 0; i < parts.length; i++) {
- var p = parts[i];
- if (lang_1.isBlank(p))
- break;
- p = p.trim();
- r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
- }
- return r.join(',');
- }
- else {
- return _polyfillHostNoCombinator + m[3];
- }
- });
- };
- ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) {
- if (lang_1.StringWrapper.contains(part, _polyfillHost)) {
- return this._colonHostPartReplacer(host, part, suffix);
- }
- else {
- return host + part + suffix + ', ' + part + ' ' + host + suffix;
- }
- };
- ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) {
- return host + lang_1.StringWrapper.replace(part, _polyfillHost, '') + suffix;
- };
- /*
- * Convert combinators like ::shadow and pseudo-elements like ::content
- * by replacing with space.
- */
- ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
- for (var i = 0; i < _shadowDOMSelectorsRe.length; i++) {
- cssText = lang_1.StringWrapper.replaceAll(cssText, _shadowDOMSelectorsRe[i], ' ');
- }
- return cssText;
- };
- // change a selector like 'div' to 'name div'
- ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
- var _this = this;
- return processRules(cssText, function (rule) {
- var selector = rule.selector;
- var content = rule.content;
- if (rule.selector[0] != '@' || rule.selector.startsWith('@page')) {
- selector =
- _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
- }
- else if (rule.selector.startsWith('@media')) {
- content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
- }
- return new CssRule(selector, content);
- });
- };
- ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
- var r = [], parts = selector.split(',');
- for (var i = 0; i < parts.length; i++) {
- var p = parts[i];
- p = p.trim();
- if (this._selectorNeedsScoping(p, scopeSelector)) {
- p = strict && !lang_1.StringWrapper.contains(p, _polyfillHostNoCombinator) ?
- this._applyStrictSelectorScope(p, scopeSelector) :
- this._applySelectorScope(p, scopeSelector, hostSelector);
- }
- r.push(p);
- }
- return r.join(', ');
- };
- ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
- var re = this._makeScopeMatcher(scopeSelector);
- return !lang_1.isPresent(lang_1.RegExpWrapper.firstMatch(re, selector));
- };
- ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
- var lre = /\[/g;
- var rre = /\]/g;
- scopeSelector = lang_1.StringWrapper.replaceAll(scopeSelector, lre, '\\[');
- scopeSelector = lang_1.StringWrapper.replaceAll(scopeSelector, rre, '\\]');
- return lang_1.RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
- };
- ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
- // Difference from webcomponentsjs: scopeSelector could not be an array
- return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
- };
- // scope via name and [is=name]
- ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
- if (lang_1.isPresent(lang_1.RegExpWrapper.firstMatch(_polyfillHostRe, selector))) {
- var replaceBy = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
- selector = lang_1.StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy);
- return lang_1.StringWrapper.replaceAll(selector, _polyfillHostRe, replaceBy + ' ');
- }
- else {
- return scopeSelector + ' ' + selector;
- }
- };
- // return a selector with [name] suffix on each simple selector
- // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
- ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector) {
- var isRe = /\[is=([^\]]*)\]/g;
- scopeSelector = lang_1.StringWrapper.replaceAllMapped(scopeSelector, isRe, function (m) { return m[1]; });
- var splits = [' ', '>', '+', '~'], scoped = selector, attrName = '[' + scopeSelector + ']';
- for (var i = 0; i < splits.length; i++) {
- var sep = splits[i];
- var parts = scoped.split(sep);
- scoped = parts.map(function (p) {
- // remove :host since it should be unnecessary
- var t = lang_1.StringWrapper.replaceAll(p.trim(), _polyfillHostRe, '');
- if (t.length > 0 && !collection_1.ListWrapper.contains(splits, t) &&
- !lang_1.StringWrapper.contains(t, attrName)) {
- var re = /([^:]*)(:*)(.*)/g;
- var m = lang_1.RegExpWrapper.firstMatch(re, t);
- if (lang_1.isPresent(m)) {
- p = m[1] + attrName + m[2] + m[3];
- }
- }
- return p;
- })
- .join(sep);
- }
- return scoped;
- };
- ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
- selector = lang_1.StringWrapper.replaceAll(selector, _colonHostContextRe, _polyfillHostContext);
- selector = lang_1.StringWrapper.replaceAll(selector, _colonHostRe, _polyfillHost);
- return selector;
- };
- return ShadowCss;
- })();
- exports.ShadowCss = ShadowCss;
- var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim;
- var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim;
- var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim;
- var _polyfillHost = '-shadowcsshost';
- // note: :host-context pre-processed to -shadowcsshostcontext.
- var _polyfillHostContext = '-shadowcsscontext';
- var _parenSuffix = ')(?:\\((' +
- '(?:\\([^)(]*\\)|[^)(]*)+?' +
- ')\\))?([^,{]*)';
- var _cssColonHostRe = lang_1.RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, 'im');
- var _cssColonHostContextRe = lang_1.RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im');
- var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
- var _shadowDOMSelectorsRe = [
- />>>/g,
- /::shadow/g,
- /::content/g,
- // Deprecated selectors
- // TODO(vicb): see https://github.com/angular/clang-format/issues/16
- // clang-format off
- /\/deep\//g,
- /\/shadow-deep\//g,
- /\/shadow\//g,
- ];
- var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
- var _polyfillHostRe = lang_1.RegExpWrapper.create(_polyfillHost, 'im');
- var _colonHostRe = /:host/gim;
- var _colonHostContextRe = /:host-context/gim;
- var _commentRe = /\/\*[\s\S]*?\*\//g;
- function stripComments(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, _commentRe, function (_) { return ''; });
- }
- var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
- var _curlyRe = /([{}])/g;
- var OPEN_CURLY = '{';
- var CLOSE_CURLY = '}';
- var BLOCK_PLACEHOLDER = '%BLOCK%';
- var CssRule = (function () {
- function CssRule(selector, content) {
- this.selector = selector;
- this.content = content;
- }
- return CssRule;
- })();
- exports.CssRule = CssRule;
- function processRules(input, ruleCallback) {
- var inputWithEscapedBlocks = escapeBlocks(input);
- var nextBlockIndex = 0;
- return lang_1.StringWrapper.replaceAllMapped(inputWithEscapedBlocks.escapedString, _ruleRe, function (m) {
- var selector = m[2];
- var content = '';
- var suffix = m[4];
- var contentPrefix = '';
- if (lang_1.isPresent(m[4]) && m[4].startsWith('{' + BLOCK_PLACEHOLDER)) {
- content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
- suffix = m[4].substring(BLOCK_PLACEHOLDER.length + 1);
- contentPrefix = '{';
- }
- var rule = ruleCallback(new CssRule(selector, content));
- return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
- });
- }
- exports.processRules = processRules;
- var StringWithEscapedBlocks = (function () {
- function StringWithEscapedBlocks(escapedString, blocks) {
- this.escapedString = escapedString;
- this.blocks = blocks;
- }
- return StringWithEscapedBlocks;
- })();
- function escapeBlocks(input) {
- var inputParts = lang_1.StringWrapper.split(input, _curlyRe);
- var resultParts = [];
- var escapedBlocks = [];
- var bracketCount = 0;
- var currentBlockParts = [];
- for (var partIndex = 0; partIndex < inputParts.length; partIndex++) {
- var part = inputParts[partIndex];
- if (part == CLOSE_CURLY) {
- bracketCount--;
- }
- if (bracketCount > 0) {
- currentBlockParts.push(part);
- }
- else {
- if (currentBlockParts.length > 0) {
- escapedBlocks.push(currentBlockParts.join(''));
- resultParts.push(BLOCK_PLACEHOLDER);
- currentBlockParts = [];
- }
- resultParts.push(part);
- }
- if (part == OPEN_CURLY) {
- bracketCount++;
- }
- }
- if (currentBlockParts.length > 0) {
- escapedBlocks.push(currentBlockParts.join(''));
- resultParts.push(BLOCK_PLACEHOLDER);
- }
- return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
- }
- /***/ },
- /* 163 */
- /***/ function(module, exports, __webpack_require__) {
- // Some of the code comes from WebComponents.JS
- // https://github.com/webcomponents/webcomponentsjs/blob/master/src/HTMLImports/path.js
- var lang_1 = __webpack_require__(5);
- var StyleWithImports = (function () {
- function StyleWithImports(style, styleUrls) {
- this.style = style;
- this.styleUrls = styleUrls;
- }
- return StyleWithImports;
- })();
- exports.StyleWithImports = StyleWithImports;
- function isStyleUrlResolvable(url) {
- if (lang_1.isBlank(url) || url.length === 0 || url[0] == '/')
- return false;
- var schemeMatch = lang_1.RegExpWrapper.firstMatch(_urlWithSchemaRe, url);
- return lang_1.isBlank(schemeMatch) || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
- }
- exports.isStyleUrlResolvable = isStyleUrlResolvable;
- /**
- * Rewrites stylesheets by resolving and removing the @import urls that
- * are either relative or don't have a `package:` scheme
- */
- function extractStyleUrls(resolver, baseUrl, cssText) {
- var foundUrls = [];
- var modifiedCssText = lang_1.StringWrapper.replaceAllMapped(cssText, _cssImportRe, function (m) {
- var url = lang_1.isPresent(m[1]) ? m[1] : m[2];
- if (!isStyleUrlResolvable(url)) {
- // Do not attempt to resolve non-package absolute URLs with URI scheme
- return m[0];
- }
- foundUrls.push(resolver.resolve(baseUrl, url));
- return '';
- });
- return new StyleWithImports(modifiedCssText, foundUrls);
- }
- exports.extractStyleUrls = extractStyleUrls;
- var _cssImportRe = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
- // TODO: can't use /^[^:/?#.]+:/g due to clang-format bug:
- // https://github.com/angular/angular/issues/4596
- var _urlWithSchemaRe = /^([a-zA-Z\-\+\.]+):/g;
- /***/ },
- /* 164 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var view_1 = __webpack_require__(165);
- var metadata_1 = __webpack_require__(3);
- var collection_1 = __webpack_require__(12);
- function encapsulateStyles(componentTemplate) {
- var processedStyles = componentTemplate.styles;
- if (componentTemplate.encapsulation === metadata_1.ViewEncapsulation.Emulated) {
- processedStyles = collection_1.ListWrapper.createFixedSize(componentTemplate.styles.length);
- for (var i = 0; i < componentTemplate.styles.length; i++) {
- processedStyles[i] = lang_1.StringWrapper.replaceAll(componentTemplate.styles[i], COMPONENT_REGEX, componentTemplate.shortId);
- }
- }
- return processedStyles;
- }
- exports.encapsulateStyles = encapsulateStyles;
- function createRenderView(componentTemplate, cmds, inplaceElement, nodeFactory) {
- var view;
- var eventDispatcher = function (boundElementIndex, eventName, event) {
- return view.dispatchRenderEvent(boundElementIndex, eventName, event);
- };
- var context = new BuildContext(eventDispatcher, nodeFactory, inplaceElement);
- context.build(componentTemplate, cmds);
- var fragments = [];
- for (var i = 0; i < context.fragments.length; i++) {
- fragments.push(new view_1.DefaultRenderFragmentRef(context.fragments[i]));
- }
- view = new view_1.DefaultRenderView(fragments, context.boundTextNodes, context.boundElements, context.nativeShadowRoots, context.globalEventAdders, context.rootContentInsertionPoints);
- return view;
- }
- exports.createRenderView = createRenderView;
- var BuildContext = (function () {
- function BuildContext(_eventDispatcher, factory, _inplaceElement) {
- this._eventDispatcher = _eventDispatcher;
- this.factory = factory;
- this._inplaceElement = _inplaceElement;
- this._builders = [];
- this.globalEventAdders = [];
- this.boundElements = [];
- this.boundTextNodes = [];
- this.nativeShadowRoots = [];
- this.fragments = [];
- this.rootContentInsertionPoints = [];
- this.componentCount = 0;
- this.isHost = lang_1.isPresent((_inplaceElement));
- }
- BuildContext.prototype.build = function (template, cmds) {
- this.enqueueRootBuilder(template, cmds);
- this._build(this._builders[0]);
- };
- BuildContext.prototype._build = function (builder) {
- this._builders = [];
- builder.build(this);
- var enqueuedBuilders = this._builders;
- for (var i = 0; i < enqueuedBuilders.length; i++) {
- this._build(enqueuedBuilders[i]);
- }
- };
- BuildContext.prototype.enqueueComponentBuilder = function (component) {
- this.componentCount++;
- this._builders.push(new RenderViewBuilder(component, null, component.template, component.template.commands));
- };
- BuildContext.prototype.enqueueFragmentBuilder = function (parentComponent, parentTemplate, commands) {
- var rootNodes = [];
- this.fragments.push(rootNodes);
- this._builders.push(new RenderViewBuilder(parentComponent, rootNodes, parentTemplate, commands));
- };
- BuildContext.prototype.enqueueRootBuilder = function (template, cmds) {
- var rootNodes = [];
- this.fragments.push(rootNodes);
- this._builders.push(new RenderViewBuilder(null, rootNodes, template, cmds));
- };
- BuildContext.prototype.consumeInplaceElement = function () {
- var result = this._inplaceElement;
- this._inplaceElement = null;
- return result;
- };
- BuildContext.prototype.addEventListener = function (boundElementIndex, target, eventName) {
- if (lang_1.isPresent(target)) {
- var handler = createEventHandler(boundElementIndex, target + ":" + eventName, this._eventDispatcher);
- this.globalEventAdders.push(createGlobalEventAdder(target, eventName, handler, this.factory));
- }
- else {
- var handler = createEventHandler(boundElementIndex, eventName, this._eventDispatcher);
- this.factory.on(this.boundElements[boundElementIndex], eventName, handler);
- }
- };
- return BuildContext;
- })();
- function createEventHandler(boundElementIndex, eventName, eventDispatcher) {
- return function ($event) { return eventDispatcher(boundElementIndex, eventName, $event); };
- }
- function createGlobalEventAdder(target, eventName, eventHandler, nodeFactory) {
- return function () { return nodeFactory.globalOn(target, eventName, eventHandler); };
- }
- var RenderViewBuilder = (function () {
- function RenderViewBuilder(parentComponent, fragmentRootNodes, template, cmds) {
- this.parentComponent = parentComponent;
- this.fragmentRootNodes = fragmentRootNodes;
- this.template = template;
- this.cmds = cmds;
- var rootNodesParent = lang_1.isPresent(fragmentRootNodes) ? null : parentComponent.shadowRoot;
- this.parentStack = [rootNodesParent];
- }
- RenderViewBuilder.prototype.build = function (context) {
- var cmds = this.cmds;
- for (var i = 0; i < cmds.length; i++) {
- cmds[i].visit(this, context);
- }
- };
- Object.defineProperty(RenderViewBuilder.prototype, "parent", {
- get: function () { return this.parentStack[this.parentStack.length - 1]; },
- enumerable: true,
- configurable: true
- });
- RenderViewBuilder.prototype.visitText = function (cmd, context) {
- var text = context.factory.createText(cmd.value);
- this._addChild(text, cmd.ngContentIndex, context);
- if (cmd.isBound) {
- context.boundTextNodes.push(text);
- }
- return null;
- };
- RenderViewBuilder.prototype.visitNgContent = function (cmd, context) {
- if (lang_1.isPresent(this.parentComponent)) {
- if (this.parentComponent.isRoot) {
- var insertionPoint = context.factory.createRootContentInsertionPoint();
- if (this.parent instanceof Component) {
- context.factory.appendChild(this.parent.shadowRoot, insertionPoint);
- }
- else {
- context.factory.appendChild(this.parent, insertionPoint);
- }
- context.rootContentInsertionPoints.push(insertionPoint);
- }
- else {
- var projectedNodes = this.parentComponent.project(cmd.index);
- for (var i = 0; i < projectedNodes.length; i++) {
- var node = projectedNodes[i];
- this._addChild(node, cmd.ngContentIndex, context);
- }
- }
- }
- return null;
- };
- RenderViewBuilder.prototype.visitBeginElement = function (cmd, context) {
- this.parentStack.push(this._beginElement(cmd, context, null));
- return null;
- };
- RenderViewBuilder.prototype.visitEndElement = function (context) {
- this._endElement();
- return null;
- };
- RenderViewBuilder.prototype.visitBeginComponent = function (cmd, context) {
- var templateId = cmd.templateId;
- var tpl = context.factory.resolveComponentTemplate(templateId);
- var el = this._beginElement(cmd, context, tpl);
- var root = el;
- if (tpl.encapsulation === metadata_1.ViewEncapsulation.Native) {
- root = context.factory.createShadowRoot(el, templateId);
- context.nativeShadowRoots.push(root);
- }
- var isRoot = context.componentCount === 0 && context.isHost;
- var component = new Component(el, root, isRoot, tpl);
- context.enqueueComponentBuilder(component);
- this.parentStack.push(component);
- return null;
- };
- RenderViewBuilder.prototype.visitEndComponent = function (context) {
- this._endElement();
- return null;
- };
- RenderViewBuilder.prototype.visitEmbeddedTemplate = function (cmd, context) {
- var el = context.factory.createTemplateAnchor(cmd.attrNameAndValues);
- this._addChild(el, cmd.ngContentIndex, context);
- context.boundElements.push(el);
- if (cmd.isMerged) {
- context.enqueueFragmentBuilder(this.parentComponent, this.template, cmd.children);
- }
- return null;
- };
- RenderViewBuilder.prototype._beginElement = function (cmd, context, componentTemplate) {
- var el = context.consumeInplaceElement();
- var attrNameAndValues = cmd.attrNameAndValues;
- var templateEmulatedEncapsulation = this.template.encapsulation === metadata_1.ViewEncapsulation.Emulated;
- var componentEmulatedEncapsulation = lang_1.isPresent(componentTemplate) &&
- componentTemplate.encapsulation === metadata_1.ViewEncapsulation.Emulated;
- var newAttrLength = attrNameAndValues.length + (templateEmulatedEncapsulation ? 2 : 0) +
- (componentEmulatedEncapsulation ? 2 : 0);
- if (newAttrLength > attrNameAndValues.length) {
- // Note: Need to clone attrNameAndValues to make it writable!
- var newAttrNameAndValues = collection_1.ListWrapper.createFixedSize(newAttrLength);
- var attrIndex;
- for (attrIndex = 0; attrIndex < attrNameAndValues.length; attrIndex++) {
- newAttrNameAndValues[attrIndex] = attrNameAndValues[attrIndex];
- }
- if (templateEmulatedEncapsulation) {
- newAttrNameAndValues[attrIndex++] = _shimContentAttribute(this.template.shortId);
- newAttrNameAndValues[attrIndex++] = '';
- }
- if (componentEmulatedEncapsulation) {
- newAttrNameAndValues[attrIndex++] = _shimHostAttribute(componentTemplate.shortId);
- newAttrNameAndValues[attrIndex++] = '';
- }
- attrNameAndValues = newAttrNameAndValues;
- }
- if (lang_1.isPresent(el)) {
- context.factory.mergeElement(el, attrNameAndValues);
- this.fragmentRootNodes.push(el);
- }
- else {
- el = context.factory.createElement(cmd.name, attrNameAndValues);
- this._addChild(el, cmd.ngContentIndex, context);
- }
- if (cmd.isBound) {
- var boundElementIndex = context.boundElements.length;
- context.boundElements.push(el);
- for (var i = 0; i < cmd.eventTargetAndNames.length; i += 2) {
- var target = cmd.eventTargetAndNames[i];
- var eventName = cmd.eventTargetAndNames[i + 1];
- context.addEventListener(boundElementIndex, target, eventName);
- }
- }
- return el;
- };
- RenderViewBuilder.prototype._endElement = function () { this.parentStack.pop(); };
- RenderViewBuilder.prototype._addChild = function (node, ngContentIndex, context) {
- var parent = this.parent;
- if (lang_1.isPresent(parent)) {
- if (parent instanceof Component) {
- parent.addContentNode(ngContentIndex, node, context);
- }
- else {
- context.factory.appendChild(parent, node);
- }
- }
- else {
- this.fragmentRootNodes.push(node);
- }
- };
- return RenderViewBuilder;
- })();
- var Component = (function () {
- function Component(hostElement, shadowRoot, isRoot, template) {
- this.hostElement = hostElement;
- this.shadowRoot = shadowRoot;
- this.isRoot = isRoot;
- this.template = template;
- this.contentNodesByNgContentIndex = [];
- }
- Component.prototype.addContentNode = function (ngContentIndex, node, context) {
- if (lang_1.isBlank(ngContentIndex)) {
- if (this.template.encapsulation === metadata_1.ViewEncapsulation.Native) {
- context.factory.appendChild(this.hostElement, node);
- }
- }
- else {
- while (this.contentNodesByNgContentIndex.length <= ngContentIndex) {
- this.contentNodesByNgContentIndex.push([]);
- }
- this.contentNodesByNgContentIndex[ngContentIndex].push(node);
- }
- };
- Component.prototype.project = function (ngContentIndex) {
- return ngContentIndex < this.contentNodesByNgContentIndex.length ?
- this.contentNodesByNgContentIndex[ngContentIndex] :
- [];
- };
- return Component;
- })();
- var COMPONENT_REGEX = /%COMP%/g;
- exports.COMPONENT_VARIABLE = '%COMP%';
- exports.HOST_ATTR = "_nghost-" + exports.COMPONENT_VARIABLE;
- exports.CONTENT_ATTR = "_ngcontent-" + exports.COMPONENT_VARIABLE;
- function _shimContentAttribute(componentShortId) {
- return lang_1.StringWrapper.replaceAll(exports.CONTENT_ATTR, COMPONENT_REGEX, componentShortId);
- }
- function _shimHostAttribute(componentShortId) {
- return lang_1.StringWrapper.replaceAll(exports.HOST_ATTR, COMPONENT_REGEX, componentShortId);
- }
- /***/ },
- /* 165 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var api_1 = __webpack_require__(72);
- var DefaultProtoViewRef = (function (_super) {
- __extends(DefaultProtoViewRef, _super);
- function DefaultProtoViewRef(template, cmds) {
- _super.call(this);
- this.template = template;
- this.cmds = cmds;
- }
- return DefaultProtoViewRef;
- })(api_1.RenderProtoViewRef);
- exports.DefaultProtoViewRef = DefaultProtoViewRef;
- var DefaultRenderFragmentRef = (function (_super) {
- __extends(DefaultRenderFragmentRef, _super);
- function DefaultRenderFragmentRef(nodes) {
- _super.call(this);
- this.nodes = nodes;
- }
- return DefaultRenderFragmentRef;
- })(api_1.RenderFragmentRef);
- exports.DefaultRenderFragmentRef = DefaultRenderFragmentRef;
- var DefaultRenderView = (function (_super) {
- __extends(DefaultRenderView, _super);
- function DefaultRenderView(fragments, boundTextNodes, boundElements, nativeShadowRoots, globalEventAdders, rootContentInsertionPoints) {
- _super.call(this);
- this.fragments = fragments;
- this.boundTextNodes = boundTextNodes;
- this.boundElements = boundElements;
- this.nativeShadowRoots = nativeShadowRoots;
- this.globalEventAdders = globalEventAdders;
- this.rootContentInsertionPoints = rootContentInsertionPoints;
- this.hydrated = false;
- this.eventDispatcher = null;
- this.globalEventRemovers = null;
- }
- DefaultRenderView.prototype.hydrate = function () {
- if (this.hydrated)
- throw new exceptions_1.BaseException('The view is already hydrated.');
- this.hydrated = true;
- this.globalEventRemovers = collection_1.ListWrapper.createFixedSize(this.globalEventAdders.length);
- for (var i = 0; i < this.globalEventAdders.length; i++) {
- this.globalEventRemovers[i] = this.globalEventAdders[i]();
- }
- };
- DefaultRenderView.prototype.dehydrate = function () {
- if (!this.hydrated)
- throw new exceptions_1.BaseException('The view is already dehydrated.');
- for (var i = 0; i < this.globalEventRemovers.length; i++) {
- this.globalEventRemovers[i]();
- }
- this.globalEventRemovers = null;
- this.hydrated = false;
- };
- DefaultRenderView.prototype.setEventDispatcher = function (dispatcher) { this.eventDispatcher = dispatcher; };
- DefaultRenderView.prototype.dispatchRenderEvent = function (boundElementIndex, eventName, event) {
- var allowDefaultBehavior = true;
- if (lang_1.isPresent(this.eventDispatcher)) {
- var locals = new collection_1.Map();
- locals.set('$event', event);
- allowDefaultBehavior =
- this.eventDispatcher.dispatchRenderEvent(boundElementIndex, eventName, locals);
- }
- return allowDefaultBehavior;
- };
- return DefaultRenderView;
- })(api_1.RenderViewRef);
- exports.DefaultRenderView = DefaultRenderView;
- /***/ },
- /* 166 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var template_commands_1 = __webpack_require__(96);
- var template_ast_1 = __webpack_require__(159);
- var source_module_1 = __webpack_require__(156);
- var util_1 = __webpack_require__(155);
- var di_1 = __webpack_require__(6);
- exports.TEMPLATE_COMMANDS_MODULE_REF = source_module_1.moduleRef("package:angular2/src/core/linker/template_commands" + util_1.MODULE_SUFFIX);
- var IMPLICIT_TEMPLATE_VAR = '\$implicit';
- var CLASS_ATTR = 'class';
- var STYLE_ATTR = 'style';
- var CommandCompiler = (function () {
- function CommandCompiler() {
- }
- CommandCompiler.prototype.compileComponentRuntime = function (component, template, changeDetectorFactories, componentTemplateFactory) {
- var visitor = new CommandBuilderVisitor(new RuntimeCommandFactory(component, componentTemplateFactory, changeDetectorFactories), 0);
- template_ast_1.templateVisitAll(visitor, template);
- return visitor.result;
- };
- CommandCompiler.prototype.compileComponentCodeGen = function (component, template, changeDetectorFactoryExpressions, componentTemplateFactory) {
- var visitor = new CommandBuilderVisitor(new CodegenCommandFactory(component, componentTemplateFactory, changeDetectorFactoryExpressions), 0);
- template_ast_1.templateVisitAll(visitor, template);
- return new source_module_1.SourceExpression([], codeGenArray(visitor.result));
- };
- CommandCompiler = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], CommandCompiler);
- return CommandCompiler;
- })();
- exports.CommandCompiler = CommandCompiler;
- var RuntimeCommandFactory = (function () {
- function RuntimeCommandFactory(component, componentTemplateFactory, changeDetectorFactories) {
- this.component = component;
- this.componentTemplateFactory = componentTemplateFactory;
- this.changeDetectorFactories = changeDetectorFactories;
- }
- RuntimeCommandFactory.prototype._mapDirectives = function (directives) {
- return directives.map(function (directive) { return directive.type.runtime; });
- };
- RuntimeCommandFactory.prototype.createText = function (value, isBound, ngContentIndex) {
- return new template_commands_1.TextCmd(value, isBound, ngContentIndex);
- };
- RuntimeCommandFactory.prototype.createNgContent = function (index, ngContentIndex) {
- return new template_commands_1.NgContentCmd(index, ngContentIndex);
- };
- RuntimeCommandFactory.prototype.createBeginElement = function (name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, isBound, ngContentIndex) {
- return new template_commands_1.BeginElementCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, this._mapDirectives(directives), isBound, ngContentIndex);
- };
- RuntimeCommandFactory.prototype.createEndElement = function () { return new template_commands_1.EndElementCmd(); };
- RuntimeCommandFactory.prototype.createBeginComponent = function (name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, encapsulation, ngContentIndex) {
- var nestedTemplateAccessor = this.componentTemplateFactory(directives[0]);
- return new template_commands_1.BeginComponentCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, this._mapDirectives(directives), encapsulation, ngContentIndex, nestedTemplateAccessor);
- };
- RuntimeCommandFactory.prototype.createEndComponent = function () { return new template_commands_1.EndComponentCmd(); };
- RuntimeCommandFactory.prototype.createEmbeddedTemplate = function (embeddedTemplateIndex, attrNameAndValues, variableNameAndValues, directives, isMerged, ngContentIndex, children) {
- return new template_commands_1.EmbeddedTemplateCmd(attrNameAndValues, variableNameAndValues, this._mapDirectives(directives), isMerged, ngContentIndex, this.changeDetectorFactories[embeddedTemplateIndex], children);
- };
- return RuntimeCommandFactory;
- })();
- var CodegenCommandFactory = (function () {
- function CodegenCommandFactory(component, componentTemplateFactory, changeDetectorFactoryExpressions) {
- this.component = component;
- this.componentTemplateFactory = componentTemplateFactory;
- this.changeDetectorFactoryExpressions = changeDetectorFactoryExpressions;
- }
- CodegenCommandFactory.prototype.createText = function (value, isBound, ngContentIndex) {
- return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'TextCmd') + "(" + util_1.escapeSingleQuoteString(value) + ", " + isBound + ", " + ngContentIndex + ")");
- };
- CodegenCommandFactory.prototype.createNgContent = function (index, ngContentIndex) {
- return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'NgContentCmd') + "(" + index + ", " + ngContentIndex + ")");
- };
- CodegenCommandFactory.prototype.createBeginElement = function (name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, isBound, ngContentIndex) {
- var attrsExpression = codeGenArray(attrNameAndValues);
- return new Expression((util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'BeginElementCmd') + "(" + util_1.escapeSingleQuoteString(name) + ", " + attrsExpression + ", ") +
- (codeGenArray(eventTargetAndNames) + ", " + codeGenArray(variableNameAndValues) + ", " + codeGenDirectivesArray(directives) + ", " + isBound + ", " + ngContentIndex + ")"));
- };
- CodegenCommandFactory.prototype.createEndElement = function () {
- return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'EndElementCmd') + "()");
- };
- CodegenCommandFactory.prototype.createBeginComponent = function (name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, encapsulation, ngContentIndex) {
- var attrsExpression = codeGenArray(attrNameAndValues);
- return new Expression((util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'BeginComponentCmd') + "(" + util_1.escapeSingleQuoteString(name) + ", " + attrsExpression + ", ") +
- (codeGenArray(eventTargetAndNames) + ", " + codeGenArray(variableNameAndValues) + ", " + codeGenDirectivesArray(directives) + ", " + codeGenViewEncapsulation(encapsulation) + ", " + ngContentIndex + ", " + this.componentTemplateFactory(directives[0]) + ")"));
- };
- CodegenCommandFactory.prototype.createEndComponent = function () {
- return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'EndComponentCmd') + "()");
- };
- CodegenCommandFactory.prototype.createEmbeddedTemplate = function (embeddedTemplateIndex, attrNameAndValues, variableNameAndValues, directives, isMerged, ngContentIndex, children) {
- return new Expression((util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'EmbeddedTemplateCmd') + "(" + codeGenArray(attrNameAndValues) + ", " + codeGenArray(variableNameAndValues) + ", ") +
- (codeGenDirectivesArray(directives) + ", " + isMerged + ", " + ngContentIndex + ", " + this.changeDetectorFactoryExpressions[embeddedTemplateIndex] + ", " + codeGenArray(children) + ")"));
- };
- return CodegenCommandFactory;
- })();
- function visitAndReturnContext(visitor, asts, context) {
- template_ast_1.templateVisitAll(visitor, asts, context);
- return context;
- }
- var CommandBuilderVisitor = (function () {
- function CommandBuilderVisitor(commandFactory, embeddedTemplateIndex) {
- this.commandFactory = commandFactory;
- this.embeddedTemplateIndex = embeddedTemplateIndex;
- this.result = [];
- this.transitiveNgContentCount = 0;
- }
- CommandBuilderVisitor.prototype._readAttrNameAndValues = function (directives, attrAsts) {
- var attrs = keyValueArrayToMap(visitAndReturnContext(this, attrAsts, []));
- directives.forEach(function (directiveMeta) {
- collection_1.StringMapWrapper.forEach(directiveMeta.hostAttributes, function (value, name) {
- var prevValue = attrs[name];
- attrs[name] = lang_1.isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
- });
- });
- return mapToKeyValueArray(attrs);
- };
- CommandBuilderVisitor.prototype.visitNgContent = function (ast, context) {
- this.transitiveNgContentCount++;
- this.result.push(this.commandFactory.createNgContent(ast.index, ast.ngContentIndex));
- return null;
- };
- CommandBuilderVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
- var _this = this;
- this.embeddedTemplateIndex++;
- var childVisitor = new CommandBuilderVisitor(this.commandFactory, this.embeddedTemplateIndex);
- template_ast_1.templateVisitAll(childVisitor, ast.children);
- var isMerged = childVisitor.transitiveNgContentCount > 0;
- var variableNameAndValues = [];
- ast.vars.forEach(function (varAst) {
- variableNameAndValues.push(varAst.name);
- variableNameAndValues.push(varAst.value.length > 0 ? varAst.value : IMPLICIT_TEMPLATE_VAR);
- });
- var directives = [];
- collection_1.ListWrapper.forEachWithIndex(ast.directives, function (directiveAst, index) {
- directiveAst.visit(_this, new DirectiveContext(index, [], [], directives));
- });
- this.result.push(this.commandFactory.createEmbeddedTemplate(this.embeddedTemplateIndex, this._readAttrNameAndValues(directives, ast.attrs), variableNameAndValues, directives, isMerged, ast.ngContentIndex, childVisitor.result));
- this.transitiveNgContentCount += childVisitor.transitiveNgContentCount;
- this.embeddedTemplateIndex = childVisitor.embeddedTemplateIndex;
- return null;
- };
- CommandBuilderVisitor.prototype.visitElement = function (ast, context) {
- var _this = this;
- var component = ast.getComponent();
- var eventTargetAndNames = visitAndReturnContext(this, ast.outputs, []);
- var variableNameAndValues = [];
- if (lang_1.isBlank(component)) {
- ast.exportAsVars.forEach(function (varAst) {
- variableNameAndValues.push(varAst.name);
- variableNameAndValues.push(null);
- });
- }
- var directives = [];
- collection_1.ListWrapper.forEachWithIndex(ast.directives, function (directiveAst, index) {
- directiveAst.visit(_this, new DirectiveContext(index, eventTargetAndNames, variableNameAndValues, directives));
- });
- eventTargetAndNames = removeKeyValueArrayDuplicates(eventTargetAndNames);
- var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs);
- if (lang_1.isPresent(component)) {
- this.result.push(this.commandFactory.createBeginComponent(ast.name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, component.template.encapsulation, ast.ngContentIndex));
- template_ast_1.templateVisitAll(this, ast.children);
- this.result.push(this.commandFactory.createEndComponent());
- }
- else {
- this.result.push(this.commandFactory.createBeginElement(ast.name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, ast.isBound(), ast.ngContentIndex));
- template_ast_1.templateVisitAll(this, ast.children);
- this.result.push(this.commandFactory.createEndElement());
- }
- return null;
- };
- CommandBuilderVisitor.prototype.visitVariable = function (ast, ctx) { return null; };
- CommandBuilderVisitor.prototype.visitAttr = function (ast, attrNameAndValues) {
- attrNameAndValues.push(ast.name);
- attrNameAndValues.push(ast.value);
- return null;
- };
- CommandBuilderVisitor.prototype.visitBoundText = function (ast, context) {
- this.result.push(this.commandFactory.createText(null, true, ast.ngContentIndex));
- return null;
- };
- CommandBuilderVisitor.prototype.visitText = function (ast, context) {
- this.result.push(this.commandFactory.createText(ast.value, false, ast.ngContentIndex));
- return null;
- };
- CommandBuilderVisitor.prototype.visitDirective = function (ast, ctx) {
- ctx.targetDirectives.push(ast.directive);
- template_ast_1.templateVisitAll(this, ast.hostEvents, ctx.eventTargetAndNames);
- ast.exportAsVars.forEach(function (varAst) {
- ctx.targetVariableNameAndValues.push(varAst.name);
- ctx.targetVariableNameAndValues.push(ctx.index);
- });
- return null;
- };
- CommandBuilderVisitor.prototype.visitEvent = function (ast, eventTargetAndNames) {
- eventTargetAndNames.push(ast.target);
- eventTargetAndNames.push(ast.name);
- return null;
- };
- CommandBuilderVisitor.prototype.visitDirectiveProperty = function (ast, context) { return null; };
- CommandBuilderVisitor.prototype.visitElementProperty = function (ast, context) { return null; };
- return CommandBuilderVisitor;
- })();
- function removeKeyValueArrayDuplicates(keyValueArray) {
- var knownPairs = new Set();
- var resultKeyValueArray = [];
- for (var i = 0; i < keyValueArray.length; i += 2) {
- var key = keyValueArray[i];
- var value = keyValueArray[i + 1];
- var pairId = key + ":" + value;
- if (!collection_1.SetWrapper.has(knownPairs, pairId)) {
- resultKeyValueArray.push(key);
- resultKeyValueArray.push(value);
- knownPairs.add(pairId);
- }
- }
- return resultKeyValueArray;
- }
- function keyValueArrayToMap(keyValueArr) {
- var data = {};
- for (var i = 0; i < keyValueArr.length; i += 2) {
- data[keyValueArr[i]] = keyValueArr[i + 1];
- }
- return data;
- }
- function mapToKeyValueArray(data) {
- var entryArray = [];
- collection_1.StringMapWrapper.forEach(data, function (value, name) { entryArray.push([name, value]); });
- // We need to sort to get a defined output order
- // for tests and for caching generated artifacts...
- collection_1.ListWrapper.sort(entryArray, function (entry1, entry2) { return lang_1.StringWrapper.compare(entry1[0], entry2[0]); });
- var keyValueArray = [];
- entryArray.forEach(function (entry) {
- keyValueArray.push(entry[0]);
- keyValueArray.push(entry[1]);
- });
- return keyValueArray;
- }
- function mergeAttributeValue(attrName, attrValue1, attrValue2) {
- if (attrName == CLASS_ATTR || attrName == STYLE_ATTR) {
- return attrValue1 + " " + attrValue2;
- }
- else {
- return attrValue2;
- }
- }
- var DirectiveContext = (function () {
- function DirectiveContext(index, eventTargetAndNames, targetVariableNameAndValues, targetDirectives) {
- this.index = index;
- this.eventTargetAndNames = eventTargetAndNames;
- this.targetVariableNameAndValues = targetVariableNameAndValues;
- this.targetDirectives = targetDirectives;
- }
- return DirectiveContext;
- })();
- var Expression = (function () {
- function Expression(value) {
- this.value = value;
- }
- return Expression;
- })();
- function escapeValue(value) {
- if (value instanceof Expression) {
- return value.value;
- }
- else if (lang_1.isString(value)) {
- return util_1.escapeSingleQuoteString(value);
- }
- else if (lang_1.isBlank(value)) {
- return 'null';
- }
- else {
- return "" + value;
- }
- }
- function codeGenArray(data) {
- var base = "[" + data.map(escapeValue).join(',') + "]";
- return lang_1.IS_DART ? "const " + base : base;
- }
- function codeGenDirectivesArray(directives) {
- var expressions = directives.map(function (directiveType) { return ("" + source_module_1.moduleRef(directiveType.type.moduleUrl) + directiveType.type.name); });
- var base = "[" + expressions.join(',') + "]";
- return lang_1.IS_DART ? "const " + base : base;
- }
- function codeGenViewEncapsulation(value) {
- if (lang_1.IS_DART) {
- return "" + exports.TEMPLATE_COMMANDS_MODULE_REF + value;
- }
- else {
- return "" + value;
- }
- }
- /***/ },
- /* 167 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- var lang_2 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var change_detection_1 = __webpack_require__(25);
- var html_parser_1 = __webpack_require__(168);
- var html_tags_1 = __webpack_require__(172);
- var parse_util_1 = __webpack_require__(171);
- var template_ast_1 = __webpack_require__(159);
- var selector_1 = __webpack_require__(154);
- var element_schema_registry_1 = __webpack_require__(173);
- var template_preparser_1 = __webpack_require__(174);
- var style_url_resolver_1 = __webpack_require__(163);
- var html_ast_1 = __webpack_require__(169);
- var util_1 = __webpack_require__(155);
- // Group 1 = "bind-"
- // Group 2 = "var-" or "#"
- // Group 3 = "on-"
- // Group 4 = "bindon-"
- // Group 5 = the identifier after "bind-", "var-/#", or "on-"
- // Group 6 = idenitifer inside [()]
- // Group 7 = idenitifer inside []
- // Group 8 = identifier inside ()
- var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g;
- var TEMPLATE_ELEMENT = 'template';
- var TEMPLATE_ATTR = 'template';
- var TEMPLATE_ATTR_PREFIX = '*';
- var CLASS_ATTR = 'class';
- var PROPERTY_PARTS_SEPARATOR = '.';
- var ATTRIBUTE_PREFIX = 'attr';
- var CLASS_PREFIX = 'class';
- var STYLE_PREFIX = 'style';
- var TEXT_CSS_SELECTOR = selector_1.CssSelector.parse('*')[0];
- /**
- * Provides an array of {@link TemplateAstVisitor}s which will be used to transform
- * parsed templates before compilation is invoked, allowing custom expression syntax
- * and other advanced transformations.
- *
- * This is currently an internal-only feature and not meant for general use.
- */
- exports.TEMPLATE_TRANSFORMS = lang_2.CONST_EXPR(new core_1.OpaqueToken('TemplateTransforms'));
- var TemplateParseError = (function (_super) {
- __extends(TemplateParseError, _super);
- function TemplateParseError(message, location) {
- _super.call(this, location, message);
- }
- return TemplateParseError;
- })(parse_util_1.ParseError);
- exports.TemplateParseError = TemplateParseError;
- var TemplateParser = (function () {
- function TemplateParser(_exprParser, _schemaRegistry, _htmlParser, transforms) {
- this._exprParser = _exprParser;
- this._schemaRegistry = _schemaRegistry;
- this._htmlParser = _htmlParser;
- this.transforms = transforms;
- }
- TemplateParser.prototype.parse = function (template, directives, templateUrl) {
- var parseVisitor = new TemplateParseVisitor(directives, this._exprParser, this._schemaRegistry);
- var htmlAstWithErrors = this._htmlParser.parse(template, templateUrl);
- var result = html_ast_1.htmlVisitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_COMPONENT);
- var errors = htmlAstWithErrors.errors.concat(parseVisitor.errors);
- if (errors.length > 0) {
- var errorString = errors.join('\n');
- throw new exceptions_1.BaseException("Template parse errors:\n" + errorString);
- }
- if (lang_1.isPresent(this.transforms)) {
- this.transforms.forEach(function (transform) { result = template_ast_1.templateVisitAll(transform, result); });
- }
- return result;
- };
- TemplateParser = __decorate([
- core_1.Injectable(),
- __param(3, core_1.Optional()),
- __param(3, core_1.Inject(exports.TEMPLATE_TRANSFORMS)),
- __metadata('design:paramtypes', [change_detection_1.Parser, element_schema_registry_1.ElementSchemaRegistry, html_parser_1.HtmlParser, Array])
- ], TemplateParser);
- return TemplateParser;
- })();
- exports.TemplateParser = TemplateParser;
- var TemplateParseVisitor = (function () {
- function TemplateParseVisitor(directives, _exprParser, _schemaRegistry) {
- var _this = this;
- this._exprParser = _exprParser;
- this._schemaRegistry = _schemaRegistry;
- this.errors = [];
- this.directivesIndex = new Map();
- this.ngContentCount = 0;
- this.selectorMatcher = new selector_1.SelectorMatcher();
- collection_1.ListWrapper.forEachWithIndex(directives, function (directive, index) {
- var selector = selector_1.CssSelector.parse(directive.selector);
- _this.selectorMatcher.addSelectables(selector, directive);
- _this.directivesIndex.set(directive, index);
- });
- }
- TemplateParseVisitor.prototype._reportError = function (message, sourceSpan) {
- this.errors.push(new TemplateParseError(message, sourceSpan.start));
- };
- TemplateParseVisitor.prototype._parseInterpolation = function (value, sourceSpan) {
- var sourceInfo = sourceSpan.start.toString();
- try {
- return this._exprParser.parseInterpolation(value, sourceInfo);
- }
- catch (e) {
- this._reportError("" + e, sourceSpan);
- return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
- }
- };
- TemplateParseVisitor.prototype._parseAction = function (value, sourceSpan) {
- var sourceInfo = sourceSpan.start.toString();
- try {
- return this._exprParser.parseAction(value, sourceInfo);
- }
- catch (e) {
- this._reportError("" + e, sourceSpan);
- return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
- }
- };
- TemplateParseVisitor.prototype._parseBinding = function (value, sourceSpan) {
- var sourceInfo = sourceSpan.start.toString();
- try {
- return this._exprParser.parseBinding(value, sourceInfo);
- }
- catch (e) {
- this._reportError("" + e, sourceSpan);
- return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo);
- }
- };
- TemplateParseVisitor.prototype._parseTemplateBindings = function (value, sourceSpan) {
- var sourceInfo = sourceSpan.start.toString();
- try {
- return this._exprParser.parseTemplateBindings(value, sourceInfo);
- }
- catch (e) {
- this._reportError("" + e, sourceSpan);
- return [];
- }
- };
- TemplateParseVisitor.prototype.visitText = function (ast, component) {
- var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
- var expr = this._parseInterpolation(ast.value, ast.sourceSpan);
- if (lang_1.isPresent(expr)) {
- return new template_ast_1.BoundTextAst(expr, ngContentIndex, ast.sourceSpan);
- }
- else {
- return new template_ast_1.TextAst(ast.value, ngContentIndex, ast.sourceSpan);
- }
- };
- TemplateParseVisitor.prototype.visitAttr = function (ast, contex) {
- return new template_ast_1.AttrAst(ast.name, ast.value, ast.sourceSpan);
- };
- TemplateParseVisitor.prototype.visitElement = function (element, component) {
- var _this = this;
- var nodeName = element.name;
- var preparsedElement = template_preparser_1.preparseElement(element);
- if (preparsedElement.type === template_preparser_1.PreparsedElementType.SCRIPT ||
- preparsedElement.type === template_preparser_1.PreparsedElementType.STYLE) {
- // Skipping <script> for security reasons
- // Skipping <style> as we already processed them
- // in the StyleCompiler
- return null;
- }
- if (preparsedElement.type === template_preparser_1.PreparsedElementType.STYLESHEET &&
- style_url_resolver_1.isStyleUrlResolvable(preparsedElement.hrefAttr)) {
- // Skipping stylesheets with either relative urls or package scheme as we already processed
- // them in the StyleCompiler
- return null;
- }
- var matchableAttrs = [];
- var elementOrDirectiveProps = [];
- var vars = [];
- var events = [];
- var templateElementOrDirectiveProps = [];
- var templateVars = [];
- var templateMatchableAttrs = [];
- var hasInlineTemplates = false;
- var attrs = [];
- element.attrs.forEach(function (attr) {
- matchableAttrs.push([attr.name, attr.value]);
- var hasBinding = _this._parseAttr(attr, matchableAttrs, elementOrDirectiveProps, events, vars);
- var hasTemplateBinding = _this._parseInlineTemplateBinding(attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateVars);
- if (!hasBinding && !hasTemplateBinding) {
- // don't include the bindings as attributes as well in the AST
- attrs.push(_this.visitAttr(attr, null));
- }
- if (hasTemplateBinding) {
- hasInlineTemplates = true;
- }
- });
- var lcElName = html_tags_1.splitNsName(nodeName.toLowerCase())[1];
- var isTemplateElement = lcElName == TEMPLATE_ELEMENT;
- var elementCssSelector = createElementCssSelector(nodeName, matchableAttrs);
- var directives = this._createDirectiveAsts(element.name, this._parseDirectives(this.selectorMatcher, elementCssSelector), elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceSpan);
- var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directives);
- var children = html_ast_1.htmlVisitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, Component.create(directives));
- var elementNgContentIndex = hasInlineTemplates ? null : component.findNgContentIndex(elementCssSelector);
- var parsedElement;
- if (preparsedElement.type === template_preparser_1.PreparsedElementType.NG_CONTENT) {
- if (lang_1.isPresent(element.children) && element.children.length > 0) {
- this._reportError("<ng-content> element cannot have content. <ng-content> must be immediately followed by </ng-content>", element.sourceSpan);
- }
- parsedElement =
- new template_ast_1.NgContentAst(this.ngContentCount++, elementNgContentIndex, element.sourceSpan);
- }
- else if (isTemplateElement) {
- this._assertAllEventsPublishedByDirectives(directives, events);
- this._assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps, element.sourceSpan);
- parsedElement = new template_ast_1.EmbeddedTemplateAst(attrs, events, vars, directives, children, elementNgContentIndex, element.sourceSpan);
- }
- else {
- this._assertOnlyOneComponent(directives, element.sourceSpan);
- var elementExportAsVars = vars.filter(function (varAst) { return varAst.value.length === 0; });
- parsedElement =
- new template_ast_1.ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives, children, elementNgContentIndex, element.sourceSpan);
- }
- if (hasInlineTemplates) {
- var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs);
- var templateDirectives = this._createDirectiveAsts(element.name, this._parseDirectives(this.selectorMatcher, templateCssSelector), templateElementOrDirectiveProps, [], element.sourceSpan);
- var templateElementProps = this._createElementPropertyAsts(element.name, templateElementOrDirectiveProps, templateDirectives);
- this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectives, templateElementProps, element.sourceSpan);
- parsedElement = new template_ast_1.EmbeddedTemplateAst([], [], templateVars, templateDirectives, [parsedElement], component.findNgContentIndex(templateCssSelector), element.sourceSpan);
- }
- return parsedElement;
- };
- TemplateParseVisitor.prototype._parseInlineTemplateBinding = function (attr, targetMatchableAttrs, targetProps, targetVars) {
- var templateBindingsSource = null;
- if (attr.name == TEMPLATE_ATTR) {
- templateBindingsSource = attr.value;
- }
- else if (attr.name.startsWith(TEMPLATE_ATTR_PREFIX)) {
- var key = attr.name.substring(TEMPLATE_ATTR_PREFIX.length); // remove the star
- templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value;
- }
- if (lang_1.isPresent(templateBindingsSource)) {
- var bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan);
- for (var i = 0; i < bindings.length; i++) {
- var binding = bindings[i];
- if (binding.keyIsVar) {
- targetVars.push(new template_ast_1.VariableAst(binding.key, binding.name, attr.sourceSpan));
- targetMatchableAttrs.push([binding.key, binding.name]);
- }
- else if (lang_1.isPresent(binding.expression)) {
- this._parsePropertyAst(binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps);
- }
- else {
- targetMatchableAttrs.push([binding.key, '']);
- this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps);
- }
- }
- return true;
- }
- return false;
- };
- TemplateParseVisitor.prototype._parseAttr = function (attr, targetMatchableAttrs, targetProps, targetEvents, targetVars) {
- var attrName = this._normalizeAttributeName(attr.name);
- var attrValue = attr.value;
- var bindParts = lang_1.RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName);
- var hasBinding = false;
- if (lang_1.isPresent(bindParts)) {
- hasBinding = true;
- if (lang_1.isPresent(bindParts[1])) {
- this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps);
- }
- else if (lang_1.isPresent(bindParts[2])) {
- var identifier = bindParts[5];
- this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars);
- }
- else if (lang_1.isPresent(bindParts[3])) {
- this._parseEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents);
- }
- else if (lang_1.isPresent(bindParts[4])) {
- this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps);
- this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents);
- }
- else if (lang_1.isPresent(bindParts[6])) {
- this._parseProperty(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps);
- this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents);
- }
- else if (lang_1.isPresent(bindParts[7])) {
- this._parseProperty(bindParts[7], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps);
- }
- else if (lang_1.isPresent(bindParts[8])) {
- this._parseEvent(bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents);
- }
- }
- else {
- hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps);
- }
- if (!hasBinding) {
- this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps);
- }
- return hasBinding;
- };
- TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
- return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName;
- };
- TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
- if (identifier.indexOf('-') > -1) {
- this._reportError("\"-\" is not allowed in variable names", sourceSpan);
- }
- targetVars.push(new template_ast_1.VariableAst(identifier, value, sourceSpan));
- };
- TemplateParseVisitor.prototype._parseProperty = function (name, expression, sourceSpan, targetMatchableAttrs, targetProps) {
- this._parsePropertyAst(name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps);
- };
- TemplateParseVisitor.prototype._parsePropertyInterpolation = function (name, value, sourceSpan, targetMatchableAttrs, targetProps) {
- var expr = this._parseInterpolation(value, sourceSpan);
- if (lang_1.isPresent(expr)) {
- this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps);
- return true;
- }
- return false;
- };
- TemplateParseVisitor.prototype._parsePropertyAst = function (name, ast, sourceSpan, targetMatchableAttrs, targetProps) {
- targetMatchableAttrs.push([name, ast.source]);
- targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan));
- };
- TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) {
- this._parseEvent(name + "Change", expression + "=$event", sourceSpan, targetMatchableAttrs, targetEvents);
- };
- TemplateParseVisitor.prototype._parseEvent = function (name, expression, sourceSpan, targetMatchableAttrs, targetEvents) {
- // long format: 'target: eventName'
- var parts = util_1.splitAtColon(name, [null, name]);
- var target = parts[0];
- var eventName = parts[1];
- targetEvents.push(new template_ast_1.BoundEventAst(eventName, target, this._parseAction(expression, sourceSpan), sourceSpan));
- // Don't detect directives for event names for now,
- // so don't add the event name to the matchableAttrs
- };
- TemplateParseVisitor.prototype._parseLiteralAttr = function (name, value, sourceSpan, targetProps) {
- targetProps.push(new BoundElementOrDirectiveProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan));
- };
- TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
- var _this = this;
- var directives = [];
- selectorMatcher.match(elementCssSelector, function (selector, directive) { directives.push(directive); });
- // Need to sort the directives so that we get consistent results throughout,
- // as selectorMatcher uses Maps inside.
- // Also need to make components the first directive in the array
- collection_1.ListWrapper.sort(directives, function (dir1, dir2) {
- var dir1Comp = dir1.isComponent;
- var dir2Comp = dir2.isComponent;
- if (dir1Comp && !dir2Comp) {
- return -1;
- }
- else if (!dir1Comp && dir2Comp) {
- return 1;
- }
- else {
- return _this.directivesIndex.get(dir1) - _this.directivesIndex.get(dir2);
- }
- });
- return directives;
- };
- TemplateParseVisitor.prototype._createDirectiveAsts = function (elementName, directives, props, possibleExportAsVars, sourceSpan) {
- var _this = this;
- var matchedVariables = new Set();
- var directiveAsts = directives.map(function (directive) {
- var hostProperties = [];
- var hostEvents = [];
- var directiveProperties = [];
- _this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceSpan, hostProperties);
- _this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents);
- _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties);
- var exportAsVars = [];
- possibleExportAsVars.forEach(function (varAst) {
- if ((varAst.value.length === 0 && directive.isComponent) ||
- (directive.exportAs == varAst.value)) {
- exportAsVars.push(varAst);
- matchedVariables.add(varAst.name);
- }
- });
- return new template_ast_1.DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, exportAsVars, sourceSpan);
- });
- possibleExportAsVars.forEach(function (varAst) {
- if (varAst.value.length > 0 && !collection_1.SetWrapper.has(matchedVariables, varAst.name)) {
- _this._reportError("There is no directive with \"exportAs\" set to \"" + varAst.value + "\"", varAst.sourceSpan);
- }
- });
- return directiveAsts;
- };
- TemplateParseVisitor.prototype._createDirectiveHostPropertyAsts = function (elementName, hostProps, sourceSpan, targetPropertyAsts) {
- var _this = this;
- if (lang_1.isPresent(hostProps)) {
- collection_1.StringMapWrapper.forEach(hostProps, function (expression, propName) {
- var exprAst = _this._parseBinding(expression, sourceSpan);
- targetPropertyAsts.push(_this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan));
- });
- }
- };
- TemplateParseVisitor.prototype._createDirectiveHostEventAsts = function (hostListeners, sourceSpan, targetEventAsts) {
- var _this = this;
- if (lang_1.isPresent(hostListeners)) {
- collection_1.StringMapWrapper.forEach(hostListeners, function (expression, propName) {
- _this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts);
- });
- }
- };
- TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps) {
- if (lang_1.isPresent(directiveProperties)) {
- var boundPropsByName = new Map();
- boundProps.forEach(function (boundProp) {
- var prevValue = boundPropsByName.get(boundProp.name);
- if (lang_1.isBlank(prevValue) || prevValue.isLiteral) {
- // give [a]="b" a higher precedence than a="b" on the same element
- boundPropsByName.set(boundProp.name, boundProp);
- }
- });
- collection_1.StringMapWrapper.forEach(directiveProperties, function (elProp, dirProp) {
- var boundProp = boundPropsByName.get(elProp);
- // Bindings are optional, so this binding only needs to be set up if an expression is given.
- if (lang_1.isPresent(boundProp)) {
- targetBoundDirectiveProps.push(new template_ast_1.BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
- }
- });
- }
- };
- TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, directives) {
- var _this = this;
- var boundElementProps = [];
- var boundDirectivePropsIndex = new Map();
- directives.forEach(function (directive) {
- directive.inputs.forEach(function (prop) {
- boundDirectivePropsIndex.set(prop.templateName, prop);
- });
- });
- props.forEach(function (prop) {
- if (!prop.isLiteral && lang_1.isBlank(boundDirectivePropsIndex.get(prop.name))) {
- boundElementProps.push(_this._createElementPropertyAst(elementName, prop.name, prop.expression, prop.sourceSpan));
- }
- });
- return boundElementProps;
- };
- TemplateParseVisitor.prototype._createElementPropertyAst = function (elementName, name, ast, sourceSpan) {
- var unit = null;
- var bindingType;
- var boundPropertyName;
- var parts = name.split(PROPERTY_PARTS_SEPARATOR);
- if (parts.length === 1) {
- boundPropertyName = this._schemaRegistry.getMappedPropName(parts[0]);
- bindingType = template_ast_1.PropertyBindingType.Property;
- if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName)) {
- this._reportError("Can't bind to '" + boundPropertyName + "' since it isn't a known native property", sourceSpan);
- }
- }
- else {
- if (parts[0] == ATTRIBUTE_PREFIX) {
- boundPropertyName = parts[1];
- bindingType = template_ast_1.PropertyBindingType.Attribute;
- }
- else if (parts[0] == CLASS_PREFIX) {
- boundPropertyName = parts[1];
- bindingType = template_ast_1.PropertyBindingType.Class;
- }
- else if (parts[0] == STYLE_PREFIX) {
- unit = parts.length > 2 ? parts[2] : null;
- boundPropertyName = parts[1];
- bindingType = template_ast_1.PropertyBindingType.Style;
- }
- else {
- this._reportError("Invalid property name '" + name + "'", sourceSpan);
- bindingType = null;
- }
- }
- return new template_ast_1.BoundElementPropertyAst(boundPropertyName, bindingType, ast, unit, sourceSpan);
- };
- TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
- var componentTypeNames = [];
- directives.forEach(function (directive) {
- var typeName = directive.directive.type.name;
- if (directive.directive.isComponent) {
- componentTypeNames.push(typeName);
- }
- });
- return componentTypeNames;
- };
- TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
- var componentTypeNames = this._findComponentDirectiveNames(directives);
- if (componentTypeNames.length > 1) {
- this._reportError("More than one component: " + componentTypeNames.join(','), sourceSpan);
- }
- };
- TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
- var _this = this;
- var componentTypeNames = this._findComponentDirectiveNames(directives);
- if (componentTypeNames.length > 0) {
- this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
- }
- elementProps.forEach(function (prop) {
- _this._reportError("Property binding " + prop.name + " not used by any directive on an embedded template", sourceSpan);
- });
- };
- TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
- var _this = this;
- var allDirectiveEvents = new Set();
- directives.forEach(function (directive) {
- collection_1.StringMapWrapper.forEach(directive.directive.outputs, function (eventName, _) { allDirectiveEvents.add(eventName); });
- });
- events.forEach(function (event) {
- if (lang_1.isPresent(event.target) || !collection_1.SetWrapper.has(allDirectiveEvents, event.name)) {
- _this._reportError("Event binding " + event.fullName + " not emitted by any directive on an embedded template", event.sourceSpan);
- }
- });
- };
- return TemplateParseVisitor;
- })();
- var NonBindableVisitor = (function () {
- function NonBindableVisitor() {
- }
- NonBindableVisitor.prototype.visitElement = function (ast, component) {
- var preparsedElement = template_preparser_1.preparseElement(ast);
- if (preparsedElement.type === template_preparser_1.PreparsedElementType.SCRIPT ||
- preparsedElement.type === template_preparser_1.PreparsedElementType.STYLE ||
- preparsedElement.type === template_preparser_1.PreparsedElementType.STYLESHEET) {
- // Skipping <script> for security reasons
- // Skipping <style> and stylesheets as we already processed them
- // in the StyleCompiler
- return null;
- }
- var attrNameAndValues = ast.attrs.map(function (attrAst) { return [attrAst.name, attrAst.value]; });
- var selector = createElementCssSelector(ast.name, attrNameAndValues);
- var ngContentIndex = component.findNgContentIndex(selector);
- var children = html_ast_1.htmlVisitAll(this, ast.children, EMPTY_COMPONENT);
- return new template_ast_1.ElementAst(ast.name, html_ast_1.htmlVisitAll(this, ast.attrs), [], [], [], [], children, ngContentIndex, ast.sourceSpan);
- };
- NonBindableVisitor.prototype.visitAttr = function (ast, context) {
- return new template_ast_1.AttrAst(ast.name, ast.value, ast.sourceSpan);
- };
- NonBindableVisitor.prototype.visitText = function (ast, component) {
- var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR);
- return new template_ast_1.TextAst(ast.value, ngContentIndex, ast.sourceSpan);
- };
- return NonBindableVisitor;
- })();
- var BoundElementOrDirectiveProperty = (function () {
- function BoundElementOrDirectiveProperty(name, expression, isLiteral, sourceSpan) {
- this.name = name;
- this.expression = expression;
- this.isLiteral = isLiteral;
- this.sourceSpan = sourceSpan;
- }
- return BoundElementOrDirectiveProperty;
- })();
- function splitClasses(classAttrValue) {
- return lang_1.StringWrapper.split(classAttrValue.trim(), /\s+/g);
- }
- exports.splitClasses = splitClasses;
- var Component = (function () {
- function Component(ngContentIndexMatcher, wildcardNgContentIndex) {
- this.ngContentIndexMatcher = ngContentIndexMatcher;
- this.wildcardNgContentIndex = wildcardNgContentIndex;
- }
- Component.create = function (directives) {
- if (directives.length === 0 || !directives[0].directive.isComponent) {
- return EMPTY_COMPONENT;
- }
- var matcher = new selector_1.SelectorMatcher();
- var ngContentSelectors = directives[0].directive.template.ngContentSelectors;
- var wildcardNgContentIndex = null;
- for (var i = 0; i < ngContentSelectors.length; i++) {
- var selector = ngContentSelectors[i];
- if (lang_1.StringWrapper.equals(selector, '*')) {
- wildcardNgContentIndex = i;
- }
- else {
- matcher.addSelectables(selector_1.CssSelector.parse(ngContentSelectors[i]), i);
- }
- }
- return new Component(matcher, wildcardNgContentIndex);
- };
- Component.prototype.findNgContentIndex = function (selector) {
- var ngContentIndices = [];
- this.ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) { ngContentIndices.push(ngContentIndex); });
- collection_1.ListWrapper.sort(ngContentIndices);
- if (lang_1.isPresent(this.wildcardNgContentIndex)) {
- ngContentIndices.push(this.wildcardNgContentIndex);
- }
- return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
- };
- return Component;
- })();
- function createElementCssSelector(elementName, matchableAttrs) {
- var cssSelector = new selector_1.CssSelector();
- var elNameNoNs = html_tags_1.splitNsName(elementName)[1];
- cssSelector.setElement(elNameNoNs);
- for (var i = 0; i < matchableAttrs.length; i++) {
- var attrName = matchableAttrs[i][0];
- var attrNameNoNs = html_tags_1.splitNsName(attrName)[1];
- var attrValue = matchableAttrs[i][1];
- cssSelector.addAttribute(attrNameNoNs, attrValue);
- if (attrName.toLowerCase() == CLASS_ATTR) {
- var classes = splitClasses(attrValue);
- classes.forEach(function (className) { return cssSelector.addClassName(className); });
- }
- }
- return cssSelector;
- }
- var EMPTY_COMPONENT = new Component(new selector_1.SelectorMatcher(), null);
- var NON_BINDABLE_VISITOR = new NonBindableVisitor();
- /***/ },
- /* 168 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var html_ast_1 = __webpack_require__(169);
- var di_1 = __webpack_require__(6);
- var html_lexer_1 = __webpack_require__(170);
- var parse_util_1 = __webpack_require__(171);
- var html_tags_1 = __webpack_require__(172);
- var HtmlTreeError = (function (_super) {
- __extends(HtmlTreeError, _super);
- function HtmlTreeError(elementName, location, msg) {
- _super.call(this, location, msg);
- this.elementName = elementName;
- }
- HtmlTreeError.create = function (elementName, location, msg) {
- return new HtmlTreeError(elementName, location, msg);
- };
- return HtmlTreeError;
- })(parse_util_1.ParseError);
- exports.HtmlTreeError = HtmlTreeError;
- var HtmlParseTreeResult = (function () {
- function HtmlParseTreeResult(rootNodes, errors) {
- this.rootNodes = rootNodes;
- this.errors = errors;
- }
- return HtmlParseTreeResult;
- })();
- exports.HtmlParseTreeResult = HtmlParseTreeResult;
- var HtmlParser = (function () {
- function HtmlParser() {
- }
- HtmlParser.prototype.parse = function (sourceContent, sourceUrl) {
- var tokensAndErrors = html_lexer_1.tokenizeHtml(sourceContent, sourceUrl);
- var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build();
- return new HtmlParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors
- .concat(treeAndErrors.errors));
- };
- HtmlParser = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], HtmlParser);
- return HtmlParser;
- })();
- exports.HtmlParser = HtmlParser;
- var TreeBuilder = (function () {
- function TreeBuilder(tokens) {
- this.tokens = tokens;
- this.index = -1;
- this.rootNodes = [];
- this.errors = [];
- this.elementStack = [];
- this._advance();
- }
- TreeBuilder.prototype.build = function () {
- while (this.peek.type !== html_lexer_1.HtmlTokenType.EOF) {
- if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_OPEN_START) {
- this._consumeStartTag(this._advance());
- }
- else if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_CLOSE) {
- this._consumeEndTag(this._advance());
- }
- else if (this.peek.type === html_lexer_1.HtmlTokenType.CDATA_START) {
- this._closeVoidElement();
- this._consumeCdata(this._advance());
- }
- else if (this.peek.type === html_lexer_1.HtmlTokenType.COMMENT_START) {
- this._closeVoidElement();
- this._consumeComment(this._advance());
- }
- else if (this.peek.type === html_lexer_1.HtmlTokenType.TEXT ||
- this.peek.type === html_lexer_1.HtmlTokenType.RAW_TEXT ||
- this.peek.type === html_lexer_1.HtmlTokenType.ESCAPABLE_RAW_TEXT) {
- this._closeVoidElement();
- this._consumeText(this._advance());
- }
- else {
- // Skip all other tokens...
- this._advance();
- }
- }
- return new HtmlParseTreeResult(this.rootNodes, this.errors);
- };
- TreeBuilder.prototype._advance = function () {
- var prev = this.peek;
- if (this.index < this.tokens.length - 1) {
- // Note: there is always an EOF token at the end
- this.index++;
- }
- this.peek = this.tokens[this.index];
- return prev;
- };
- TreeBuilder.prototype._advanceIf = function (type) {
- if (this.peek.type === type) {
- return this._advance();
- }
- return null;
- };
- TreeBuilder.prototype._consumeCdata = function (startToken) {
- this._consumeText(this._advance());
- this._advanceIf(html_lexer_1.HtmlTokenType.CDATA_END);
- };
- TreeBuilder.prototype._consumeComment = function (startToken) {
- this._advanceIf(html_lexer_1.HtmlTokenType.RAW_TEXT);
- this._advanceIf(html_lexer_1.HtmlTokenType.COMMENT_END);
- };
- TreeBuilder.prototype._consumeText = function (token) {
- var text = token.parts[0];
- if (text.length > 0 && text[0] == '\n') {
- var parent_1 = this._getParentElement();
- if (lang_1.isPresent(parent_1) && parent_1.children.length == 0 &&
- html_tags_1.getHtmlTagDefinition(parent_1.name).ignoreFirstLf) {
- text = text.substring(1);
- }
- }
- if (text.length > 0) {
- this._addToParent(new html_ast_1.HtmlTextAst(text, token.sourceSpan));
- }
- };
- TreeBuilder.prototype._closeVoidElement = function () {
- if (this.elementStack.length > 0) {
- var el = collection_1.ListWrapper.last(this.elementStack);
- if (html_tags_1.getHtmlTagDefinition(el.name).isVoid) {
- this.elementStack.pop();
- }
- }
- };
- TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
- var prefix = startTagToken.parts[0];
- var name = startTagToken.parts[1];
- var attrs = [];
- while (this.peek.type === html_lexer_1.HtmlTokenType.ATTR_NAME) {
- attrs.push(this._consumeAttr(this._advance()));
- }
- var fullName = getElementFullName(prefix, name, this._getParentElement());
- var selfClosing = false;
- // Note: There could have been a tokenizer error
- // so that we don't get a token for the end tag...
- if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_OPEN_END_VOID) {
- this._advance();
- selfClosing = true;
- if (html_tags_1.getNsPrefix(fullName) == null && !html_tags_1.getHtmlTagDefinition(fullName).isVoid) {
- this.errors.push(HtmlTreeError.create(fullName, startTagToken.sourceSpan.start, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
- }
- }
- else if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_OPEN_END) {
- this._advance();
- selfClosing = false;
- }
- var end = this.peek.sourceSpan.start;
- var el = new html_ast_1.HtmlElementAst(fullName, attrs, [], new parse_util_1.ParseSourceSpan(startTagToken.sourceSpan.start, end));
- this._pushElement(el);
- if (selfClosing) {
- this._popElement(fullName);
- }
- };
- TreeBuilder.prototype._pushElement = function (el) {
- if (this.elementStack.length > 0) {
- var parentEl = collection_1.ListWrapper.last(this.elementStack);
- if (html_tags_1.getHtmlTagDefinition(parentEl.name).isClosedByChild(el.name)) {
- this.elementStack.pop();
- }
- }
- var tagDef = html_tags_1.getHtmlTagDefinition(el.name);
- var parentEl = this._getParentElement();
- if (tagDef.requireExtraParent(lang_1.isPresent(parentEl) ? parentEl.name : null)) {
- var newParent = new html_ast_1.HtmlElementAst(tagDef.parentToAdd, [], [el], el.sourceSpan);
- this._addToParent(newParent);
- this.elementStack.push(newParent);
- this.elementStack.push(el);
- }
- else {
- this._addToParent(el);
- this.elementStack.push(el);
- }
- };
- TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
- var fullName = getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
- if (html_tags_1.getHtmlTagDefinition(fullName).isVoid) {
- this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan.start, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
- }
- else if (!this._popElement(fullName)) {
- this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan.start, "Unexpected closing tag \"" + endTagToken.parts[1] + "\""));
- }
- };
- TreeBuilder.prototype._popElement = function (fullName) {
- for (var stackIndex = this.elementStack.length - 1; stackIndex >= 0; stackIndex--) {
- var el = this.elementStack[stackIndex];
- if (el.name == fullName) {
- collection_1.ListWrapper.splice(this.elementStack, stackIndex, this.elementStack.length - stackIndex);
- return true;
- }
- if (!html_tags_1.getHtmlTagDefinition(el.name).closedByParent) {
- return false;
- }
- }
- return false;
- };
- TreeBuilder.prototype._consumeAttr = function (attrName) {
- var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
- var end = attrName.sourceSpan.end;
- var value = '';
- if (this.peek.type === html_lexer_1.HtmlTokenType.ATTR_VALUE) {
- var valueToken = this._advance();
- value = valueToken.parts[0];
- end = valueToken.sourceSpan.end;
- }
- return new html_ast_1.HtmlAttrAst(fullName, value, new parse_util_1.ParseSourceSpan(attrName.sourceSpan.start, end));
- };
- TreeBuilder.prototype._getParentElement = function () {
- return this.elementStack.length > 0 ? collection_1.ListWrapper.last(this.elementStack) : null;
- };
- TreeBuilder.prototype._addToParent = function (node) {
- var parent = this._getParentElement();
- if (lang_1.isPresent(parent)) {
- parent.children.push(node);
- }
- else {
- this.rootNodes.push(node);
- }
- };
- return TreeBuilder;
- })();
- function mergeNsAndName(prefix, localName) {
- return lang_1.isPresent(prefix) ? "@" + prefix + ":" + localName : localName;
- }
- function getElementFullName(prefix, localName, parentElement) {
- if (lang_1.isBlank(prefix)) {
- prefix = html_tags_1.getHtmlTagDefinition(localName).implicitNamespacePrefix;
- if (lang_1.isBlank(prefix) && lang_1.isPresent(parentElement)) {
- prefix = html_tags_1.getNsPrefix(parentElement.name);
- }
- }
- return mergeNsAndName(prefix, localName);
- }
- /***/ },
- /* 169 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var HtmlTextAst = (function () {
- function HtmlTextAst(value, sourceSpan) {
- this.value = value;
- this.sourceSpan = sourceSpan;
- }
- HtmlTextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
- return HtmlTextAst;
- })();
- exports.HtmlTextAst = HtmlTextAst;
- var HtmlAttrAst = (function () {
- function HtmlAttrAst(name, value, sourceSpan) {
- this.name = name;
- this.value = value;
- this.sourceSpan = sourceSpan;
- }
- HtmlAttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
- return HtmlAttrAst;
- })();
- exports.HtmlAttrAst = HtmlAttrAst;
- var HtmlElementAst = (function () {
- function HtmlElementAst(name, attrs, children, sourceSpan) {
- this.name = name;
- this.attrs = attrs;
- this.children = children;
- this.sourceSpan = sourceSpan;
- }
- HtmlElementAst.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); };
- return HtmlElementAst;
- })();
- exports.HtmlElementAst = HtmlElementAst;
- function htmlVisitAll(visitor, asts, context) {
- if (context === void 0) { context = null; }
- var result = [];
- asts.forEach(function (ast) {
- var astResult = ast.visit(visitor, context);
- if (lang_1.isPresent(astResult)) {
- result.push(astResult);
- }
- });
- return result;
- }
- exports.htmlVisitAll = htmlVisitAll;
- /***/ },
- /* 170 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var parse_util_1 = __webpack_require__(171);
- var html_tags_1 = __webpack_require__(172);
- (function (HtmlTokenType) {
- HtmlTokenType[HtmlTokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
- HtmlTokenType[HtmlTokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
- HtmlTokenType[HtmlTokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
- HtmlTokenType[HtmlTokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
- HtmlTokenType[HtmlTokenType["TEXT"] = 4] = "TEXT";
- HtmlTokenType[HtmlTokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT";
- HtmlTokenType[HtmlTokenType["RAW_TEXT"] = 6] = "RAW_TEXT";
- HtmlTokenType[HtmlTokenType["COMMENT_START"] = 7] = "COMMENT_START";
- HtmlTokenType[HtmlTokenType["COMMENT_END"] = 8] = "COMMENT_END";
- HtmlTokenType[HtmlTokenType["CDATA_START"] = 9] = "CDATA_START";
- HtmlTokenType[HtmlTokenType["CDATA_END"] = 10] = "CDATA_END";
- HtmlTokenType[HtmlTokenType["ATTR_NAME"] = 11] = "ATTR_NAME";
- HtmlTokenType[HtmlTokenType["ATTR_VALUE"] = 12] = "ATTR_VALUE";
- HtmlTokenType[HtmlTokenType["DOC_TYPE"] = 13] = "DOC_TYPE";
- HtmlTokenType[HtmlTokenType["EOF"] = 14] = "EOF";
- })(exports.HtmlTokenType || (exports.HtmlTokenType = {}));
- var HtmlTokenType = exports.HtmlTokenType;
- var HtmlToken = (function () {
- function HtmlToken(type, parts, sourceSpan) {
- this.type = type;
- this.parts = parts;
- this.sourceSpan = sourceSpan;
- }
- return HtmlToken;
- })();
- exports.HtmlToken = HtmlToken;
- var HtmlTokenError = (function (_super) {
- __extends(HtmlTokenError, _super);
- function HtmlTokenError(errorMsg, tokenType, location) {
- _super.call(this, location, errorMsg);
- this.tokenType = tokenType;
- }
- return HtmlTokenError;
- })(parse_util_1.ParseError);
- exports.HtmlTokenError = HtmlTokenError;
- var HtmlTokenizeResult = (function () {
- function HtmlTokenizeResult(tokens, errors) {
- this.tokens = tokens;
- this.errors = errors;
- }
- return HtmlTokenizeResult;
- })();
- exports.HtmlTokenizeResult = HtmlTokenizeResult;
- function tokenizeHtml(sourceContent, sourceUrl) {
- return new _HtmlTokenizer(new parse_util_1.ParseSourceFile(sourceContent, sourceUrl)).tokenize();
- }
- exports.tokenizeHtml = tokenizeHtml;
- var $EOF = 0;
- var $TAB = 9;
- var $LF = 10;
- var $FF = 12;
- var $CR = 13;
- var $SPACE = 32;
- var $BANG = 33;
- var $DQ = 34;
- var $HASH = 35;
- var $$ = 36;
- var $AMPERSAND = 38;
- var $SQ = 39;
- var $MINUS = 45;
- var $SLASH = 47;
- var $0 = 48;
- var $SEMICOLON = 59;
- var $9 = 57;
- var $COLON = 58;
- var $LT = 60;
- var $EQ = 61;
- var $GT = 62;
- var $QUESTION = 63;
- var $A = 65;
- var $Z = 90;
- var $LBRACKET = 91;
- var $RBRACKET = 93;
- var $a = 97;
- var $f = 102;
- var $z = 122;
- var $x = 120;
- var $NBSP = 160;
- var CR_OR_CRLF_REGEXP = /\r\n?/g;
- function unexpectedCharacterErrorMsg(charCode) {
- var char = charCode === $EOF ? 'EOF' : lang_1.StringWrapper.fromCharCode(charCode);
- return "Unexpected character \"" + char + "\"";
- }
- function unknownEntityErrorMsg(entitySrc) {
- return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
- }
- var ControlFlowError = (function () {
- function ControlFlowError(error) {
- this.error = error;
- }
- return ControlFlowError;
- })();
- // See http://www.w3.org/TR/html51/syntax.html#writing
- var _HtmlTokenizer = (function () {
- function _HtmlTokenizer(file) {
- this.file = file;
- // Note: this is always lowercase!
- this.peek = -1;
- this.index = -1;
- this.line = 0;
- this.column = -1;
- this.tokens = [];
- this.errors = [];
- this.input = file.content;
- this.inputLowercase = file.content.toLowerCase();
- this.length = file.content.length;
- this._advance();
- }
- _HtmlTokenizer.prototype._processCarriageReturns = function (content) {
- // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
- // In order to keep the original position in the source, we can not pre-process it.
- // Instead CRs are processed right before instantiating the tokens.
- return lang_1.StringWrapper.replaceAll(content, CR_OR_CRLF_REGEXP, '\n');
- };
- _HtmlTokenizer.prototype.tokenize = function () {
- while (this.peek !== $EOF) {
- var start = this._getLocation();
- try {
- if (this._attemptChar($LT)) {
- if (this._attemptChar($BANG)) {
- if (this._attemptChar($LBRACKET)) {
- this._consumeCdata(start);
- }
- else if (this._attemptChar($MINUS)) {
- this._consumeComment(start);
- }
- else {
- this._consumeDocType(start);
- }
- }
- else if (this._attemptChar($SLASH)) {
- this._consumeTagClose(start);
- }
- else {
- this._consumeTagOpen(start);
- }
- }
- else {
- this._consumeText();
- }
- }
- catch (e) {
- if (e instanceof ControlFlowError) {
- this.errors.push(e.error);
- }
- else {
- throw e;
- }
- }
- }
- this._beginToken(HtmlTokenType.EOF);
- this._endToken([]);
- return new HtmlTokenizeResult(mergeTextTokens(this.tokens), this.errors);
- };
- _HtmlTokenizer.prototype._getLocation = function () {
- return new parse_util_1.ParseLocation(this.file, this.index, this.line, this.column);
- };
- _HtmlTokenizer.prototype._beginToken = function (type, start) {
- if (start === void 0) { start = null; }
- if (lang_1.isBlank(start)) {
- start = this._getLocation();
- }
- this.currentTokenStart = start;
- this.currentTokenType = type;
- };
- _HtmlTokenizer.prototype._endToken = function (parts, end) {
- if (end === void 0) { end = null; }
- if (lang_1.isBlank(end)) {
- end = this._getLocation();
- }
- var token = new HtmlToken(this.currentTokenType, parts, new parse_util_1.ParseSourceSpan(this.currentTokenStart, end));
- this.tokens.push(token);
- this.currentTokenStart = null;
- this.currentTokenType = null;
- return token;
- };
- _HtmlTokenizer.prototype._createError = function (msg, position) {
- var error = new HtmlTokenError(msg, this.currentTokenType, position);
- this.currentTokenStart = null;
- this.currentTokenType = null;
- return new ControlFlowError(error);
- };
- _HtmlTokenizer.prototype._advance = function () {
- if (this.index >= this.length) {
- throw this._createError(unexpectedCharacterErrorMsg($EOF), this._getLocation());
- }
- if (this.peek === $LF) {
- this.line++;
- this.column = 0;
- }
- else if (this.peek !== $LF && this.peek !== $CR) {
- this.column++;
- }
- this.index++;
- this.peek = this.index >= this.length ? $EOF : lang_1.StringWrapper.charCodeAt(this.inputLowercase, this.index);
- };
- _HtmlTokenizer.prototype._attemptChar = function (charCode) {
- if (this.peek === charCode) {
- this._advance();
- return true;
- }
- return false;
- };
- _HtmlTokenizer.prototype._requireChar = function (charCode) {
- var location = this._getLocation();
- if (!this._attemptChar(charCode)) {
- throw this._createError(unexpectedCharacterErrorMsg(this.peek), location);
- }
- };
- _HtmlTokenizer.prototype._attemptChars = function (chars) {
- for (var i = 0; i < chars.length; i++) {
- if (!this._attemptChar(lang_1.StringWrapper.charCodeAt(chars, i))) {
- return false;
- }
- }
- return true;
- };
- _HtmlTokenizer.prototype._requireChars = function (chars) {
- var location = this._getLocation();
- if (!this._attemptChars(chars)) {
- throw this._createError(unexpectedCharacterErrorMsg(this.peek), location);
- }
- };
- _HtmlTokenizer.prototype._attemptUntilFn = function (predicate) {
- while (!predicate(this.peek)) {
- this._advance();
- }
- };
- _HtmlTokenizer.prototype._requireUntilFn = function (predicate, len) {
- var start = this._getLocation();
- this._attemptUntilFn(predicate);
- if (this.index - start.offset < len) {
- throw this._createError(unexpectedCharacterErrorMsg(this.peek), start);
- }
- };
- _HtmlTokenizer.prototype._attemptUntilChar = function (char) {
- while (this.peek !== char) {
- this._advance();
- }
- };
- _HtmlTokenizer.prototype._readChar = function (decodeEntities) {
- if (decodeEntities && this.peek === $AMPERSAND) {
- return this._decodeEntity();
- }
- else {
- var index = this.index;
- this._advance();
- return this.input[index];
- }
- };
- _HtmlTokenizer.prototype._decodeEntity = function () {
- var start = this._getLocation();
- this._advance();
- if (this._attemptChar($HASH)) {
- var isHex = this._attemptChar($x);
- var numberStart = this._getLocation().offset;
- this._attemptUntilFn(isDigitEntityEnd);
- if (this.peek != $SEMICOLON) {
- throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getLocation());
- }
- this._advance();
- var strNum = this.input.substring(numberStart, this.index - 1);
- try {
- var charCode = lang_1.NumberWrapper.parseInt(strNum, isHex ? 16 : 10);
- return lang_1.StringWrapper.fromCharCode(charCode);
- }
- catch (e) {
- var entity = this.input.substring(start.offset + 1, this.index - 1);
- throw this._createError(unknownEntityErrorMsg(entity), start);
- }
- }
- else {
- var startPosition = this._savePosition();
- this._attemptUntilFn(isNamedEntityEnd);
- if (this.peek != $SEMICOLON) {
- this._restorePosition(startPosition);
- return '&';
- }
- this._advance();
- var name_1 = this.input.substring(start.offset + 1, this.index - 1);
- var char = html_tags_1.NAMED_ENTITIES[name_1];
- if (lang_1.isBlank(char)) {
- throw this._createError(unknownEntityErrorMsg(name_1), start);
- }
- return char;
- }
- };
- _HtmlTokenizer.prototype._consumeRawText = function (decodeEntities, firstCharOfEnd, attemptEndRest) {
- var tagCloseStart;
- var textStart = this._getLocation();
- this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT, textStart);
- var parts = [];
- while (true) {
- tagCloseStart = this._getLocation();
- if (this._attemptChar(firstCharOfEnd) && attemptEndRest()) {
- break;
- }
- if (this.index > tagCloseStart.offset) {
- parts.push(this.input.substring(tagCloseStart.offset, this.index));
- }
- while (this.peek !== firstCharOfEnd) {
- parts.push(this._readChar(decodeEntities));
- }
- }
- return this._endToken([this._processCarriageReturns(parts.join(''))], tagCloseStart);
- };
- _HtmlTokenizer.prototype._consumeComment = function (start) {
- var _this = this;
- this._beginToken(HtmlTokenType.COMMENT_START, start);
- this._requireChar($MINUS);
- this._endToken([]);
- var textToken = this._consumeRawText(false, $MINUS, function () { return _this._attemptChars('->'); });
- this._beginToken(HtmlTokenType.COMMENT_END, textToken.sourceSpan.end);
- this._endToken([]);
- };
- _HtmlTokenizer.prototype._consumeCdata = function (start) {
- var _this = this;
- this._beginToken(HtmlTokenType.CDATA_START, start);
- this._requireChars('cdata[');
- this._endToken([]);
- var textToken = this._consumeRawText(false, $RBRACKET, function () { return _this._attemptChars(']>'); });
- this._beginToken(HtmlTokenType.CDATA_END, textToken.sourceSpan.end);
- this._endToken([]);
- };
- _HtmlTokenizer.prototype._consumeDocType = function (start) {
- this._beginToken(HtmlTokenType.DOC_TYPE, start);
- this._attemptUntilChar($GT);
- this._advance();
- this._endToken([this.input.substring(start.offset + 2, this.index - 1)]);
- };
- _HtmlTokenizer.prototype._consumePrefixAndName = function () {
- var nameOrPrefixStart = this.index;
- var prefix = null;
- while (this.peek !== $COLON && !isPrefixEnd(this.peek)) {
- this._advance();
- }
- var nameStart;
- if (this.peek === $COLON) {
- this._advance();
- prefix = this.input.substring(nameOrPrefixStart, this.index - 1);
- nameStart = this.index;
- }
- else {
- nameStart = nameOrPrefixStart;
- }
- this._requireUntilFn(isNameEnd, this.index === nameStart ? 1 : 0);
- var name = this.input.substring(nameStart, this.index);
- return [prefix, name];
- };
- _HtmlTokenizer.prototype._consumeTagOpen = function (start) {
- var savedPos = this._savePosition();
- var lowercaseTagName;
- try {
- if (!isAsciiLetter(this.peek)) {
- throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getLocation());
- }
- var nameStart = this.index;
- this._consumeTagOpenStart(start);
- lowercaseTagName = this.inputLowercase.substring(nameStart, this.index);
- this._attemptUntilFn(isNotWhitespace);
- while (this.peek !== $SLASH && this.peek !== $GT) {
- this._consumeAttributeName();
- this._attemptUntilFn(isNotWhitespace);
- if (this._attemptChar($EQ)) {
- this._attemptUntilFn(isNotWhitespace);
- this._consumeAttributeValue();
- }
- this._attemptUntilFn(isNotWhitespace);
- }
- this._consumeTagOpenEnd();
- }
- catch (e) {
- if (e instanceof ControlFlowError) {
- // When the start tag is invalid, assume we want a "<"
- this._restorePosition(savedPos);
- // Back to back text tokens are merged at the end
- this._beginToken(HtmlTokenType.TEXT, start);
- this._endToken(['<']);
- return;
- }
- throw e;
- }
- var contentTokenType = html_tags_1.getHtmlTagDefinition(lowercaseTagName).contentType;
- if (contentTokenType === html_tags_1.HtmlTagContentType.RAW_TEXT) {
- this._consumeRawTextWithTagClose(lowercaseTagName, false);
- }
- else if (contentTokenType === html_tags_1.HtmlTagContentType.ESCAPABLE_RAW_TEXT) {
- this._consumeRawTextWithTagClose(lowercaseTagName, true);
- }
- };
- _HtmlTokenizer.prototype._consumeRawTextWithTagClose = function (lowercaseTagName, decodeEntities) {
- var _this = this;
- var textToken = this._consumeRawText(decodeEntities, $LT, function () {
- if (!_this._attemptChar($SLASH))
- return false;
- _this._attemptUntilFn(isNotWhitespace);
- if (!_this._attemptChars(lowercaseTagName))
- return false;
- _this._attemptUntilFn(isNotWhitespace);
- if (!_this._attemptChar($GT))
- return false;
- return true;
- });
- this._beginToken(HtmlTokenType.TAG_CLOSE, textToken.sourceSpan.end);
- this._endToken([null, lowercaseTagName]);
- };
- _HtmlTokenizer.prototype._consumeTagOpenStart = function (start) {
- this._beginToken(HtmlTokenType.TAG_OPEN_START, start);
- var parts = this._consumePrefixAndName();
- this._endToken(parts);
- };
- _HtmlTokenizer.prototype._consumeAttributeName = function () {
- this._beginToken(HtmlTokenType.ATTR_NAME);
- var prefixAndName = this._consumePrefixAndName();
- this._endToken(prefixAndName);
- };
- _HtmlTokenizer.prototype._consumeAttributeValue = function () {
- this._beginToken(HtmlTokenType.ATTR_VALUE);
- var value;
- if (this.peek === $SQ || this.peek === $DQ) {
- var quoteChar = this.peek;
- this._advance();
- var parts = [];
- while (this.peek !== quoteChar) {
- parts.push(this._readChar(true));
- }
- value = parts.join('');
- this._advance();
- }
- else {
- var valueStart = this.index;
- this._requireUntilFn(isNameEnd, 1);
- value = this.input.substring(valueStart, this.index);
- }
- this._endToken([this._processCarriageReturns(value)]);
- };
- _HtmlTokenizer.prototype._consumeTagOpenEnd = function () {
- var tokenType = this._attemptChar($SLASH) ? HtmlTokenType.TAG_OPEN_END_VOID : HtmlTokenType.TAG_OPEN_END;
- this._beginToken(tokenType);
- this._requireChar($GT);
- this._endToken([]);
- };
- _HtmlTokenizer.prototype._consumeTagClose = function (start) {
- this._beginToken(HtmlTokenType.TAG_CLOSE, start);
- this._attemptUntilFn(isNotWhitespace);
- var prefixAndName;
- prefixAndName = this._consumePrefixAndName();
- this._attemptUntilFn(isNotWhitespace);
- this._requireChar($GT);
- this._endToken(prefixAndName);
- };
- _HtmlTokenizer.prototype._consumeText = function () {
- var start = this._getLocation();
- this._beginToken(HtmlTokenType.TEXT, start);
- var parts = [this._readChar(true)];
- while (!isTextEnd(this.peek)) {
- parts.push(this._readChar(true));
- }
- this._endToken([this._processCarriageReturns(parts.join(''))]);
- };
- _HtmlTokenizer.prototype._savePosition = function () {
- return [this.peek, this.index, this.column, this.line, this.tokens.length];
- };
- _HtmlTokenizer.prototype._restorePosition = function (position) {
- this.peek = position[0];
- this.index = position[1];
- this.column = position[2];
- this.line = position[3];
- var nbTokens = position[4];
- if (nbTokens < this.tokens.length) {
- // remove any extra tokens
- this.tokens = collection_1.ListWrapper.slice(this.tokens, 0, nbTokens);
- }
- };
- return _HtmlTokenizer;
- })();
- function isNotWhitespace(code) {
- return !isWhitespace(code) || code === $EOF;
- }
- function isWhitespace(code) {
- return (code >= $TAB && code <= $SPACE) || (code === $NBSP);
- }
- function isNameEnd(code) {
- return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ ||
- code === $EQ;
- }
- function isPrefixEnd(code) {
- return (code < $a || $z < code) && (code < $A || $Z < code) && (code < $0 || code > $9);
- }
- function isDigitEntityEnd(code) {
- return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
- }
- function isNamedEntityEnd(code) {
- return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
- }
- function isTextEnd(code) {
- return code === $LT || code === $EOF;
- }
- function isAsciiLetter(code) {
- return code >= $a && code <= $z;
- }
- function isAsciiHexDigit(code) {
- return code >= $a && code <= $f || code >= $0 && code <= $9;
- }
- function mergeTextTokens(srcTokens) {
- var dstTokens = [];
- var lastDstToken;
- for (var i = 0; i < srcTokens.length; i++) {
- var token = srcTokens[i];
- if (lang_1.isPresent(lastDstToken) && lastDstToken.type == HtmlTokenType.TEXT &&
- token.type == HtmlTokenType.TEXT) {
- lastDstToken.parts[0] += token.parts[0];
- lastDstToken.sourceSpan.end = token.sourceSpan.end;
- }
- else {
- lastDstToken = token;
- dstTokens.push(lastDstToken);
- }
- }
- return dstTokens;
- }
- /***/ },
- /* 171 */
- /***/ function(module, exports) {
- var ParseLocation = (function () {
- function ParseLocation(file, offset, line, col) {
- this.file = file;
- this.offset = offset;
- this.line = line;
- this.col = col;
- }
- ParseLocation.prototype.toString = function () { return this.file.url + "@" + this.line + ":" + this.col; };
- return ParseLocation;
- })();
- exports.ParseLocation = ParseLocation;
- var ParseSourceFile = (function () {
- function ParseSourceFile(content, url) {
- this.content = content;
- this.url = url;
- }
- return ParseSourceFile;
- })();
- exports.ParseSourceFile = ParseSourceFile;
- var ParseError = (function () {
- function ParseError(location, msg) {
- this.location = location;
- this.msg = msg;
- }
- ParseError.prototype.toString = function () {
- var source = this.location.file.content;
- var ctxStart = this.location.offset;
- if (ctxStart > source.length - 1) {
- ctxStart = source.length - 1;
- }
- var ctxEnd = ctxStart;
- var ctxLen = 0;
- var ctxLines = 0;
- while (ctxLen < 100 && ctxStart > 0) {
- ctxStart--;
- ctxLen++;
- if (source[ctxStart] == "\n") {
- if (++ctxLines == 3) {
- break;
- }
- }
- }
- ctxLen = 0;
- ctxLines = 0;
- while (ctxLen < 100 && ctxEnd < source.length - 1) {
- ctxEnd++;
- ctxLen++;
- if (source[ctxEnd] == "\n") {
- if (++ctxLines == 3) {
- break;
- }
- }
- }
- var context = source.substring(ctxStart, this.location.offset) + '[ERROR ->]' +
- source.substring(this.location.offset, ctxEnd + 1);
- return this.msg + " (\"" + context + "\"): " + this.location;
- };
- return ParseError;
- })();
- exports.ParseError = ParseError;
- var ParseSourceSpan = (function () {
- function ParseSourceSpan(start, end) {
- this.start = start;
- this.end = end;
- }
- ParseSourceSpan.prototype.toString = function () {
- return this.start.file.content.substring(this.start.offset, this.end.offset);
- };
- return ParseSourceSpan;
- })();
- exports.ParseSourceSpan = ParseSourceSpan;
- /***/ },
- /* 172 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- // see http://www.w3.org/TR/html51/syntax.html#named-character-references
- // see https://html.spec.whatwg.org/multipage/entities.json
- // This list is not exhaustive to keep the compiler footprint low.
- // The `{` / `ƫ` syntax should be used when the named character reference does not exist.
- exports.NAMED_ENTITIES = lang_1.CONST_EXPR({
- 'Aacute': '\u00C1',
- 'aacute': '\u00E1',
- 'Acirc': '\u00C2',
- 'acirc': '\u00E2',
- 'acute': '\u00B4',
- 'AElig': '\u00C6',
- 'aelig': '\u00E6',
- 'Agrave': '\u00C0',
- 'agrave': '\u00E0',
- 'alefsym': '\u2135',
- 'Alpha': '\u0391',
- 'alpha': '\u03B1',
- 'amp': '&',
- 'and': '\u2227',
- 'ang': '\u2220',
- 'apos': '\u0027',
- 'Aring': '\u00C5',
- 'aring': '\u00E5',
- 'asymp': '\u2248',
- 'Atilde': '\u00C3',
- 'atilde': '\u00E3',
- 'Auml': '\u00C4',
- 'auml': '\u00E4',
- 'bdquo': '\u201E',
- 'Beta': '\u0392',
- 'beta': '\u03B2',
- 'brvbar': '\u00A6',
- 'bull': '\u2022',
- 'cap': '\u2229',
- 'Ccedil': '\u00C7',
- 'ccedil': '\u00E7',
- 'cedil': '\u00B8',
- 'cent': '\u00A2',
- 'Chi': '\u03A7',
- 'chi': '\u03C7',
- 'circ': '\u02C6',
- 'clubs': '\u2663',
- 'cong': '\u2245',
- 'copy': '\u00A9',
- 'crarr': '\u21B5',
- 'cup': '\u222A',
- 'curren': '\u00A4',
- 'dagger': '\u2020',
- 'Dagger': '\u2021',
- 'darr': '\u2193',
- 'dArr': '\u21D3',
- 'deg': '\u00B0',
- 'Delta': '\u0394',
- 'delta': '\u03B4',
- 'diams': '\u2666',
- 'divide': '\u00F7',
- 'Eacute': '\u00C9',
- 'eacute': '\u00E9',
- 'Ecirc': '\u00CA',
- 'ecirc': '\u00EA',
- 'Egrave': '\u00C8',
- 'egrave': '\u00E8',
- 'empty': '\u2205',
- 'emsp': '\u2003',
- 'ensp': '\u2002',
- 'Epsilon': '\u0395',
- 'epsilon': '\u03B5',
- 'equiv': '\u2261',
- 'Eta': '\u0397',
- 'eta': '\u03B7',
- 'ETH': '\u00D0',
- 'eth': '\u00F0',
- 'Euml': '\u00CB',
- 'euml': '\u00EB',
- 'euro': '\u20AC',
- 'exist': '\u2203',
- 'fnof': '\u0192',
- 'forall': '\u2200',
- 'frac12': '\u00BD',
- 'frac14': '\u00BC',
- 'frac34': '\u00BE',
- 'frasl': '\u2044',
- 'Gamma': '\u0393',
- 'gamma': '\u03B3',
- 'ge': '\u2265',
- 'gt': '>',
- 'harr': '\u2194',
- 'hArr': '\u21D4',
- 'hearts': '\u2665',
- 'hellip': '\u2026',
- 'Iacute': '\u00CD',
- 'iacute': '\u00ED',
- 'Icirc': '\u00CE',
- 'icirc': '\u00EE',
- 'iexcl': '\u00A1',
- 'Igrave': '\u00CC',
- 'igrave': '\u00EC',
- 'image': '\u2111',
- 'infin': '\u221E',
- 'int': '\u222B',
- 'Iota': '\u0399',
- 'iota': '\u03B9',
- 'iquest': '\u00BF',
- 'isin': '\u2208',
- 'Iuml': '\u00CF',
- 'iuml': '\u00EF',
- 'Kappa': '\u039A',
- 'kappa': '\u03BA',
- 'Lambda': '\u039B',
- 'lambda': '\u03BB',
- 'lang': '\u27E8',
- 'laquo': '\u00AB',
- 'larr': '\u2190',
- 'lArr': '\u21D0',
- 'lceil': '\u2308',
- 'ldquo': '\u201C',
- 'le': '\u2264',
- 'lfloor': '\u230A',
- 'lowast': '\u2217',
- 'loz': '\u25CA',
- 'lrm': '\u200E',
- 'lsaquo': '\u2039',
- 'lsquo': '\u2018',
- 'lt': '<',
- 'macr': '\u00AF',
- 'mdash': '\u2014',
- 'micro': '\u00B5',
- 'middot': '\u00B7',
- 'minus': '\u2212',
- 'Mu': '\u039C',
- 'mu': '\u03BC',
- 'nabla': '\u2207',
- 'nbsp': '\u00A0',
- 'ndash': '\u2013',
- 'ne': '\u2260',
- 'ni': '\u220B',
- 'not': '\u00AC',
- 'notin': '\u2209',
- 'nsub': '\u2284',
- 'Ntilde': '\u00D1',
- 'ntilde': '\u00F1',
- 'Nu': '\u039D',
- 'nu': '\u03BD',
- 'Oacute': '\u00D3',
- 'oacute': '\u00F3',
- 'Ocirc': '\u00D4',
- 'ocirc': '\u00F4',
- 'OElig': '\u0152',
- 'oelig': '\u0153',
- 'Ograve': '\u00D2',
- 'ograve': '\u00F2',
- 'oline': '\u203E',
- 'Omega': '\u03A9',
- 'omega': '\u03C9',
- 'Omicron': '\u039F',
- 'omicron': '\u03BF',
- 'oplus': '\u2295',
- 'or': '\u2228',
- 'ordf': '\u00AA',
- 'ordm': '\u00BA',
- 'Oslash': '\u00D8',
- 'oslash': '\u00F8',
- 'Otilde': '\u00D5',
- 'otilde': '\u00F5',
- 'otimes': '\u2297',
- 'Ouml': '\u00D6',
- 'ouml': '\u00F6',
- 'para': '\u00B6',
- 'permil': '\u2030',
- 'perp': '\u22A5',
- 'Phi': '\u03A6',
- 'phi': '\u03C6',
- 'Pi': '\u03A0',
- 'pi': '\u03C0',
- 'piv': '\u03D6',
- 'plusmn': '\u00B1',
- 'pound': '\u00A3',
- 'prime': '\u2032',
- 'Prime': '\u2033',
- 'prod': '\u220F',
- 'prop': '\u221D',
- 'Psi': '\u03A8',
- 'psi': '\u03C8',
- 'quot': '\u0022',
- 'radic': '\u221A',
- 'rang': '\u27E9',
- 'raquo': '\u00BB',
- 'rarr': '\u2192',
- 'rArr': '\u21D2',
- 'rceil': '\u2309',
- 'rdquo': '\u201D',
- 'real': '\u211C',
- 'reg': '\u00AE',
- 'rfloor': '\u230B',
- 'Rho': '\u03A1',
- 'rho': '\u03C1',
- 'rlm': '\u200F',
- 'rsaquo': '\u203A',
- 'rsquo': '\u2019',
- 'sbquo': '\u201A',
- 'Scaron': '\u0160',
- 'scaron': '\u0161',
- 'sdot': '\u22C5',
- 'sect': '\u00A7',
- 'shy': '\u00AD',
- 'Sigma': '\u03A3',
- 'sigma': '\u03C3',
- 'sigmaf': '\u03C2',
- 'sim': '\u223C',
- 'spades': '\u2660',
- 'sub': '\u2282',
- 'sube': '\u2286',
- 'sum': '\u2211',
- 'sup': '\u2283',
- 'sup1': '\u00B9',
- 'sup2': '\u00B2',
- 'sup3': '\u00B3',
- 'supe': '\u2287',
- 'szlig': '\u00DF',
- 'Tau': '\u03A4',
- 'tau': '\u03C4',
- 'there4': '\u2234',
- 'Theta': '\u0398',
- 'theta': '\u03B8',
- 'thetasym': '\u03D1',
- 'thinsp': '\u2009',
- 'THORN': '\u00DE',
- 'thorn': '\u00FE',
- 'tilde': '\u02DC',
- 'times': '\u00D7',
- 'trade': '\u2122',
- 'Uacute': '\u00DA',
- 'uacute': '\u00FA',
- 'uarr': '\u2191',
- 'uArr': '\u21D1',
- 'Ucirc': '\u00DB',
- 'ucirc': '\u00FB',
- 'Ugrave': '\u00D9',
- 'ugrave': '\u00F9',
- 'uml': '\u00A8',
- 'upsih': '\u03D2',
- 'Upsilon': '\u03A5',
- 'upsilon': '\u03C5',
- 'Uuml': '\u00DC',
- 'uuml': '\u00FC',
- 'weierp': '\u2118',
- 'Xi': '\u039E',
- 'xi': '\u03BE',
- 'Yacute': '\u00DD',
- 'yacute': '\u00FD',
- 'yen': '\u00A5',
- 'yuml': '\u00FF',
- 'Yuml': '\u0178',
- 'Zeta': '\u0396',
- 'zeta': '\u03B6',
- 'zwj': '\u200D',
- 'zwnj': '\u200C',
- });
- (function (HtmlTagContentType) {
- HtmlTagContentType[HtmlTagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
- HtmlTagContentType[HtmlTagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
- HtmlTagContentType[HtmlTagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
- })(exports.HtmlTagContentType || (exports.HtmlTagContentType = {}));
- var HtmlTagContentType = exports.HtmlTagContentType;
- var HtmlTagDefinition = (function () {
- function HtmlTagDefinition(_a) {
- var _this = this;
- var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, requiredParents = _b.requiredParents, implicitNamespacePrefix = _b.implicitNamespacePrefix, contentType = _b.contentType, closedByParent = _b.closedByParent, isVoid = _b.isVoid, ignoreFirstLf = _b.ignoreFirstLf;
- this.closedByChildren = {};
- this.closedByParent = false;
- if (lang_1.isPresent(closedByChildren) && closedByChildren.length > 0) {
- closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
- }
- this.isVoid = lang_1.normalizeBool(isVoid);
- this.closedByParent = lang_1.normalizeBool(closedByParent) || this.isVoid;
- if (lang_1.isPresent(requiredParents) && requiredParents.length > 0) {
- this.requiredParents = {};
- this.parentToAdd = requiredParents[0];
- requiredParents.forEach(function (tagName) { return _this.requiredParents[tagName] = true; });
- }
- this.implicitNamespacePrefix = implicitNamespacePrefix;
- this.contentType = lang_1.isPresent(contentType) ? contentType : HtmlTagContentType.PARSABLE_DATA;
- this.ignoreFirstLf = lang_1.normalizeBool(ignoreFirstLf);
- }
- HtmlTagDefinition.prototype.requireExtraParent = function (currentParent) {
- if (lang_1.isBlank(this.requiredParents)) {
- return false;
- }
- if (lang_1.isBlank(currentParent)) {
- return true;
- }
- var lcParent = currentParent.toLowerCase();
- return this.requiredParents[lcParent] != true && lcParent != 'template';
- };
- HtmlTagDefinition.prototype.isClosedByChild = function (name) {
- return this.isVoid || lang_1.normalizeBool(this.closedByChildren[name.toLowerCase()]);
- };
- return HtmlTagDefinition;
- })();
- exports.HtmlTagDefinition = HtmlTagDefinition;
- // see http://www.w3.org/TR/html51/syntax.html#optional-tags
- // This implementation does not fully conform to the HTML5 spec.
- var TAG_DEFINITIONS = {
- 'area': new HtmlTagDefinition({ isVoid: true }),
- 'embed': new HtmlTagDefinition({ isVoid: true }),
- 'link': new HtmlTagDefinition({ isVoid: true }),
- 'img': new HtmlTagDefinition({ isVoid: true }),
- 'input': new HtmlTagDefinition({ isVoid: true }),
- 'param': new HtmlTagDefinition({ isVoid: true }),
- 'hr': new HtmlTagDefinition({ isVoid: true }),
- 'br': new HtmlTagDefinition({ isVoid: true }),
- 'source': new HtmlTagDefinition({ isVoid: true }),
- 'track': new HtmlTagDefinition({ isVoid: true }),
- 'wbr': new HtmlTagDefinition({ isVoid: true }),
- 'p': new HtmlTagDefinition({
- closedByChildren: [
- 'address',
- 'article',
- 'aside',
- 'blockquote',
- 'div',
- 'dl',
- 'fieldset',
- 'footer',
- 'form',
- 'h1',
- 'h2',
- 'h3',
- 'h4',
- 'h5',
- 'h6',
- 'header',
- 'hgroup',
- 'hr',
- 'main',
- 'nav',
- 'ol',
- 'p',
- 'pre',
- 'section',
- 'table',
- 'ul'
- ],
- closedByParent: true
- }),
- 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
- 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
- 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
- 'tr': new HtmlTagDefinition({
- closedByChildren: ['tr'],
- requiredParents: ['tbody', 'tfoot', 'thead'],
- closedByParent: true
- }),
- 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
- 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
- 'col': new HtmlTagDefinition({ requiredParents: ['colgroup'], isVoid: true }),
- 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
- 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
- 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
- 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
- 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
- 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
- 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
- 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
- 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
- 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
- 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
- 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
- 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
- 'style': new HtmlTagDefinition({ contentType: HtmlTagContentType.RAW_TEXT }),
- 'script': new HtmlTagDefinition({ contentType: HtmlTagContentType.RAW_TEXT }),
- 'title': new HtmlTagDefinition({ contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT }),
- 'textarea': new HtmlTagDefinition({ contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
- };
- var DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
- function getHtmlTagDefinition(tagName) {
- var result = TAG_DEFINITIONS[tagName.toLowerCase()];
- return lang_1.isPresent(result) ? result : DEFAULT_TAG_DEFINITION;
- }
- exports.getHtmlTagDefinition = getHtmlTagDefinition;
- var NS_PREFIX_RE = /^@([^:]+):(.+)/g;
- function splitNsName(elementName) {
- if (elementName[0] != '@') {
- return [null, elementName];
- }
- var match = lang_1.RegExpWrapper.firstMatch(NS_PREFIX_RE, elementName);
- return [match[1], match[2]];
- }
- exports.splitNsName = splitNsName;
- function getNsPrefix(elementName) {
- return splitNsName(elementName)[0];
- }
- exports.getNsPrefix = getNsPrefix;
- /***/ },
- /* 173 */
- /***/ function(module, exports) {
- var ElementSchemaRegistry = (function () {
- function ElementSchemaRegistry() {
- }
- ElementSchemaRegistry.prototype.hasProperty = function (tagName, propName) { return true; };
- ElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return propName; };
- return ElementSchemaRegistry;
- })();
- exports.ElementSchemaRegistry = ElementSchemaRegistry;
- /***/ },
- /* 174 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var html_tags_1 = __webpack_require__(172);
- var NG_CONTENT_SELECT_ATTR = 'select';
- var NG_CONTENT_ELEMENT = 'ng-content';
- var LINK_ELEMENT = 'link';
- var LINK_STYLE_REL_ATTR = 'rel';
- var LINK_STYLE_HREF_ATTR = 'href';
- var LINK_STYLE_REL_VALUE = 'stylesheet';
- var STYLE_ELEMENT = 'style';
- var SCRIPT_ELEMENT = 'script';
- var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
- function preparseElement(ast) {
- var selectAttr = null;
- var hrefAttr = null;
- var relAttr = null;
- var nonBindable = false;
- ast.attrs.forEach(function (attr) {
- var lcAttrName = attr.name.toLowerCase();
- if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
- selectAttr = attr.value;
- }
- else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
- hrefAttr = attr.value;
- }
- else if (lcAttrName == LINK_STYLE_REL_ATTR) {
- relAttr = attr.value;
- }
- else if (attr.name == NG_NON_BINDABLE_ATTR) {
- nonBindable = true;
- }
- });
- selectAttr = normalizeNgContentSelect(selectAttr);
- var nodeName = ast.name.toLowerCase();
- var type = PreparsedElementType.OTHER;
- if (html_tags_1.splitNsName(nodeName)[1] == NG_CONTENT_ELEMENT) {
- type = PreparsedElementType.NG_CONTENT;
- }
- else if (nodeName == STYLE_ELEMENT) {
- type = PreparsedElementType.STYLE;
- }
- else if (nodeName == SCRIPT_ELEMENT) {
- type = PreparsedElementType.SCRIPT;
- }
- else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
- type = PreparsedElementType.STYLESHEET;
- }
- return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable);
- }
- exports.preparseElement = preparseElement;
- (function (PreparsedElementType) {
- PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
- PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
- PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
- PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
- PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
- })(exports.PreparsedElementType || (exports.PreparsedElementType = {}));
- var PreparsedElementType = exports.PreparsedElementType;
- var PreparsedElement = (function () {
- function PreparsedElement(type, selectAttr, hrefAttr, nonBindable) {
- this.type = type;
- this.selectAttr = selectAttr;
- this.hrefAttr = hrefAttr;
- this.nonBindable = nonBindable;
- }
- return PreparsedElement;
- })();
- exports.PreparsedElement = PreparsedElement;
- function normalizeNgContentSelect(selectAttr) {
- if (lang_1.isBlank(selectAttr) || selectAttr.length === 0) {
- return '*';
- }
- return selectAttr;
- }
- /***/ },
- /* 175 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var directive_metadata_1 = __webpack_require__(153);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var async_1 = __webpack_require__(60);
- var xhr_1 = __webpack_require__(149);
- var url_resolver_1 = __webpack_require__(148);
- var style_url_resolver_1 = __webpack_require__(163);
- var di_1 = __webpack_require__(6);
- var view_1 = __webpack_require__(56);
- var html_ast_1 = __webpack_require__(169);
- var html_parser_1 = __webpack_require__(168);
- var template_preparser_1 = __webpack_require__(174);
- var TemplateNormalizer = (function () {
- function TemplateNormalizer(_xhr, _urlResolver, _htmlParser) {
- this._xhr = _xhr;
- this._urlResolver = _urlResolver;
- this._htmlParser = _htmlParser;
- }
- TemplateNormalizer.prototype.normalizeTemplate = function (directiveType, template) {
- var _this = this;
- if (lang_1.isPresent(template.template)) {
- return async_1.PromiseWrapper.resolve(this.normalizeLoadedTemplate(directiveType, template, template.template, directiveType.moduleUrl));
- }
- else if (lang_1.isPresent(template.templateUrl)) {
- var sourceAbsUrl = this._urlResolver.resolve(directiveType.moduleUrl, template.templateUrl);
- return this._xhr.get(sourceAbsUrl)
- .then(function (templateContent) { return _this.normalizeLoadedTemplate(directiveType, template, templateContent, sourceAbsUrl); });
- }
- else {
- throw new exceptions_1.BaseException("No template specified for component " + directiveType.name);
- }
- };
- TemplateNormalizer.prototype.normalizeLoadedTemplate = function (directiveType, templateMeta, template, templateAbsUrl) {
- var _this = this;
- var rootNodesAndErrors = this._htmlParser.parse(template, directiveType.name);
- if (rootNodesAndErrors.errors.length > 0) {
- var errorString = rootNodesAndErrors.errors.join('\n');
- throw new exceptions_1.BaseException("Template parse errors:\n" + errorString);
- }
- var visitor = new TemplatePreparseVisitor();
- html_ast_1.htmlVisitAll(visitor, rootNodesAndErrors.rootNodes);
- var allStyles = templateMeta.styles.concat(visitor.styles);
- var allStyleAbsUrls = visitor.styleUrls.filter(style_url_resolver_1.isStyleUrlResolvable)
- .map(function (url) { return _this._urlResolver.resolve(templateAbsUrl, url); })
- .concat(templateMeta.styleUrls.filter(style_url_resolver_1.isStyleUrlResolvable)
- .map(function (url) { return _this._urlResolver.resolve(directiveType.moduleUrl, url); }));
- var allResolvedStyles = allStyles.map(function (style) {
- var styleWithImports = style_url_resolver_1.extractStyleUrls(_this._urlResolver, templateAbsUrl, style);
- styleWithImports.styleUrls.forEach(function (styleUrl) { return allStyleAbsUrls.push(styleUrl); });
- return styleWithImports.style;
- });
- var encapsulation = templateMeta.encapsulation;
- if (encapsulation === view_1.ViewEncapsulation.Emulated && allResolvedStyles.length === 0 &&
- allStyleAbsUrls.length === 0) {
- encapsulation = view_1.ViewEncapsulation.None;
- }
- return new directive_metadata_1.CompileTemplateMetadata({
- encapsulation: encapsulation,
- template: template,
- templateUrl: templateAbsUrl,
- styles: allResolvedStyles,
- styleUrls: allStyleAbsUrls,
- ngContentSelectors: visitor.ngContentSelectors
- });
- };
- TemplateNormalizer = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [xhr_1.XHR, url_resolver_1.UrlResolver, html_parser_1.HtmlParser])
- ], TemplateNormalizer);
- return TemplateNormalizer;
- })();
- exports.TemplateNormalizer = TemplateNormalizer;
- var TemplatePreparseVisitor = (function () {
- function TemplatePreparseVisitor() {
- this.ngContentSelectors = [];
- this.styles = [];
- this.styleUrls = [];
- this.ngNonBindableStackCount = 0;
- }
- TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
- var preparsedElement = template_preparser_1.preparseElement(ast);
- switch (preparsedElement.type) {
- case template_preparser_1.PreparsedElementType.NG_CONTENT:
- if (this.ngNonBindableStackCount === 0) {
- this.ngContentSelectors.push(preparsedElement.selectAttr);
- }
- break;
- case template_preparser_1.PreparsedElementType.STYLE:
- var textContent = '';
- ast.children.forEach(function (child) {
- if (child instanceof html_ast_1.HtmlTextAst) {
- textContent += child.value;
- }
- });
- this.styles.push(textContent);
- break;
- case template_preparser_1.PreparsedElementType.STYLESHEET:
- this.styleUrls.push(preparsedElement.hrefAttr);
- break;
- }
- if (preparsedElement.nonBindable) {
- this.ngNonBindableStackCount++;
- }
- html_ast_1.htmlVisitAll(this, ast.children);
- if (preparsedElement.nonBindable) {
- this.ngNonBindableStackCount--;
- }
- return null;
- };
- TemplatePreparseVisitor.prototype.visitAttr = function (ast, context) { return null; };
- TemplatePreparseVisitor.prototype.visitText = function (ast, context) { return null; };
- return TemplatePreparseVisitor;
- })();
- /***/ },
- /* 176 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var cpl = __webpack_require__(153);
- var md = __webpack_require__(23);
- var directive_resolver_1 = __webpack_require__(92);
- var view_resolver_1 = __webpack_require__(93);
- var directive_lifecycle_reflector_1 = __webpack_require__(88);
- var interfaces_1 = __webpack_require__(89);
- var reflection_1 = __webpack_require__(16);
- var di_2 = __webpack_require__(6);
- var platform_directives_and_pipes_1 = __webpack_require__(95);
- var util_1 = __webpack_require__(155);
- var url_resolver_1 = __webpack_require__(148);
- var RuntimeMetadataResolver = (function () {
- function RuntimeMetadataResolver(_directiveResolver, _viewResolver, _platformDirectives) {
- this._directiveResolver = _directiveResolver;
- this._viewResolver = _viewResolver;
- this._platformDirectives = _platformDirectives;
- this._cache = new Map();
- }
- RuntimeMetadataResolver.prototype.getMetadata = function (directiveType) {
- var meta = this._cache.get(directiveType);
- if (lang_1.isBlank(meta)) {
- var dirMeta = this._directiveResolver.resolve(directiveType);
- var moduleUrl = null;
- var templateMeta = null;
- var changeDetectionStrategy = null;
- if (dirMeta instanceof md.ComponentMetadata) {
- var cmpMeta = dirMeta;
- moduleUrl = calcModuleUrl(directiveType, cmpMeta);
- var viewMeta = this._viewResolver.resolve(directiveType);
- templateMeta = new cpl.CompileTemplateMetadata({
- encapsulation: viewMeta.encapsulation,
- template: viewMeta.template,
- templateUrl: viewMeta.templateUrl,
- styles: viewMeta.styles,
- styleUrls: viewMeta.styleUrls
- });
- changeDetectionStrategy = cmpMeta.changeDetection;
- }
- meta = cpl.CompileDirectiveMetadata.create({
- selector: dirMeta.selector,
- exportAs: dirMeta.exportAs,
- isComponent: lang_1.isPresent(templateMeta),
- dynamicLoadable: true,
- type: new cpl.CompileTypeMetadata({ name: lang_1.stringify(directiveType), moduleUrl: moduleUrl, runtime: directiveType }),
- template: templateMeta,
- changeDetection: changeDetectionStrategy,
- inputs: dirMeta.inputs,
- outputs: dirMeta.outputs,
- host: dirMeta.host,
- lifecycleHooks: interfaces_1.LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return directive_lifecycle_reflector_1.hasLifecycleHook(hook, directiveType); })
- });
- this._cache.set(directiveType, meta);
- }
- return meta;
- };
- RuntimeMetadataResolver.prototype.getViewDirectivesMetadata = function (component) {
- var _this = this;
- var view = this._viewResolver.resolve(component);
- var directives = flattenDirectives(view, this._platformDirectives);
- for (var i = 0; i < directives.length; i++) {
- if (!isValidDirective(directives[i])) {
- throw new exceptions_1.BaseException("Unexpected directive value '" + lang_1.stringify(directives[i]) + "' on the View of component '" + lang_1.stringify(component) + "'");
- }
- }
- return directives.map(function (type) { return _this.getMetadata(type); });
- };
- RuntimeMetadataResolver = __decorate([
- di_2.Injectable(),
- __param(2, di_2.Optional()),
- __param(2, di_2.Inject(platform_directives_and_pipes_1.PLATFORM_DIRECTIVES)),
- __metadata('design:paramtypes', [directive_resolver_1.DirectiveResolver, view_resolver_1.ViewResolver, Array])
- ], RuntimeMetadataResolver);
- return RuntimeMetadataResolver;
- })();
- exports.RuntimeMetadataResolver = RuntimeMetadataResolver;
- function flattenDirectives(view, platformDirectives) {
- var directives = [];
- if (lang_1.isPresent(platformDirectives)) {
- flattenArray(platformDirectives, directives);
- }
- if (lang_1.isPresent(view.directives)) {
- flattenArray(view.directives, directives);
- }
- return directives;
- }
- function flattenArray(tree, out) {
- for (var i = 0; i < tree.length; i++) {
- var item = di_1.resolveForwardRef(tree[i]);
- if (lang_1.isArray(item)) {
- flattenArray(item, out);
- }
- else {
- out.push(item);
- }
- }
- }
- function isValidDirective(value) {
- return lang_1.isPresent(value) && (value instanceof lang_1.Type);
- }
- function calcModuleUrl(type, cmpMetadata) {
- var moduleId = cmpMetadata.moduleId;
- if (lang_1.isPresent(moduleId)) {
- var scheme = url_resolver_1.getUrlScheme(moduleId);
- return lang_1.isPresent(scheme) && scheme.length > 0 ? moduleId :
- "package:" + moduleId + util_1.MODULE_SUFFIX;
- }
- else {
- return reflection_1.reflector.importUri(type);
- }
- }
- /***/ },
- /* 177 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var dom_adapter_1 = __webpack_require__(178);
- var html_tags_1 = __webpack_require__(172);
- var element_schema_registry_1 = __webpack_require__(173);
- var NAMESPACE_URIS = lang_1.CONST_EXPR({ 'xlink': 'http://www.w3.org/1999/xlink', 'svg': 'http://www.w3.org/2000/svg' });
- var DomElementSchemaRegistry = (function (_super) {
- __extends(DomElementSchemaRegistry, _super);
- function DomElementSchemaRegistry() {
- _super.apply(this, arguments);
- this._protoElements = new Map();
- }
- DomElementSchemaRegistry.prototype._getProtoElement = function (tagName) {
- var element = this._protoElements.get(tagName);
- if (lang_1.isBlank(element)) {
- var nsAndName = html_tags_1.splitNsName(tagName);
- element = lang_1.isPresent(nsAndName[0]) ?
- dom_adapter_1.DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) :
- dom_adapter_1.DOM.createElement(nsAndName[1]);
- this._protoElements.set(tagName, element);
- }
- return element;
- };
- DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName) {
- if (tagName.indexOf('-') !== -1) {
- // can't tell now as we don't know which properties a custom element will get
- // once it is instantiated
- return true;
- }
- else {
- var elm = this._getProtoElement(tagName);
- return dom_adapter_1.DOM.hasProperty(elm, propName);
- }
- };
- DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) {
- var mappedPropName = collection_1.StringMapWrapper.get(dom_adapter_1.DOM.attrToPropMap, propName);
- return lang_1.isPresent(mappedPropName) ? mappedPropName : propName;
- };
- DomElementSchemaRegistry = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], DomElementSchemaRegistry);
- return DomElementSchemaRegistry;
- })(element_schema_registry_1.ElementSchemaRegistry);
- exports.DomElementSchemaRegistry = DomElementSchemaRegistry;
- /***/ },
- /* 178 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- exports.DOM = null;
- function setRootDomAdapter(adapter) {
- if (lang_1.isBlank(exports.DOM)) {
- exports.DOM = adapter;
- }
- }
- exports.setRootDomAdapter = setRootDomAdapter;
- /* tslint:disable:requireParameterType */
- /**
- * Provides DOM operations in an environment-agnostic way.
- */
- var DomAdapter = (function () {
- function DomAdapter() {
- }
- return DomAdapter;
- })();
- exports.DomAdapter = DomAdapter;
- /***/ },
- /* 179 */
- /***/ function(module, exports, __webpack_require__) {
- var angular_entrypoint_1 = __webpack_require__(180);
- exports.AngularEntrypoint = angular_entrypoint_1.AngularEntrypoint;
- var browser_common_1 = __webpack_require__(181);
- exports.BROWSER_PROVIDERS = browser_common_1.BROWSER_PROVIDERS;
- exports.ELEMENT_PROBE_BINDINGS = browser_common_1.ELEMENT_PROBE_BINDINGS;
- exports.ELEMENT_PROBE_PROVIDERS = browser_common_1.ELEMENT_PROBE_PROVIDERS;
- exports.inspectNativeElement = browser_common_1.inspectNativeElement;
- exports.BrowserDomAdapter = browser_common_1.BrowserDomAdapter;
- exports.By = browser_common_1.By;
- exports.Title = browser_common_1.Title;
- exports.DOCUMENT = browser_common_1.DOCUMENT;
- exports.enableDebugTools = browser_common_1.enableDebugTools;
- exports.disableDebugTools = browser_common_1.disableDebugTools;
- var lang_1 = __webpack_require__(5);
- var browser_common_2 = __webpack_require__(181);
- var compiler_1 = __webpack_require__(147);
- var core_1 = __webpack_require__(2);
- var reflection_capabilities_1 = __webpack_require__(18);
- var xhr_impl_1 = __webpack_require__(199);
- var compiler_2 = __webpack_require__(147);
- var di_1 = __webpack_require__(6);
- /**
- * An array of providers that should be passed into `application()` when bootstrapping a component.
- */
- exports.BROWSER_APP_PROVIDERS = lang_1.CONST_EXPR([
- browser_common_2.BROWSER_APP_COMMON_PROVIDERS,
- compiler_1.COMPILER_PROVIDERS,
- new di_1.Provider(compiler_2.XHR, { useClass: xhr_impl_1.XHRImpl }),
- ]);
- /**
- * Bootstrapping for Angular applications.
- *
- * You instantiate an Angular application by explicitly specifying a component to use
- * as the root component for your application via the `bootstrap()` method.
- *
- * ## Simple Example
- *
- * Assuming this `index.html`:
- *
- * ```html
- * <html>
- * <!-- load Angular script tags here. -->
- * <body>
- * <my-app>loading...</my-app>
- * </body>
- * </html>
- * ```
- *
- * An application is bootstrapped inside an existing browser DOM, typically `index.html`.
- * Unlike Angular 1, Angular 2 does not compile/process providers in `index.html`. This is
- * mainly for security reasons, as well as architectural changes in Angular 2. This means
- * that `index.html` can safely be processed using server-side technologies such as
- * providers. Bindings can thus use double-curly `{{ syntax }}` without collision from
- * Angular 2 component double-curly `{{ syntax }}`.
- *
- * We can use this script code:
- *
- * {@example core/ts/bootstrap/bootstrap.ts region='bootstrap'}
- *
- * When the app developer invokes `bootstrap()` with the root component `MyApp` as its
- * argument, Angular performs the following tasks:
- *
- * 1. It uses the component's `selector` property to locate the DOM element which needs
- * to be upgraded into the angular component.
- * 2. It creates a new child injector (from the platform injector). Optionally, you can
- * also override the injector configuration for an app by invoking `bootstrap` with the
- * `componentInjectableBindings` argument.
- * 3. It creates a new `Zone` and connects it to the angular application's change detection
- * domain instance.
- * 4. It creates an emulated or shadow DOM on the selected component's host element and loads the
- * template into it.
- * 5. It instantiates the specified component.
- * 6. Finally, Angular performs change detection to apply the initial data providers for the
- * application.
- *
- *
- * ## Bootstrapping Multiple Applications
- *
- * When working within a browser window, there are many singleton resources: cookies, title,
- * location, and others. Angular services that represent these resources must likewise be
- * shared across all Angular applications that occupy the same browser window. For this
- * reason, Angular creates exactly one global platform object which stores all shared
- * services, and each angular application injector has the platform injector as its parent.
- *
- * Each application has its own private injector as well. When there are multiple
- * applications on a page, Angular treats each application injector's services as private
- * to that application.
- *
- * ## API
- *
- * - `appComponentType`: The root component which should act as the application. This is
- * a reference to a `Type` which is annotated with `@Component(...)`.
- * - `customProviders`: An additional set of providers that can be added to the
- * app injector to override default injection behavior.
- *
- * Returns a `Promise` of {@link ComponentRef}.
- */
- function bootstrap(appComponentType, customProviders) {
- core_1.reflector.reflectionCapabilities = new reflection_capabilities_1.ReflectionCapabilities();
- var appProviders = lang_1.isPresent(customProviders) ? [exports.BROWSER_APP_PROVIDERS, customProviders] : exports.BROWSER_APP_PROVIDERS;
- return core_1.platform(browser_common_2.BROWSER_PROVIDERS).application(appProviders).bootstrap(appComponentType);
- }
- exports.bootstrap = bootstrap;
- /***/ },
- /* 180 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- /**
- * Marks a function or method as an Angular 2 entrypoint. Only necessary in Dart code.
- *
- * The optional `name` parameter will be reflected in logs when the entry point is processed.
- *
- * See [the wiki][] for detailed documentation.
- * [the wiki]: https://github.com/angular/angular/wiki/Angular-2-Dart-Transformer#entry_points
- *
- * ## Example
- *
- * ```
- * @AngularEntrypoint("name-for-debug")
- * void main() {
- * bootstrap(MyComponent);
- * }
- * ```
- */
- var AngularEntrypoint = (function () {
- function AngularEntrypoint(name) {
- this.name = name;
- }
- AngularEntrypoint = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], AngularEntrypoint);
- return AngularEntrypoint;
- })();
- exports.AngularEntrypoint = AngularEntrypoint;
- /***/ },
- /* 181 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var di_1 = __webpack_require__(6);
- var core_1 = __webpack_require__(2);
- var common_1 = __webpack_require__(104);
- var testability_1 = __webpack_require__(68);
- var dom_adapter_1 = __webpack_require__(178);
- var dom_events_1 = __webpack_require__(182);
- var key_events_1 = __webpack_require__(184);
- var hammer_gestures_1 = __webpack_require__(185);
- var dom_tokens_1 = __webpack_require__(187);
- var dom_renderer_1 = __webpack_require__(188);
- var shared_styles_host_1 = __webpack_require__(196);
- var shared_styles_host_2 = __webpack_require__(196);
- var browser_details_1 = __webpack_require__(195);
- var animation_builder_1 = __webpack_require__(189);
- var browser_adapter_1 = __webpack_require__(197);
- var testability_2 = __webpack_require__(200);
- var wtf_init_1 = __webpack_require__(201);
- var event_manager_1 = __webpack_require__(183);
- var dom_tokens_2 = __webpack_require__(187);
- exports.DOCUMENT = dom_tokens_2.DOCUMENT;
- var title_1 = __webpack_require__(202);
- exports.Title = title_1.Title;
- var common_dom_1 = __webpack_require__(203);
- exports.DebugElementViewListener = common_dom_1.DebugElementViewListener;
- exports.ELEMENT_PROBE_PROVIDERS = common_dom_1.ELEMENT_PROBE_PROVIDERS;
- exports.ELEMENT_PROBE_BINDINGS = common_dom_1.ELEMENT_PROBE_BINDINGS;
- exports.inspectNativeElement = common_dom_1.inspectNativeElement;
- exports.By = common_dom_1.By;
- var browser_adapter_2 = __webpack_require__(197);
- exports.BrowserDomAdapter = browser_adapter_2.BrowserDomAdapter;
- var tools_1 = __webpack_require__(206);
- exports.enableDebugTools = tools_1.enableDebugTools;
- exports.disableDebugTools = tools_1.disableDebugTools;
- /**
- * A set of providers to initialize the Angular platform in a web browser.
- *
- * Used automatically by `bootstrap`, or can be passed to {@link platform}.
- */
- exports.BROWSER_PROVIDERS = lang_1.CONST_EXPR([
- core_1.PLATFORM_COMMON_PROVIDERS,
- new di_1.Provider(core_1.PLATFORM_INITIALIZER, { useValue: initDomAdapter, multi: true }),
- ]);
- function _exceptionHandler() {
- // !IS_DART is required because we must rethrow exceptions in JS,
- // but must not rethrow exceptions in Dart
- return new core_1.ExceptionHandler(dom_adapter_1.DOM, !lang_1.IS_DART);
- }
- function _document() {
- return dom_adapter_1.DOM.defaultDoc();
- }
- /**
- * A set of providers to initialize an Angular application in a web browser.
- *
- * Used automatically by `bootstrap`, or can be passed to {@link PlatformRef.application}.
- */
- exports.BROWSER_APP_COMMON_PROVIDERS = lang_1.CONST_EXPR([
- core_1.APPLICATION_COMMON_PROVIDERS,
- common_1.FORM_PROVIDERS,
- new di_1.Provider(core_1.PLATFORM_PIPES, { useValue: common_1.COMMON_PIPES, multi: true }),
- new di_1.Provider(core_1.PLATFORM_DIRECTIVES, { useValue: common_1.COMMON_DIRECTIVES, multi: true }),
- new di_1.Provider(core_1.ExceptionHandler, { useFactory: _exceptionHandler, deps: [] }),
- new di_1.Provider(dom_tokens_1.DOCUMENT, { useFactory: _document, deps: [] }),
- new di_1.Provider(event_manager_1.EVENT_MANAGER_PLUGINS, { useClass: dom_events_1.DomEventsPlugin, multi: true }),
- new di_1.Provider(event_manager_1.EVENT_MANAGER_PLUGINS, { useClass: key_events_1.KeyEventsPlugin, multi: true }),
- new di_1.Provider(event_manager_1.EVENT_MANAGER_PLUGINS, { useClass: hammer_gestures_1.HammerGesturesPlugin, multi: true }),
- new di_1.Provider(dom_renderer_1.DomRenderer, { useClass: dom_renderer_1.DomRenderer_ }),
- new di_1.Provider(core_1.Renderer, { useExisting: dom_renderer_1.DomRenderer }),
- new di_1.Provider(shared_styles_host_2.SharedStylesHost, { useExisting: shared_styles_host_1.DomSharedStylesHost }),
- shared_styles_host_1.DomSharedStylesHost,
- testability_1.Testability,
- browser_details_1.BrowserDetails,
- animation_builder_1.AnimationBuilder,
- event_manager_1.EventManager
- ]);
- function initDomAdapter() {
- browser_adapter_1.BrowserDomAdapter.makeCurrent();
- wtf_init_1.wtfInit();
- testability_2.BrowserGetTestability.init();
- }
- exports.initDomAdapter = initDomAdapter;
- /***/ },
- /* 182 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var dom_adapter_1 = __webpack_require__(178);
- var core_1 = __webpack_require__(2);
- var event_manager_1 = __webpack_require__(183);
- var DomEventsPlugin = (function (_super) {
- __extends(DomEventsPlugin, _super);
- function DomEventsPlugin() {
- _super.apply(this, arguments);
- }
- // This plugin should come last in the list of plugins, because it accepts all
- // events.
- DomEventsPlugin.prototype.supports = function (eventName) { return true; };
- DomEventsPlugin.prototype.addEventListener = function (element, eventName, handler) {
- var zone = this.manager.getZone();
- var outsideHandler = function (event) { return zone.run(function () { return handler(event); }); };
- this.manager.getZone().runOutsideAngular(function () { dom_adapter_1.DOM.on(element, eventName, outsideHandler); });
- };
- DomEventsPlugin.prototype.addGlobalEventListener = function (target, eventName, handler) {
- var element = dom_adapter_1.DOM.getGlobalEventTarget(target);
- var zone = this.manager.getZone();
- var outsideHandler = function (event) { return zone.run(function () { return handler(event); }); };
- return this.manager.getZone().runOutsideAngular(function () { return dom_adapter_1.DOM.onAndCancel(element, eventName, outsideHandler); });
- };
- DomEventsPlugin = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], DomEventsPlugin);
- return DomEventsPlugin;
- })(event_manager_1.EventManagerPlugin);
- exports.DomEventsPlugin = DomEventsPlugin;
- /***/ },
- /* 183 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var di_1 = __webpack_require__(6);
- var ng_zone_1 = __webpack_require__(66);
- var collection_1 = __webpack_require__(12);
- exports.EVENT_MANAGER_PLUGINS = lang_1.CONST_EXPR(new di_1.OpaqueToken("EventManagerPlugins"));
- var EventManager = (function () {
- function EventManager(plugins, _zone) {
- var _this = this;
- this._zone = _zone;
- plugins.forEach(function (p) { return p.manager = _this; });
- this._plugins = collection_1.ListWrapper.reversed(plugins);
- }
- EventManager.prototype.addEventListener = function (element, eventName, handler) {
- var plugin = this._findPluginFor(eventName);
- plugin.addEventListener(element, eventName, handler);
- };
- EventManager.prototype.addGlobalEventListener = function (target, eventName, handler) {
- var plugin = this._findPluginFor(eventName);
- return plugin.addGlobalEventListener(target, eventName, handler);
- };
- EventManager.prototype.getZone = function () { return this._zone; };
- /** @internal */
- EventManager.prototype._findPluginFor = function (eventName) {
- var plugins = this._plugins;
- for (var i = 0; i < plugins.length; i++) {
- var plugin = plugins[i];
- if (plugin.supports(eventName)) {
- return plugin;
- }
- }
- throw new exceptions_1.BaseException("No event manager plugin found for event " + eventName);
- };
- EventManager = __decorate([
- di_1.Injectable(),
- __param(0, di_1.Inject(exports.EVENT_MANAGER_PLUGINS)),
- __metadata('design:paramtypes', [Array, ng_zone_1.NgZone])
- ], EventManager);
- return EventManager;
- })();
- exports.EventManager = EventManager;
- var EventManagerPlugin = (function () {
- function EventManagerPlugin() {
- }
- // That is equivalent to having supporting $event.target
- EventManagerPlugin.prototype.supports = function (eventName) { return false; };
- EventManagerPlugin.prototype.addEventListener = function (element, eventName, handler) {
- throw "not implemented";
- };
- EventManagerPlugin.prototype.addGlobalEventListener = function (element, eventName, handler) {
- throw "not implemented";
- };
- return EventManagerPlugin;
- })();
- exports.EventManagerPlugin = EventManagerPlugin;
- /***/ },
- /* 184 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var dom_adapter_1 = __webpack_require__(178);
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var event_manager_1 = __webpack_require__(183);
- var di_1 = __webpack_require__(6);
- var modifierKeys = ['alt', 'control', 'meta', 'shift'];
- var modifierKeyGetters = {
- 'alt': function (event) { return event.altKey; },
- 'control': function (event) { return event.ctrlKey; },
- 'meta': function (event) { return event.metaKey; },
- 'shift': function (event) { return event.shiftKey; }
- };
- var KeyEventsPlugin = (function (_super) {
- __extends(KeyEventsPlugin, _super);
- function KeyEventsPlugin() {
- _super.call(this);
- }
- KeyEventsPlugin.prototype.supports = function (eventName) {
- return lang_1.isPresent(KeyEventsPlugin.parseEventName(eventName));
- };
- KeyEventsPlugin.prototype.addEventListener = function (element, eventName, handler) {
- var parsedEvent = KeyEventsPlugin.parseEventName(eventName);
- var outsideHandler = KeyEventsPlugin.eventCallback(element, collection_1.StringMapWrapper.get(parsedEvent, 'fullKey'), handler, this.manager.getZone());
- this.manager.getZone().runOutsideAngular(function () {
- dom_adapter_1.DOM.on(element, collection_1.StringMapWrapper.get(parsedEvent, 'domEventName'), outsideHandler);
- });
- };
- KeyEventsPlugin.parseEventName = function (eventName) {
- var parts = eventName.toLowerCase().split('.');
- var domEventName = parts.shift();
- if ((parts.length === 0) ||
- !(lang_1.StringWrapper.equals(domEventName, 'keydown') ||
- lang_1.StringWrapper.equals(domEventName, 'keyup'))) {
- return null;
- }
- var key = KeyEventsPlugin._normalizeKey(parts.pop());
- var fullKey = '';
- modifierKeys.forEach(function (modifierName) {
- if (collection_1.ListWrapper.contains(parts, modifierName)) {
- collection_1.ListWrapper.remove(parts, modifierName);
- fullKey += modifierName + '.';
- }
- });
- fullKey += key;
- if (parts.length != 0 || key.length === 0) {
- // returning null instead of throwing to let another plugin process the event
- return null;
- }
- var result = collection_1.StringMapWrapper.create();
- collection_1.StringMapWrapper.set(result, 'domEventName', domEventName);
- collection_1.StringMapWrapper.set(result, 'fullKey', fullKey);
- return result;
- };
- KeyEventsPlugin.getEventFullKey = function (event) {
- var fullKey = '';
- var key = dom_adapter_1.DOM.getEventKey(event);
- key = key.toLowerCase();
- if (lang_1.StringWrapper.equals(key, ' ')) {
- key = 'space'; // for readability
- }
- else if (lang_1.StringWrapper.equals(key, '.')) {
- key = 'dot'; // because '.' is used as a separator in event names
- }
- modifierKeys.forEach(function (modifierName) {
- if (modifierName != key) {
- var modifierGetter = collection_1.StringMapWrapper.get(modifierKeyGetters, modifierName);
- if (modifierGetter(event)) {
- fullKey += modifierName + '.';
- }
- }
- });
- fullKey += key;
- return fullKey;
- };
- KeyEventsPlugin.eventCallback = function (element, fullKey, handler, zone) {
- return function (event) {
- if (lang_1.StringWrapper.equals(KeyEventsPlugin.getEventFullKey(event), fullKey)) {
- zone.run(function () { return handler(event); });
- }
- };
- };
- /** @internal */
- KeyEventsPlugin._normalizeKey = function (keyName) {
- // TODO: switch to a StringMap if the mapping grows too much
- switch (keyName) {
- case 'esc':
- return 'escape';
- default:
- return keyName;
- }
- };
- KeyEventsPlugin = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], KeyEventsPlugin);
- return KeyEventsPlugin;
- })(event_manager_1.EventManagerPlugin);
- exports.KeyEventsPlugin = KeyEventsPlugin;
- /***/ },
- /* 185 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var hammer_common_1 = __webpack_require__(186);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var di_1 = __webpack_require__(6);
- var HammerGesturesPlugin = (function (_super) {
- __extends(HammerGesturesPlugin, _super);
- function HammerGesturesPlugin() {
- _super.apply(this, arguments);
- }
- HammerGesturesPlugin.prototype.supports = function (eventName) {
- if (!_super.prototype.supports.call(this, eventName))
- return false;
- if (!lang_1.isPresent(window['Hammer'])) {
- throw new exceptions_1.BaseException("Hammer.js is not loaded, can not bind " + eventName + " event");
- }
- return true;
- };
- HammerGesturesPlugin.prototype.addEventListener = function (element, eventName, handler) {
- var zone = this.manager.getZone();
- eventName = eventName.toLowerCase();
- zone.runOutsideAngular(function () {
- // Creating the manager bind events, must be done outside of angular
- var mc = new Hammer(element);
- mc.get('pinch').set({ enable: true });
- mc.get('rotate').set({ enable: true });
- mc.on(eventName, function (eventObj) { zone.run(function () { handler(eventObj); }); });
- });
- };
- HammerGesturesPlugin = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], HammerGesturesPlugin);
- return HammerGesturesPlugin;
- })(hammer_common_1.HammerGesturesPluginCommon);
- exports.HammerGesturesPlugin = HammerGesturesPlugin;
- /***/ },
- /* 186 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var event_manager_1 = __webpack_require__(183);
- var collection_1 = __webpack_require__(12);
- var _eventNames = {
- // pan
- 'pan': true,
- 'panstart': true,
- 'panmove': true,
- 'panend': true,
- 'pancancel': true,
- 'panleft': true,
- 'panright': true,
- 'panup': true,
- 'pandown': true,
- // pinch
- 'pinch': true,
- 'pinchstart': true,
- 'pinchmove': true,
- 'pinchend': true,
- 'pinchcancel': true,
- 'pinchin': true,
- 'pinchout': true,
- // press
- 'press': true,
- 'pressup': true,
- // rotate
- 'rotate': true,
- 'rotatestart': true,
- 'rotatemove': true,
- 'rotateend': true,
- 'rotatecancel': true,
- // swipe
- 'swipe': true,
- 'swipeleft': true,
- 'swiperight': true,
- 'swipeup': true,
- 'swipedown': true,
- // tap
- 'tap': true,
- };
- var HammerGesturesPluginCommon = (function (_super) {
- __extends(HammerGesturesPluginCommon, _super);
- function HammerGesturesPluginCommon() {
- _super.call(this);
- }
- HammerGesturesPluginCommon.prototype.supports = function (eventName) {
- eventName = eventName.toLowerCase();
- return collection_1.StringMapWrapper.contains(_eventNames, eventName);
- };
- return HammerGesturesPluginCommon;
- })(event_manager_1.EventManagerPlugin);
- exports.HammerGesturesPluginCommon = HammerGesturesPluginCommon;
- /***/ },
- /* 187 */
- /***/ function(module, exports, __webpack_require__) {
- var di_1 = __webpack_require__(6);
- var lang_1 = __webpack_require__(5);
- /**
- * A DI Token representing the main rendering context. In a browser this is the DOM Document.
- *
- * Note: Document might not be available in the Application Context when Application and Rendering
- * Contexts are not the same (e.g. when running the application into a Web Worker).
- */
- exports.DOCUMENT = lang_1.CONST_EXPR(new di_1.OpaqueToken('DocumentToken'));
- /***/ },
- /* 188 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var di_1 = __webpack_require__(6);
- var animation_builder_1 = __webpack_require__(189);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var shared_styles_host_1 = __webpack_require__(196);
- var profile_1 = __webpack_require__(45);
- var core_1 = __webpack_require__(2);
- var event_manager_1 = __webpack_require__(183);
- var dom_tokens_1 = __webpack_require__(187);
- var view_factory_1 = __webpack_require__(164);
- var view_1 = __webpack_require__(165);
- var metadata_1 = __webpack_require__(3);
- var dom_adapter_1 = __webpack_require__(178);
- var util_1 = __webpack_require__(194);
- var NAMESPACE_URIS = lang_1.CONST_EXPR({ 'xlink': 'http://www.w3.org/1999/xlink', 'svg': 'http://www.w3.org/2000/svg' });
- var TEMPLATE_COMMENT_TEXT = 'template bindings={}';
- var TEMPLATE_BINDINGS_EXP = /^template bindings=(.*)$/g;
- var DomRenderer = (function (_super) {
- __extends(DomRenderer, _super);
- function DomRenderer() {
- _super.apply(this, arguments);
- }
- DomRenderer.prototype.getNativeElementSync = function (location) {
- return resolveInternalDomView(location.renderView).boundElements[location.boundElementIndex];
- };
- DomRenderer.prototype.getRootNodes = function (fragment) { return resolveInternalDomFragment(fragment); };
- DomRenderer.prototype.attachFragmentAfterFragment = function (previousFragmentRef, fragmentRef) {
- var previousFragmentNodes = resolveInternalDomFragment(previousFragmentRef);
- if (previousFragmentNodes.length > 0) {
- var sibling = previousFragmentNodes[previousFragmentNodes.length - 1];
- var nodes = resolveInternalDomFragment(fragmentRef);
- moveNodesAfterSibling(sibling, nodes);
- this.animateNodesEnter(nodes);
- }
- };
- /**
- * Iterates through all nodes being added to the DOM and animates them if necessary
- * @param nodes
- */
- DomRenderer.prototype.animateNodesEnter = function (nodes) {
- for (var i = 0; i < nodes.length; i++)
- this.animateNodeEnter(nodes[i]);
- };
- DomRenderer.prototype.attachFragmentAfterElement = function (elementRef, fragmentRef) {
- var parentView = resolveInternalDomView(elementRef.renderView);
- var element = parentView.boundElements[elementRef.boundElementIndex];
- var nodes = resolveInternalDomFragment(fragmentRef);
- moveNodesAfterSibling(element, nodes);
- this.animateNodesEnter(nodes);
- };
- DomRenderer.prototype.hydrateView = function (viewRef) { resolveInternalDomView(viewRef).hydrate(); };
- DomRenderer.prototype.dehydrateView = function (viewRef) { resolveInternalDomView(viewRef).dehydrate(); };
- DomRenderer.prototype.createTemplateAnchor = function (attrNameAndValues) {
- return dom_adapter_1.DOM.createComment(TEMPLATE_COMMENT_TEXT);
- };
- DomRenderer.prototype.createText = function (value) { return dom_adapter_1.DOM.createTextNode(lang_1.isPresent(value) ? value : ''); };
- DomRenderer.prototype.appendChild = function (parent, child) { dom_adapter_1.DOM.appendChild(parent, child); };
- DomRenderer.prototype.setElementProperty = function (location, propertyName, propertyValue) {
- var view = resolveInternalDomView(location.renderView);
- dom_adapter_1.DOM.setProperty(view.boundElements[location.boundElementIndex], propertyName, propertyValue);
- };
- DomRenderer.prototype.setElementAttribute = function (location, attributeName, attributeValue) {
- var view = resolveInternalDomView(location.renderView);
- var element = view.boundElements[location.boundElementIndex];
- if (lang_1.isPresent(attributeValue)) {
- dom_adapter_1.DOM.setAttribute(element, attributeName, lang_1.stringify(attributeValue));
- }
- else {
- dom_adapter_1.DOM.removeAttribute(element, attributeName);
- }
- };
- /**
- * Used only in debug mode to serialize property changes to comment nodes,
- * such as <template> placeholders.
- */
- DomRenderer.prototype.setBindingDebugInfo = function (location, propertyName, propertyValue) {
- var view = resolveInternalDomView(location.renderView);
- var element = view.boundElements[location.boundElementIndex];
- var dashCasedPropertyName = util_1.camelCaseToDashCase(propertyName);
- if (dom_adapter_1.DOM.isCommentNode(element)) {
- var existingBindings = lang_1.RegExpWrapper.firstMatch(TEMPLATE_BINDINGS_EXP, lang_1.StringWrapper.replaceAll(dom_adapter_1.DOM.getText(element), /\n/g, ''));
- var parsedBindings = lang_1.Json.parse(existingBindings[1]);
- parsedBindings[dashCasedPropertyName] = propertyValue;
- dom_adapter_1.DOM.setText(element, lang_1.StringWrapper.replace(TEMPLATE_COMMENT_TEXT, '{}', lang_1.Json.stringify(parsedBindings)));
- }
- else {
- this.setElementAttribute(location, propertyName, propertyValue);
- }
- };
- DomRenderer.prototype.setElementClass = function (location, className, isAdd) {
- var view = resolveInternalDomView(location.renderView);
- var element = view.boundElements[location.boundElementIndex];
- if (isAdd) {
- dom_adapter_1.DOM.addClass(element, className);
- }
- else {
- dom_adapter_1.DOM.removeClass(element, className);
- }
- };
- DomRenderer.prototype.setElementStyle = function (location, styleName, styleValue) {
- var view = resolveInternalDomView(location.renderView);
- var element = view.boundElements[location.boundElementIndex];
- if (lang_1.isPresent(styleValue)) {
- dom_adapter_1.DOM.setStyle(element, styleName, lang_1.stringify(styleValue));
- }
- else {
- dom_adapter_1.DOM.removeStyle(element, styleName);
- }
- };
- DomRenderer.prototype.invokeElementMethod = function (location, methodName, args) {
- var view = resolveInternalDomView(location.renderView);
- var element = view.boundElements[location.boundElementIndex];
- dom_adapter_1.DOM.invoke(element, methodName, args);
- };
- DomRenderer.prototype.setText = function (viewRef, textNodeIndex, text) {
- var view = resolveInternalDomView(viewRef);
- dom_adapter_1.DOM.setText(view.boundTextNodes[textNodeIndex], text);
- };
- DomRenderer.prototype.setEventDispatcher = function (viewRef, dispatcher) {
- resolveInternalDomView(viewRef).setEventDispatcher(dispatcher);
- };
- return DomRenderer;
- })(core_1.Renderer);
- exports.DomRenderer = DomRenderer;
- var DomRenderer_ = (function (_super) {
- __extends(DomRenderer_, _super);
- function DomRenderer_(_eventManager, _domSharedStylesHost, _animate, document) {
- _super.call(this);
- this._eventManager = _eventManager;
- this._domSharedStylesHost = _domSharedStylesHost;
- this._animate = _animate;
- this._componentTpls = new Map();
- /** @internal */
- this._createRootHostViewScope = profile_1.wtfCreateScope('DomRenderer#createRootHostView()');
- /** @internal */
- this._createViewScope = profile_1.wtfCreateScope('DomRenderer#createView()');
- /** @internal */
- this._detachFragmentScope = profile_1.wtfCreateScope('DomRenderer#detachFragment()');
- this._document = document;
- }
- DomRenderer_.prototype.registerComponentTemplate = function (template) {
- this._componentTpls.set(template.id, template);
- if (template.encapsulation !== metadata_1.ViewEncapsulation.Native) {
- var encapsulatedStyles = view_factory_1.encapsulateStyles(template);
- this._domSharedStylesHost.addStyles(encapsulatedStyles);
- }
- };
- DomRenderer_.prototype.createProtoView = function (componentTemplateId, cmds) {
- return new view_1.DefaultProtoViewRef(this._componentTpls.get(componentTemplateId), cmds);
- };
- DomRenderer_.prototype.resolveComponentTemplate = function (templateId) {
- return this._componentTpls.get(templateId);
- };
- DomRenderer_.prototype.createRootHostView = function (hostProtoViewRef, fragmentCount, hostElementSelector) {
- var s = this._createRootHostViewScope();
- var element = dom_adapter_1.DOM.querySelector(this._document, hostElementSelector);
- if (lang_1.isBlank(element)) {
- profile_1.wtfLeave(s);
- throw new exceptions_1.BaseException("The selector \"" + hostElementSelector + "\" did not match any elements");
- }
- return profile_1.wtfLeave(s, this._createView(hostProtoViewRef, element));
- };
- DomRenderer_.prototype.createView = function (protoViewRef, fragmentCount) {
- var s = this._createViewScope();
- return profile_1.wtfLeave(s, this._createView(protoViewRef, null));
- };
- DomRenderer_.prototype._createView = function (protoViewRef, inplaceElement) {
- var dpvr = protoViewRef;
- var view = view_factory_1.createRenderView(dpvr.template, dpvr.cmds, inplaceElement, this);
- var sdRoots = view.nativeShadowRoots;
- for (var i = 0; i < sdRoots.length; i++) {
- this._domSharedStylesHost.addHost(sdRoots[i]);
- }
- return new core_1.RenderViewWithFragments(view, view.fragments);
- };
- DomRenderer_.prototype.destroyView = function (viewRef) {
- var view = viewRef;
- var sdRoots = view.nativeShadowRoots;
- for (var i = 0; i < sdRoots.length; i++) {
- this._domSharedStylesHost.removeHost(sdRoots[i]);
- }
- };
- DomRenderer_.prototype.animateNodeEnter = function (node) {
- if (dom_adapter_1.DOM.isElementNode(node) && dom_adapter_1.DOM.hasClass(node, 'ng-animate')) {
- dom_adapter_1.DOM.addClass(node, 'ng-enter');
- this._animate.css()
- .addAnimationClass('ng-enter-active')
- .start(node)
- .onComplete(function () { dom_adapter_1.DOM.removeClass(node, 'ng-enter'); });
- }
- };
- DomRenderer_.prototype.animateNodeLeave = function (node) {
- if (dom_adapter_1.DOM.isElementNode(node) && dom_adapter_1.DOM.hasClass(node, 'ng-animate')) {
- dom_adapter_1.DOM.addClass(node, 'ng-leave');
- this._animate.css()
- .addAnimationClass('ng-leave-active')
- .start(node)
- .onComplete(function () {
- dom_adapter_1.DOM.removeClass(node, 'ng-leave');
- dom_adapter_1.DOM.remove(node);
- });
- }
- else {
- dom_adapter_1.DOM.remove(node);
- }
- };
- DomRenderer_.prototype.detachFragment = function (fragmentRef) {
- var s = this._detachFragmentScope();
- var fragmentNodes = resolveInternalDomFragment(fragmentRef);
- for (var i = 0; i < fragmentNodes.length; i++) {
- this.animateNodeLeave(fragmentNodes[i]);
- }
- profile_1.wtfLeave(s);
- };
- DomRenderer_.prototype.createElement = function (name, attrNameAndValues) {
- var nsAndName = splitNamespace(name);
- var el = lang_1.isPresent(nsAndName[0]) ?
- dom_adapter_1.DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) :
- dom_adapter_1.DOM.createElement(nsAndName[1]);
- this._setAttributes(el, attrNameAndValues);
- return el;
- };
- DomRenderer_.prototype.mergeElement = function (existing, attrNameAndValues) {
- dom_adapter_1.DOM.clearNodes(existing);
- this._setAttributes(existing, attrNameAndValues);
- };
- DomRenderer_.prototype._setAttributes = function (node, attrNameAndValues) {
- for (var attrIdx = 0; attrIdx < attrNameAndValues.length; attrIdx += 2) {
- var attrNs;
- var attrName = attrNameAndValues[attrIdx];
- var nsAndName = splitNamespace(attrName);
- if (lang_1.isPresent(nsAndName[0])) {
- attrName = nsAndName[0] + ':' + nsAndName[1];
- attrNs = NAMESPACE_URIS[nsAndName[0]];
- }
- var attrValue = attrNameAndValues[attrIdx + 1];
- if (lang_1.isPresent(attrNs)) {
- dom_adapter_1.DOM.setAttributeNS(node, attrNs, attrName, attrValue);
- }
- else {
- dom_adapter_1.DOM.setAttribute(node, nsAndName[1], attrValue);
- }
- }
- };
- DomRenderer_.prototype.createRootContentInsertionPoint = function () {
- return dom_adapter_1.DOM.createComment('root-content-insertion-point');
- };
- DomRenderer_.prototype.createShadowRoot = function (host, templateId) {
- var sr = dom_adapter_1.DOM.createShadowRoot(host);
- var tpl = this._componentTpls.get(templateId);
- for (var i = 0; i < tpl.styles.length; i++) {
- dom_adapter_1.DOM.appendChild(sr, dom_adapter_1.DOM.createStyleElement(tpl.styles[i]));
- }
- return sr;
- };
- DomRenderer_.prototype.on = function (element, eventName, callback) {
- this._eventManager.addEventListener(element, eventName, decoratePreventDefault(callback));
- };
- DomRenderer_.prototype.globalOn = function (target, eventName, callback) {
- return this._eventManager.addGlobalEventListener(target, eventName, decoratePreventDefault(callback));
- };
- DomRenderer_ = __decorate([
- di_1.Injectable(),
- __param(3, di_1.Inject(dom_tokens_1.DOCUMENT)),
- __metadata('design:paramtypes', [event_manager_1.EventManager, shared_styles_host_1.DomSharedStylesHost, animation_builder_1.AnimationBuilder, Object])
- ], DomRenderer_);
- return DomRenderer_;
- })(DomRenderer);
- exports.DomRenderer_ = DomRenderer_;
- function resolveInternalDomView(viewRef) {
- return viewRef;
- }
- function resolveInternalDomFragment(fragmentRef) {
- return fragmentRef.nodes;
- }
- function moveNodesAfterSibling(sibling, nodes) {
- var parent = dom_adapter_1.DOM.parentElement(sibling);
- if (nodes.length > 0 && lang_1.isPresent(parent)) {
- var nextSibling = dom_adapter_1.DOM.nextSibling(sibling);
- if (lang_1.isPresent(nextSibling)) {
- for (var i = 0; i < nodes.length; i++) {
- dom_adapter_1.DOM.insertBefore(nextSibling, nodes[i]);
- }
- }
- else {
- for (var i = 0; i < nodes.length; i++) {
- dom_adapter_1.DOM.appendChild(parent, nodes[i]);
- }
- }
- }
- }
- function decoratePreventDefault(eventHandler) {
- return function (event) {
- var allowDefaultBehavior = eventHandler(event);
- if (!allowDefaultBehavior) {
- // TODO(tbosch): move preventDefault into event plugins...
- dom_adapter_1.DOM.preventDefault(event);
- }
- };
- }
- var NS_PREFIX_RE = /^@([^:]+):(.+)/g;
- function splitNamespace(name) {
- if (name[0] != '@') {
- return [null, name];
- }
- var match = lang_1.RegExpWrapper.firstMatch(NS_PREFIX_RE, name);
- return [match[1], match[2]];
- }
- /***/ },
- /* 189 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var css_animation_builder_1 = __webpack_require__(190);
- var browser_details_1 = __webpack_require__(195);
- var AnimationBuilder = (function () {
- /**
- * Used for DI
- * @param browserDetails
- */
- function AnimationBuilder(browserDetails) {
- this.browserDetails = browserDetails;
- }
- /**
- * Creates a new CSS Animation
- * @returns {CssAnimationBuilder}
- */
- AnimationBuilder.prototype.css = function () { return new css_animation_builder_1.CssAnimationBuilder(this.browserDetails); };
- AnimationBuilder = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [browser_details_1.BrowserDetails])
- ], AnimationBuilder);
- return AnimationBuilder;
- })();
- exports.AnimationBuilder = AnimationBuilder;
- /***/ },
- /* 190 */
- /***/ function(module, exports, __webpack_require__) {
- var css_animation_options_1 = __webpack_require__(191);
- var animation_1 = __webpack_require__(192);
- var CssAnimationBuilder = (function () {
- /**
- * Accepts public properties for CssAnimationBuilder
- */
- function CssAnimationBuilder(browserDetails) {
- this.browserDetails = browserDetails;
- /** @type {CssAnimationOptions} */
- this.data = new css_animation_options_1.CssAnimationOptions();
- }
- /**
- * Adds a temporary class that will be removed at the end of the animation
- * @param className
- */
- CssAnimationBuilder.prototype.addAnimationClass = function (className) {
- this.data.animationClasses.push(className);
- return this;
- };
- /**
- * Adds a class that will remain on the element after the animation has finished
- * @param className
- */
- CssAnimationBuilder.prototype.addClass = function (className) {
- this.data.classesToAdd.push(className);
- return this;
- };
- /**
- * Removes a class from the element
- * @param className
- */
- CssAnimationBuilder.prototype.removeClass = function (className) {
- this.data.classesToRemove.push(className);
- return this;
- };
- /**
- * Sets the animation duration (and overrides any defined through CSS)
- * @param duration
- */
- CssAnimationBuilder.prototype.setDuration = function (duration) {
- this.data.duration = duration;
- return this;
- };
- /**
- * Sets the animation delay (and overrides any defined through CSS)
- * @param delay
- */
- CssAnimationBuilder.prototype.setDelay = function (delay) {
- this.data.delay = delay;
- return this;
- };
- /**
- * Sets styles for both the initial state and the destination state
- * @param from
- * @param to
- */
- CssAnimationBuilder.prototype.setStyles = function (from, to) {
- return this.setFromStyles(from).setToStyles(to);
- };
- /**
- * Sets the initial styles for the animation
- * @param from
- */
- CssAnimationBuilder.prototype.setFromStyles = function (from) {
- this.data.fromStyles = from;
- return this;
- };
- /**
- * Sets the destination styles for the animation
- * @param to
- */
- CssAnimationBuilder.prototype.setToStyles = function (to) {
- this.data.toStyles = to;
- return this;
- };
- /**
- * Starts the animation and returns a promise
- * @param element
- */
- CssAnimationBuilder.prototype.start = function (element) {
- return new animation_1.Animation(element, this.data, this.browserDetails);
- };
- return CssAnimationBuilder;
- })();
- exports.CssAnimationBuilder = CssAnimationBuilder;
- /***/ },
- /* 191 */
- /***/ function(module, exports) {
- var CssAnimationOptions = (function () {
- function CssAnimationOptions() {
- /** classes to be added to the element */
- this.classesToAdd = [];
- /** classes to be removed from the element */
- this.classesToRemove = [];
- /** classes to be added for the duration of the animation */
- this.animationClasses = [];
- }
- return CssAnimationOptions;
- })();
- exports.CssAnimationOptions = CssAnimationOptions;
- /***/ },
- /* 192 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var math_1 = __webpack_require__(193);
- var util_1 = __webpack_require__(194);
- var collection_1 = __webpack_require__(12);
- var dom_adapter_1 = __webpack_require__(178);
- var Animation = (function () {
- /**
- * Stores the start time and starts the animation
- * @param element
- * @param data
- * @param browserDetails
- */
- function Animation(element, data, browserDetails) {
- var _this = this;
- this.element = element;
- this.data = data;
- this.browserDetails = browserDetails;
- /** functions to be called upon completion */
- this.callbacks = [];
- /** functions for removing event listeners */
- this.eventClearFunctions = [];
- /** flag used to track whether or not the animation has finished */
- this.completed = false;
- this._stringPrefix = '';
- this.startTime = lang_1.DateWrapper.toMillis(lang_1.DateWrapper.now());
- this._stringPrefix = dom_adapter_1.DOM.getAnimationPrefix();
- this.setup();
- this.wait(function (timestamp) { return _this.start(); });
- }
- Object.defineProperty(Animation.prototype, "totalTime", {
- /** total amount of time that the animation should take including delay */
- get: function () {
- var delay = this.computedDelay != null ? this.computedDelay : 0;
- var duration = this.computedDuration != null ? this.computedDuration : 0;
- return delay + duration;
- },
- enumerable: true,
- configurable: true
- });
- Animation.prototype.wait = function (callback) {
- // Firefox requires 2 frames for some reason
- this.browserDetails.raf(callback, 2);
- };
- /**
- * Sets up the initial styles before the animation is started
- */
- Animation.prototype.setup = function () {
- if (this.data.fromStyles != null)
- this.applyStyles(this.data.fromStyles);
- if (this.data.duration != null)
- this.applyStyles({ 'transitionDuration': this.data.duration.toString() + 'ms' });
- if (this.data.delay != null)
- this.applyStyles({ 'transitionDelay': this.data.delay.toString() + 'ms' });
- };
- /**
- * After the initial setup has occurred, this method adds the animation styles
- */
- Animation.prototype.start = function () {
- this.addClasses(this.data.classesToAdd);
- this.addClasses(this.data.animationClasses);
- this.removeClasses(this.data.classesToRemove);
- if (this.data.toStyles != null)
- this.applyStyles(this.data.toStyles);
- var computedStyles = dom_adapter_1.DOM.getComputedStyle(this.element);
- this.computedDelay =
- math_1.Math.max(this.parseDurationString(computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), this.parseDurationString(this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay')));
- this.computedDuration = math_1.Math.max(this.parseDurationString(computedStyles.getPropertyValue(this._stringPrefix + 'transition-duration')), this.parseDurationString(this.element.style.getPropertyValue(this._stringPrefix + 'transition-duration')));
- this.addEvents();
- };
- /**
- * Applies the provided styles to the element
- * @param styles
- */
- Animation.prototype.applyStyles = function (styles) {
- var _this = this;
- collection_1.StringMapWrapper.forEach(styles, function (value, key) {
- var dashCaseKey = util_1.camelCaseToDashCase(key);
- if (lang_1.isPresent(dom_adapter_1.DOM.getStyle(_this.element, dashCaseKey))) {
- dom_adapter_1.DOM.setStyle(_this.element, dashCaseKey, value.toString());
- }
- else {
- dom_adapter_1.DOM.setStyle(_this.element, _this._stringPrefix + dashCaseKey, value.toString());
- }
- });
- };
- /**
- * Adds the provided classes to the element
- * @param classes
- */
- Animation.prototype.addClasses = function (classes) {
- for (var i = 0, len = classes.length; i < len; i++)
- dom_adapter_1.DOM.addClass(this.element, classes[i]);
- };
- /**
- * Removes the provided classes from the element
- * @param classes
- */
- Animation.prototype.removeClasses = function (classes) {
- for (var i = 0, len = classes.length; i < len; i++)
- dom_adapter_1.DOM.removeClass(this.element, classes[i]);
- };
- /**
- * Adds events to track when animations have finished
- */
- Animation.prototype.addEvents = function () {
- var _this = this;
- if (this.totalTime > 0) {
- this.eventClearFunctions.push(dom_adapter_1.DOM.onAndCancel(this.element, dom_adapter_1.DOM.getTransitionEnd(), function (event) { return _this.handleAnimationEvent(event); }));
- }
- else {
- this.handleAnimationCompleted();
- }
- };
- Animation.prototype.handleAnimationEvent = function (event) {
- var elapsedTime = math_1.Math.round(event.elapsedTime * 1000);
- if (!this.browserDetails.elapsedTimeIncludesDelay)
- elapsedTime += this.computedDelay;
- event.stopPropagation();
- if (elapsedTime >= this.totalTime)
- this.handleAnimationCompleted();
- };
- /**
- * Runs all animation callbacks and removes temporary classes
- */
- Animation.prototype.handleAnimationCompleted = function () {
- this.removeClasses(this.data.animationClasses);
- this.callbacks.forEach(function (callback) { return callback(); });
- this.callbacks = [];
- this.eventClearFunctions.forEach(function (fn) { return fn(); });
- this.eventClearFunctions = [];
- this.completed = true;
- };
- /**
- * Adds animation callbacks to be called upon completion
- * @param callback
- * @returns {Animation}
- */
- Animation.prototype.onComplete = function (callback) {
- if (this.completed) {
- callback();
- }
- else {
- this.callbacks.push(callback);
- }
- return this;
- };
- /**
- * Converts the duration string to the number of milliseconds
- * @param duration
- * @returns {number}
- */
- Animation.prototype.parseDurationString = function (duration) {
- var maxValue = 0;
- // duration must have at least 2 characters to be valid. (number + type)
- if (duration == null || duration.length < 2) {
- return maxValue;
- }
- else if (duration.substring(duration.length - 2) == 'ms') {
- var value = lang_1.NumberWrapper.parseInt(this.stripLetters(duration), 10);
- if (value > maxValue)
- maxValue = value;
- }
- else if (duration.substring(duration.length - 1) == 's') {
- var ms = lang_1.NumberWrapper.parseFloat(this.stripLetters(duration)) * 1000;
- var value = math_1.Math.floor(ms);
- if (value > maxValue)
- maxValue = value;
- }
- return maxValue;
- };
- /**
- * Strips the letters from the duration string
- * @param str
- * @returns {string}
- */
- Animation.prototype.stripLetters = function (str) {
- return lang_1.StringWrapper.replaceAll(str, lang_1.RegExpWrapper.create('[^0-9]+$', ''), '');
- };
- return Animation;
- })();
- exports.Animation = Animation;
- /***/ },
- /* 193 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- exports.Math = lang_1.global.Math;
- exports.NaN = typeof exports.NaN;
- /***/ },
- /* 194 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var CAMEL_CASE_REGEXP = /([A-Z])/g;
- var DASH_CASE_REGEXP = /-([a-z])/g;
- function camelCaseToDashCase(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function (m) { return '-' + m[1].toLowerCase(); });
- }
- exports.camelCaseToDashCase = camelCaseToDashCase;
- function dashCaseToCamelCase(input) {
- return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function (m) { return m[1].toUpperCase(); });
- }
- exports.dashCaseToCamelCase = dashCaseToCamelCase;
- /***/ },
- /* 195 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var di_1 = __webpack_require__(6);
- var math_1 = __webpack_require__(193);
- var dom_adapter_1 = __webpack_require__(178);
- var BrowserDetails = (function () {
- function BrowserDetails() {
- this.elapsedTimeIncludesDelay = false;
- this.doesElapsedTimeIncludesDelay();
- }
- /**
- * Determines if `event.elapsedTime` includes transition delay in the current browser. At this
- * time, Chrome and Opera seem to be the only browsers that include this.
- */
- BrowserDetails.prototype.doesElapsedTimeIncludesDelay = function () {
- var _this = this;
- var div = dom_adapter_1.DOM.createElement('div');
- dom_adapter_1.DOM.setAttribute(div, 'style', "position: absolute; top: -9999px; left: -9999px; width: 1px;\n height: 1px; transition: all 1ms linear 1ms;");
- // Firefox requires that we wait for 2 frames for some reason
- this.raf(function (timestamp) {
- dom_adapter_1.DOM.on(div, 'transitionend', function (event) {
- var elapsed = math_1.Math.round(event.elapsedTime * 1000);
- _this.elapsedTimeIncludesDelay = elapsed == 2;
- dom_adapter_1.DOM.remove(div);
- });
- dom_adapter_1.DOM.setStyle(div, 'width', '2px');
- }, 2);
- };
- BrowserDetails.prototype.raf = function (callback, frames) {
- if (frames === void 0) { frames = 1; }
- var queue = new RafQueue(callback, frames);
- return function () { return queue.cancel(); };
- };
- BrowserDetails = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], BrowserDetails);
- return BrowserDetails;
- })();
- exports.BrowserDetails = BrowserDetails;
- var RafQueue = (function () {
- function RafQueue(callback, frames) {
- this.callback = callback;
- this.frames = frames;
- this._raf();
- }
- RafQueue.prototype._raf = function () {
- var _this = this;
- this.currentFrameId = dom_adapter_1.DOM.requestAnimationFrame(function (timestamp) { return _this._nextFrame(timestamp); });
- };
- RafQueue.prototype._nextFrame = function (timestamp) {
- this.frames--;
- if (this.frames > 0) {
- this._raf();
- }
- else {
- this.callback(timestamp);
- }
- };
- RafQueue.prototype.cancel = function () {
- dom_adapter_1.DOM.cancelAnimationFrame(this.currentFrameId);
- this.currentFrameId = null;
- };
- return RafQueue;
- })();
- /***/ },
- /* 196 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var dom_adapter_1 = __webpack_require__(178);
- var di_1 = __webpack_require__(6);
- var collection_1 = __webpack_require__(12);
- var dom_tokens_1 = __webpack_require__(187);
- var SharedStylesHost = (function () {
- function SharedStylesHost() {
- /** @internal */
- this._styles = [];
- /** @internal */
- this._stylesSet = new Set();
- }
- SharedStylesHost.prototype.addStyles = function (styles) {
- var _this = this;
- var additions = [];
- styles.forEach(function (style) {
- if (!collection_1.SetWrapper.has(_this._stylesSet, style)) {
- _this._stylesSet.add(style);
- _this._styles.push(style);
- additions.push(style);
- }
- });
- this.onStylesAdded(additions);
- };
- SharedStylesHost.prototype.onStylesAdded = function (additions) { };
- SharedStylesHost.prototype.getAllStyles = function () { return this._styles; };
- SharedStylesHost = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], SharedStylesHost);
- return SharedStylesHost;
- })();
- exports.SharedStylesHost = SharedStylesHost;
- var DomSharedStylesHost = (function (_super) {
- __extends(DomSharedStylesHost, _super);
- function DomSharedStylesHost(doc) {
- _super.call(this);
- this._hostNodes = new Set();
- this._hostNodes.add(doc.head);
- }
- /** @internal */
- DomSharedStylesHost.prototype._addStylesToHost = function (styles, host) {
- for (var i = 0; i < styles.length; i++) {
- var style = styles[i];
- dom_adapter_1.DOM.appendChild(host, dom_adapter_1.DOM.createStyleElement(style));
- }
- };
- DomSharedStylesHost.prototype.addHost = function (hostNode) {
- this._addStylesToHost(this._styles, hostNode);
- this._hostNodes.add(hostNode);
- };
- DomSharedStylesHost.prototype.removeHost = function (hostNode) { collection_1.SetWrapper.delete(this._hostNodes, hostNode); };
- DomSharedStylesHost.prototype.onStylesAdded = function (additions) {
- var _this = this;
- this._hostNodes.forEach(function (hostNode) { _this._addStylesToHost(additions, hostNode); });
- };
- DomSharedStylesHost = __decorate([
- di_1.Injectable(),
- __param(0, di_1.Inject(dom_tokens_1.DOCUMENT)),
- __metadata('design:paramtypes', [Object])
- ], DomSharedStylesHost);
- return DomSharedStylesHost;
- })(SharedStylesHost);
- exports.DomSharedStylesHost = DomSharedStylesHost;
- /***/ },
- /* 197 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var dom_adapter_1 = __webpack_require__(178);
- var generic_browser_adapter_1 = __webpack_require__(198);
- var _attrToPropMap = {
- 'class': 'className',
- 'innerHtml': 'innerHTML',
- 'readonly': 'readOnly',
- 'tabindex': 'tabIndex'
- };
- var DOM_KEY_LOCATION_NUMPAD = 3;
- // Map to convert some key or keyIdentifier values to what will be returned by getEventKey
- var _keyMap = {
- // The following values are here for cross-browser compatibility and to match the W3C standard
- // cf http://www.w3.org/TR/DOM-Level-3-Events-key/
- '\b': 'Backspace',
- '\t': 'Tab',
- '\x7F': 'Delete',
- '\x1B': 'Escape',
- 'Del': 'Delete',
- 'Esc': 'Escape',
- 'Left': 'ArrowLeft',
- 'Right': 'ArrowRight',
- 'Up': 'ArrowUp',
- 'Down': 'ArrowDown',
- 'Menu': 'ContextMenu',
- 'Scroll': 'ScrollLock',
- 'Win': 'OS'
- };
- // There is a bug in Chrome for numeric keypad keys:
- // https://code.google.com/p/chromium/issues/detail?id=155654
- // 1, 2, 3 ... are reported as A, B, C ...
- var _chromeNumKeyPadMap = {
- 'A': '1',
- 'B': '2',
- 'C': '3',
- 'D': '4',
- 'E': '5',
- 'F': '6',
- 'G': '7',
- 'H': '8',
- 'I': '9',
- 'J': '*',
- 'K': '+',
- 'M': '-',
- 'N': '.',
- 'O': '/',
- '\x60': '0',
- '\x90': 'NumLock'
- };
- /**
- * A `DomAdapter` powered by full browser DOM APIs.
- */
- /* tslint:disable:requireParameterType */
- var BrowserDomAdapter = (function (_super) {
- __extends(BrowserDomAdapter, _super);
- function BrowserDomAdapter() {
- _super.apply(this, arguments);
- }
- BrowserDomAdapter.prototype.parse = function (templateHtml) { throw new Error("parse not implemented"); };
- BrowserDomAdapter.makeCurrent = function () { dom_adapter_1.setRootDomAdapter(new BrowserDomAdapter()); };
- BrowserDomAdapter.prototype.hasProperty = function (element, name) { return name in element; };
- BrowserDomAdapter.prototype.setProperty = function (el, name, value) { el[name] = value; };
- BrowserDomAdapter.prototype.getProperty = function (el, name) { return el[name]; };
- BrowserDomAdapter.prototype.invoke = function (el, methodName, args) {
- el[methodName].apply(el, args);
- };
- // TODO(tbosch): move this into a separate environment class once we have it
- BrowserDomAdapter.prototype.logError = function (error) {
- if (window.console.error) {
- window.console.error(error);
- }
- else {
- window.console.log(error);
- }
- };
- BrowserDomAdapter.prototype.log = function (error) { window.console.log(error); };
- BrowserDomAdapter.prototype.logGroup = function (error) {
- if (window.console.group) {
- window.console.group(error);
- this.logError(error);
- }
- else {
- window.console.log(error);
- }
- };
- BrowserDomAdapter.prototype.logGroupEnd = function () {
- if (window.console.groupEnd) {
- window.console.groupEnd();
- }
- };
- Object.defineProperty(BrowserDomAdapter.prototype, "attrToPropMap", {
- get: function () { return _attrToPropMap; },
- enumerable: true,
- configurable: true
- });
- BrowserDomAdapter.prototype.query = function (selector) { return document.querySelector(selector); };
- BrowserDomAdapter.prototype.querySelector = function (el, selector) { return el.querySelector(selector); };
- BrowserDomAdapter.prototype.querySelectorAll = function (el, selector) { return el.querySelectorAll(selector); };
- BrowserDomAdapter.prototype.on = function (el, evt, listener) { el.addEventListener(evt, listener, false); };
- BrowserDomAdapter.prototype.onAndCancel = function (el, evt, listener) {
- el.addEventListener(evt, listener, false);
- // Needed to follow Dart's subscription semantic, until fix of
- // https://code.google.com/p/dart/issues/detail?id=17406
- return function () { el.removeEventListener(evt, listener, false); };
- };
- BrowserDomAdapter.prototype.dispatchEvent = function (el, evt) { el.dispatchEvent(evt); };
- BrowserDomAdapter.prototype.createMouseEvent = function (eventType) {
- var evt = document.createEvent('MouseEvent');
- evt.initEvent(eventType, true, true);
- return evt;
- };
- BrowserDomAdapter.prototype.createEvent = function (eventType) {
- var evt = document.createEvent('Event');
- evt.initEvent(eventType, true, true);
- return evt;
- };
- BrowserDomAdapter.prototype.preventDefault = function (evt) {
- evt.preventDefault();
- evt.returnValue = false;
- };
- BrowserDomAdapter.prototype.isPrevented = function (evt) {
- return evt.defaultPrevented || lang_1.isPresent(evt.returnValue) && !evt.returnValue;
- };
- BrowserDomAdapter.prototype.getInnerHTML = function (el) { return el.innerHTML; };
- BrowserDomAdapter.prototype.getOuterHTML = function (el) { return el.outerHTML; };
- BrowserDomAdapter.prototype.nodeName = function (node) { return node.nodeName; };
- BrowserDomAdapter.prototype.nodeValue = function (node) { return node.nodeValue; };
- BrowserDomAdapter.prototype.type = function (node) { return node.type; };
- BrowserDomAdapter.prototype.content = function (node) {
- if (this.hasProperty(node, "content")) {
- return node.content;
- }
- else {
- return node;
- }
- };
- BrowserDomAdapter.prototype.firstChild = function (el) { return el.firstChild; };
- BrowserDomAdapter.prototype.nextSibling = function (el) { return el.nextSibling; };
- BrowserDomAdapter.prototype.parentElement = function (el) { return el.parentNode; };
- BrowserDomAdapter.prototype.childNodes = function (el) { return el.childNodes; };
- BrowserDomAdapter.prototype.childNodesAsList = function (el) {
- var childNodes = el.childNodes;
- var res = collection_1.ListWrapper.createFixedSize(childNodes.length);
- for (var i = 0; i < childNodes.length; i++) {
- res[i] = childNodes[i];
- }
- return res;
- };
- BrowserDomAdapter.prototype.clearNodes = function (el) {
- while (el.firstChild) {
- el.removeChild(el.firstChild);
- }
- };
- BrowserDomAdapter.prototype.appendChild = function (el, node) { el.appendChild(node); };
- BrowserDomAdapter.prototype.removeChild = function (el, node) { el.removeChild(node); };
- BrowserDomAdapter.prototype.replaceChild = function (el, newChild, oldChild) { el.replaceChild(newChild, oldChild); };
- BrowserDomAdapter.prototype.remove = function (node) {
- if (node.parentNode) {
- node.parentNode.removeChild(node);
- }
- return node;
- };
- BrowserDomAdapter.prototype.insertBefore = function (el, node) { el.parentNode.insertBefore(node, el); };
- BrowserDomAdapter.prototype.insertAllBefore = function (el, nodes) { nodes.forEach(function (n) { return el.parentNode.insertBefore(n, el); }); };
- BrowserDomAdapter.prototype.insertAfter = function (el, node) { el.parentNode.insertBefore(node, el.nextSibling); };
- BrowserDomAdapter.prototype.setInnerHTML = function (el, value) { el.innerHTML = value; };
- BrowserDomAdapter.prototype.getText = function (el) { return el.textContent; };
- // TODO(vicb): removed Element type because it does not support StyleElement
- BrowserDomAdapter.prototype.setText = function (el, value) { el.textContent = value; };
- BrowserDomAdapter.prototype.getValue = function (el) { return el.value; };
- BrowserDomAdapter.prototype.setValue = function (el, value) { el.value = value; };
- BrowserDomAdapter.prototype.getChecked = function (el) { return el.checked; };
- BrowserDomAdapter.prototype.setChecked = function (el, value) { el.checked = value; };
- BrowserDomAdapter.prototype.createComment = function (text) { return document.createComment(text); };
- BrowserDomAdapter.prototype.createTemplate = function (html) {
- var t = document.createElement('template');
- t.innerHTML = html;
- return t;
- };
- BrowserDomAdapter.prototype.createElement = function (tagName, doc) {
- if (doc === void 0) { doc = document; }
- return doc.createElement(tagName);
- };
- BrowserDomAdapter.prototype.createElementNS = function (ns, tagName, doc) {
- if (doc === void 0) { doc = document; }
- return doc.createElementNS(ns, tagName);
- };
- BrowserDomAdapter.prototype.createTextNode = function (text, doc) {
- if (doc === void 0) { doc = document; }
- return doc.createTextNode(text);
- };
- BrowserDomAdapter.prototype.createScriptTag = function (attrName, attrValue, doc) {
- if (doc === void 0) { doc = document; }
- var el = doc.createElement('SCRIPT');
- el.setAttribute(attrName, attrValue);
- return el;
- };
- BrowserDomAdapter.prototype.createStyleElement = function (css, doc) {
- if (doc === void 0) { doc = document; }
- var style = doc.createElement('style');
- this.appendChild(style, this.createTextNode(css));
- return style;
- };
- BrowserDomAdapter.prototype.createShadowRoot = function (el) { return el.createShadowRoot(); };
- BrowserDomAdapter.prototype.getShadowRoot = function (el) { return el.shadowRoot; };
- BrowserDomAdapter.prototype.getHost = function (el) { return el.host; };
- BrowserDomAdapter.prototype.clone = function (node) { return node.cloneNode(true); };
- BrowserDomAdapter.prototype.getElementsByClassName = function (element, name) {
- return element.getElementsByClassName(name);
- };
- BrowserDomAdapter.prototype.getElementsByTagName = function (element, name) {
- return element.getElementsByTagName(name);
- };
- BrowserDomAdapter.prototype.classList = function (element) { return Array.prototype.slice.call(element.classList, 0); };
- BrowserDomAdapter.prototype.addClass = function (element, className) { element.classList.add(className); };
- BrowserDomAdapter.prototype.removeClass = function (element, className) { element.classList.remove(className); };
- BrowserDomAdapter.prototype.hasClass = function (element, className) { return element.classList.contains(className); };
- BrowserDomAdapter.prototype.setStyle = function (element, styleName, styleValue) {
- element.style[styleName] = styleValue;
- };
- BrowserDomAdapter.prototype.removeStyle = function (element, stylename) { element.style[stylename] = null; };
- BrowserDomAdapter.prototype.getStyle = function (element, stylename) { return element.style[stylename]; };
- BrowserDomAdapter.prototype.hasStyle = function (element, styleName, styleValue) {
- if (styleValue === void 0) { styleValue = null; }
- var value = this.getStyle(element, styleName) || '';
- return styleValue ? value == styleValue : value.length > 0;
- };
- BrowserDomAdapter.prototype.tagName = function (element) { return element.tagName; };
- BrowserDomAdapter.prototype.attributeMap = function (element) {
- var res = new Map();
- var elAttrs = element.attributes;
- for (var i = 0; i < elAttrs.length; i++) {
- var attrib = elAttrs[i];
- res.set(attrib.name, attrib.value);
- }
- return res;
- };
- BrowserDomAdapter.prototype.hasAttribute = function (element, attribute) { return element.hasAttribute(attribute); };
- BrowserDomAdapter.prototype.getAttribute = function (element, attribute) { return element.getAttribute(attribute); };
- BrowserDomAdapter.prototype.setAttribute = function (element, name, value) { element.setAttribute(name, value); };
- BrowserDomAdapter.prototype.setAttributeNS = function (element, ns, name, value) {
- element.setAttributeNS(ns, name, value);
- };
- BrowserDomAdapter.prototype.removeAttribute = function (element, attribute) { element.removeAttribute(attribute); };
- BrowserDomAdapter.prototype.templateAwareRoot = function (el) { return this.isTemplateElement(el) ? this.content(el) : el; };
- BrowserDomAdapter.prototype.createHtmlDocument = function () {
- return document.implementation.createHTMLDocument('fakeTitle');
- };
- BrowserDomAdapter.prototype.defaultDoc = function () { return document; };
- BrowserDomAdapter.prototype.getBoundingClientRect = function (el) {
- try {
- return el.getBoundingClientRect();
- }
- catch (e) {
- return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 };
- }
- };
- BrowserDomAdapter.prototype.getTitle = function () { return document.title; };
- BrowserDomAdapter.prototype.setTitle = function (newTitle) { document.title = newTitle || ''; };
- BrowserDomAdapter.prototype.elementMatches = function (n, selector) {
- var matches = false;
- if (n instanceof HTMLElement) {
- if (n.matches) {
- matches = n.matches(selector);
- }
- else if (n.msMatchesSelector) {
- matches = n.msMatchesSelector(selector);
- }
- else if (n.webkitMatchesSelector) {
- matches = n.webkitMatchesSelector(selector);
- }
- }
- return matches;
- };
- BrowserDomAdapter.prototype.isTemplateElement = function (el) {
- return el instanceof HTMLElement && el.nodeName == "TEMPLATE";
- };
- BrowserDomAdapter.prototype.isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
- BrowserDomAdapter.prototype.isCommentNode = function (node) { return node.nodeType === Node.COMMENT_NODE; };
- BrowserDomAdapter.prototype.isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
- BrowserDomAdapter.prototype.hasShadowRoot = function (node) { return node instanceof HTMLElement && lang_1.isPresent(node.shadowRoot); };
- BrowserDomAdapter.prototype.isShadowRoot = function (node) { return node instanceof DocumentFragment; };
- BrowserDomAdapter.prototype.importIntoDoc = function (node) {
- var toImport = node;
- if (this.isTemplateElement(node)) {
- toImport = this.content(node);
- }
- return document.importNode(toImport, true);
- };
- BrowserDomAdapter.prototype.adoptNode = function (node) { return document.adoptNode(node); };
- BrowserDomAdapter.prototype.getHref = function (el) { return el.href; };
- BrowserDomAdapter.prototype.getEventKey = function (event) {
- var key = event.key;
- if (lang_1.isBlank(key)) {
- key = event.keyIdentifier;
- // keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
- // Safari
- // cf
- // http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
- if (lang_1.isBlank(key)) {
- return 'Unidentified';
- }
- if (key.startsWith('U+')) {
- key = String.fromCharCode(parseInt(key.substring(2), 16));
- if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) {
- // There is a bug in Chrome for numeric keypad keys:
- // https://code.google.com/p/chromium/issues/detail?id=155654
- // 1, 2, 3 ... are reported as A, B, C ...
- key = _chromeNumKeyPadMap[key];
- }
- }
- }
- if (_keyMap.hasOwnProperty(key)) {
- key = _keyMap[key];
- }
- return key;
- };
- BrowserDomAdapter.prototype.getGlobalEventTarget = function (target) {
- if (target == "window") {
- return window;
- }
- else if (target == "document") {
- return document;
- }
- else if (target == "body") {
- return document.body;
- }
- };
- BrowserDomAdapter.prototype.getHistory = function () { return window.history; };
- BrowserDomAdapter.prototype.getLocation = function () { return window.location; };
- BrowserDomAdapter.prototype.getBaseHref = function () {
- var href = getBaseElementHref();
- if (lang_1.isBlank(href)) {
- return null;
- }
- return relativePath(href);
- };
- BrowserDomAdapter.prototype.resetBaseElement = function () { baseElement = null; };
- BrowserDomAdapter.prototype.getUserAgent = function () { return window.navigator.userAgent; };
- BrowserDomAdapter.prototype.setData = function (element, name, value) {
- this.setAttribute(element, 'data-' + name, value);
- };
- BrowserDomAdapter.prototype.getData = function (element, name) { return this.getAttribute(element, 'data-' + name); };
- BrowserDomAdapter.prototype.getComputedStyle = function (element) { return getComputedStyle(element); };
- // TODO(tbosch): move this into a separate environment class once we have it
- BrowserDomAdapter.prototype.setGlobalVar = function (path, value) { lang_1.setValueOnPath(lang_1.global, path, value); };
- BrowserDomAdapter.prototype.requestAnimationFrame = function (callback) { return window.requestAnimationFrame(callback); };
- BrowserDomAdapter.prototype.cancelAnimationFrame = function (id) { window.cancelAnimationFrame(id); };
- BrowserDomAdapter.prototype.performanceNow = function () {
- // performance.now() is not available in all browsers, see
- // http://caniuse.com/#search=performance.now
- if (lang_1.isPresent(window.performance) && lang_1.isPresent(window.performance.now)) {
- return window.performance.now();
- }
- else {
- return lang_1.DateWrapper.toMillis(lang_1.DateWrapper.now());
- }
- };
- return BrowserDomAdapter;
- })(generic_browser_adapter_1.GenericBrowserDomAdapter);
- exports.BrowserDomAdapter = BrowserDomAdapter;
- var baseElement = null;
- function getBaseElementHref() {
- if (lang_1.isBlank(baseElement)) {
- baseElement = document.querySelector('base');
- if (lang_1.isBlank(baseElement)) {
- return null;
- }
- }
- return baseElement.getAttribute('href');
- }
- // based on urlUtils.js in AngularJS 1
- var urlParsingNode = null;
- function relativePath(url) {
- if (lang_1.isBlank(urlParsingNode)) {
- urlParsingNode = document.createElement("a");
- }
- urlParsingNode.setAttribute('href', url);
- return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname :
- '/' + urlParsingNode.pathname;
- }
- /***/ },
- /* 198 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var dom_adapter_1 = __webpack_require__(178);
- var xhr_impl_1 = __webpack_require__(199);
- /**
- * Provides DOM operations in any browser environment.
- */
- var GenericBrowserDomAdapter = (function (_super) {
- __extends(GenericBrowserDomAdapter, _super);
- function GenericBrowserDomAdapter() {
- var _this = this;
- _super.call(this);
- this._animationPrefix = null;
- this._transitionEnd = null;
- try {
- var element = this.createElement('div', this.defaultDoc());
- if (lang_1.isPresent(this.getStyle(element, 'animationName'))) {
- this._animationPrefix = '';
- }
- else {
- var domPrefixes = ['Webkit', 'Moz', 'O', 'ms'];
- for (var i = 0; i < domPrefixes.length; i++) {
- if (lang_1.isPresent(this.getStyle(element, domPrefixes[i] + 'AnimationName'))) {
- this._animationPrefix = '-' + domPrefixes[i].toLowerCase() + '-';
- break;
- }
- }
- }
- var transEndEventNames = {
- WebkitTransition: 'webkitTransitionEnd',
- MozTransition: 'transitionend',
- OTransition: 'oTransitionEnd otransitionend',
- transition: 'transitionend'
- };
- collection_1.StringMapWrapper.forEach(transEndEventNames, function (value, key) {
- if (lang_1.isPresent(_this.getStyle(element, key))) {
- _this._transitionEnd = value;
- }
- });
- }
- catch (e) {
- this._animationPrefix = null;
- this._transitionEnd = null;
- }
- }
- GenericBrowserDomAdapter.prototype.getXHR = function () { return xhr_impl_1.XHRImpl; };
- GenericBrowserDomAdapter.prototype.getDistributedNodes = function (el) { return el.getDistributedNodes(); };
- GenericBrowserDomAdapter.prototype.resolveAndSetHref = function (el, baseUrl, href) {
- el.href = href == null ? baseUrl : baseUrl + '/../' + href;
- };
- GenericBrowserDomAdapter.prototype.supportsDOMEvents = function () { return true; };
- GenericBrowserDomAdapter.prototype.supportsNativeShadowDOM = function () {
- return lang_1.isFunction(this.defaultDoc().body.createShadowRoot);
- };
- GenericBrowserDomAdapter.prototype.getAnimationPrefix = function () {
- return lang_1.isPresent(this._animationPrefix) ? this._animationPrefix : "";
- };
- GenericBrowserDomAdapter.prototype.getTransitionEnd = function () { return lang_1.isPresent(this._transitionEnd) ? this._transitionEnd : ""; };
- GenericBrowserDomAdapter.prototype.supportsAnimation = function () {
- return lang_1.isPresent(this._animationPrefix) && lang_1.isPresent(this._transitionEnd);
- };
- return GenericBrowserDomAdapter;
- })(dom_adapter_1.DomAdapter);
- exports.GenericBrowserDomAdapter = GenericBrowserDomAdapter;
- /***/ },
- /* 199 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var promise_1 = __webpack_require__(61);
- var lang_1 = __webpack_require__(5);
- var xhr_1 = __webpack_require__(149);
- var XHRImpl = (function (_super) {
- __extends(XHRImpl, _super);
- function XHRImpl() {
- _super.apply(this, arguments);
- }
- XHRImpl.prototype.get = function (url) {
- var completer = promise_1.PromiseWrapper.completer();
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.responseType = 'text';
- xhr.onload = function () {
- // responseText is the old-school way of retrieving response (supported by IE8 & 9)
- // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
- var response = lang_1.isPresent(xhr.response) ? xhr.response : xhr.responseText;
- // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
- var status = xhr.status === 1223 ? 204 : xhr.status;
- // fix status code when it is 0 (0 status is undocumented).
- // Occurs when accessing file resources or on Android 4.1 stock browser
- // while retrieving files from application cache.
- if (status === 0) {
- status = response ? 200 : 0;
- }
- if (200 <= status && status <= 300) {
- completer.resolve(response);
- }
- else {
- completer.reject("Failed to load " + url, null);
- }
- };
- xhr.onerror = function () { completer.reject("Failed to load " + url, null); };
- xhr.send();
- return completer.promise;
- };
- return XHRImpl;
- })(xhr_1.XHR);
- exports.XHRImpl = XHRImpl;
- /***/ },
- /* 200 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var dom_adapter_1 = __webpack_require__(178);
- var core_1 = __webpack_require__(2);
- var PublicTestability = (function () {
- function PublicTestability(testability) {
- this._testability = testability;
- }
- PublicTestability.prototype.isStable = function () { return this._testability.isStable(); };
- PublicTestability.prototype.whenStable = function (callback) { this._testability.whenStable(callback); };
- PublicTestability.prototype.findBindings = function (using, provider, exactMatch) {
- return this.findProviders(using, provider, exactMatch);
- };
- PublicTestability.prototype.findProviders = function (using, provider, exactMatch) {
- return this._testability.findBindings(using, provider, exactMatch);
- };
- return PublicTestability;
- })();
- var BrowserGetTestability = (function () {
- function BrowserGetTestability() {
- }
- BrowserGetTestability.init = function () { core_1.setTestabilityGetter(new BrowserGetTestability()); };
- BrowserGetTestability.prototype.addToWindow = function (registry) {
- lang_1.global.getAngularTestability = function (elem, findInAncestors) {
- if (findInAncestors === void 0) { findInAncestors = true; }
- var testability = registry.findTestabilityInTree(elem, findInAncestors);
- if (testability == null) {
- throw new Error('Could not find testability for element.');
- }
- return new PublicTestability(testability);
- };
- lang_1.global.getAllAngularTestabilities = function () {
- var testabilities = registry.getAllTestabilities();
- return testabilities.map(function (testability) { return new PublicTestability(testability); });
- };
- };
- BrowserGetTestability.prototype.findTestabilityInTree = function (registry, elem, findInAncestors) {
- if (elem == null) {
- return null;
- }
- var t = registry.getTestability(elem);
- if (lang_1.isPresent(t)) {
- return t;
- }
- else if (!findInAncestors) {
- return null;
- }
- if (dom_adapter_1.DOM.isShadowRoot(elem)) {
- return this.findTestabilityInTree(registry, dom_adapter_1.DOM.getHost(elem), true);
- }
- return this.findTestabilityInTree(registry, dom_adapter_1.DOM.parentElement(elem), true);
- };
- return BrowserGetTestability;
- })();
- exports.BrowserGetTestability = BrowserGetTestability;
- /***/ },
- /* 201 */
- /***/ function(module, exports) {
- /**
- * This is here because DART requires it. It is noop in JS.
- */
- function wtfInit() { }
- exports.wtfInit = wtfInit;
- /***/ },
- /* 202 */
- /***/ function(module, exports, __webpack_require__) {
- var dom_adapter_1 = __webpack_require__(178);
- /**
- * A service that can be used to get and set the title of a current HTML document.
- *
- * Since an Angular 2 application can't be bootstrapped on the entire HTML document (`<html>` tag)
- * it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
- * (representing the `<title>` tag). Instead, this service can be used to set and get the current
- * title value.
- */
- var Title = (function () {
- function Title() {
- }
- /**
- * Get the title of the current HTML document.
- * @returns {string}
- */
- Title.prototype.getTitle = function () { return dom_adapter_1.DOM.getTitle(); };
- /**
- * Set the title of the current HTML document.
- * @param newTitle
- */
- Title.prototype.setTitle = function (newTitle) { dom_adapter_1.DOM.setTitle(newTitle); };
- return Title;
- })();
- exports.Title = Title;
- /***/ },
- /* 203 */
- /***/ function(module, exports, __webpack_require__) {
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- /**
- * This is a set of classes and objects that can be used both in the browser and on the server.
- */
- var dom_adapter_1 = __webpack_require__(178);
- exports.DOM = dom_adapter_1.DOM;
- exports.setRootDomAdapter = dom_adapter_1.setRootDomAdapter;
- exports.DomAdapter = dom_adapter_1.DomAdapter;
- var dom_renderer_1 = __webpack_require__(188);
- exports.DomRenderer = dom_renderer_1.DomRenderer;
- var dom_tokens_1 = __webpack_require__(187);
- exports.DOCUMENT = dom_tokens_1.DOCUMENT;
- var shared_styles_host_1 = __webpack_require__(196);
- exports.SharedStylesHost = shared_styles_host_1.SharedStylesHost;
- exports.DomSharedStylesHost = shared_styles_host_1.DomSharedStylesHost;
- var dom_events_1 = __webpack_require__(182);
- exports.DomEventsPlugin = dom_events_1.DomEventsPlugin;
- var event_manager_1 = __webpack_require__(183);
- exports.EVENT_MANAGER_PLUGINS = event_manager_1.EVENT_MANAGER_PLUGINS;
- exports.EventManager = event_manager_1.EventManager;
- exports.EventManagerPlugin = event_manager_1.EventManagerPlugin;
- __export(__webpack_require__(204));
- __export(__webpack_require__(205));
- /***/ },
- /* 204 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var dom_adapter_1 = __webpack_require__(178);
- /**
- * Predicates for use with {@link DebugElement}'s query functions.
- */
- var By = (function () {
- function By() {
- }
- /**
- * Match all elements.
- *
- * ## Example
- *
- * {@example platform/dom/debug/ts/by/by.ts region='by_all'}
- */
- By.all = function () { return function (debugElement) { return true; }; };
- /**
- * Match elements by the given CSS selector.
- *
- * ## Example
- *
- * {@example platform/dom/debug/ts/by/by.ts region='by_css'}
- */
- By.css = function (selector) {
- return function (debugElement) {
- return lang_1.isPresent(debugElement.nativeElement) ?
- dom_adapter_1.DOM.elementMatches(debugElement.nativeElement, selector) :
- false;
- };
- };
- /**
- * Match elements that have the given directive present.
- *
- * ## Example
- *
- * {@example platform/dom/debug/ts/by/by.ts region='by_directive'}
- */
- By.directive = function (type) {
- return function (debugElement) { return debugElement.hasDirective(type); };
- };
- return By;
- })();
- exports.By = By;
- /***/ },
- /* 205 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- var di_1 = __webpack_require__(6);
- var view_listener_1 = __webpack_require__(86);
- var dom_adapter_1 = __webpack_require__(178);
- var api_1 = __webpack_require__(72);
- var debug_element_1 = __webpack_require__(101);
- var NG_ID_PROPERTY = 'ngid';
- var INSPECT_GLOBAL_NAME = 'ng.probe';
- var NG_ID_SEPARATOR = '#';
- // Need to keep the views in a global Map so that multiple angular apps are supported
- var _allIdsByView = new collection_1.Map();
- var _allViewsById = new collection_1.Map();
- var _nextId = 0;
- function _setElementId(element, indices) {
- if (lang_1.isPresent(element) && dom_adapter_1.DOM.isElementNode(element)) {
- dom_adapter_1.DOM.setData(element, NG_ID_PROPERTY, indices.join(NG_ID_SEPARATOR));
- }
- }
- function _getElementId(element) {
- var elId = dom_adapter_1.DOM.getData(element, NG_ID_PROPERTY);
- if (lang_1.isPresent(elId)) {
- return elId.split(NG_ID_SEPARATOR).map(function (partStr) { return lang_1.NumberWrapper.parseInt(partStr, 10); });
- }
- else {
- return null;
- }
- }
- /**
- * Returns a {@link DebugElement} for the given native DOM element, or
- * null if the given native element does not have an Angular view associated
- * with it.
- */
- function inspectNativeElement(element) {
- var elId = _getElementId(element);
- if (lang_1.isPresent(elId)) {
- var view = _allViewsById.get(elId[0]);
- if (lang_1.isPresent(view)) {
- return new debug_element_1.DebugElement_(view, elId[1]);
- }
- }
- return null;
- }
- exports.inspectNativeElement = inspectNativeElement;
- var DebugElementViewListener = (function () {
- function DebugElementViewListener(_renderer) {
- this._renderer = _renderer;
- dom_adapter_1.DOM.setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
- }
- DebugElementViewListener.prototype.onViewCreated = function (view) {
- var viewId = _nextId++;
- _allViewsById.set(viewId, view);
- _allIdsByView.set(view, viewId);
- for (var i = 0; i < view.elementRefs.length; i++) {
- var el = view.elementRefs[i];
- _setElementId(this._renderer.getNativeElementSync(el), [viewId, i]);
- }
- };
- DebugElementViewListener.prototype.onViewDestroyed = function (view) {
- var viewId = _allIdsByView.get(view);
- _allIdsByView.delete(view);
- _allViewsById.delete(viewId);
- };
- DebugElementViewListener = __decorate([
- di_1.Injectable(),
- __metadata('design:paramtypes', [api_1.Renderer])
- ], DebugElementViewListener);
- return DebugElementViewListener;
- })();
- exports.DebugElementViewListener = DebugElementViewListener;
- /**
- * Providers which support debugging Angular applications (e.g. via `ng.probe`).
- *
- * ## Example
- *
- * {@example platform/dom/debug/ts/debug_element_view_listener/providers.ts region='providers'}
- */
- exports.ELEMENT_PROBE_PROVIDERS = lang_1.CONST_EXPR([
- DebugElementViewListener,
- lang_1.CONST_EXPR(new di_1.Provider(view_listener_1.AppViewListener, { useExisting: DebugElementViewListener })),
- ]);
- /**
- * Use {@link ELEMENT_PROBE_PROVIDERS}.
- *
- * @deprecated
- */
- exports.ELEMENT_PROBE_BINDINGS = exports.ELEMENT_PROBE_PROVIDERS;
- /***/ },
- /* 206 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var common_tools_1 = __webpack_require__(207);
- var context = lang_1.global;
- /**
- * Enabled Angular 2 debug tools that are accessible via your browser's
- * developer console.
- *
- * Usage:
- *
- * 1. Open developer console (e.g. in Chrome Ctrl + Shift + j)
- * 1. Type `ng.` (usually the console will show auto-complete suggestion)
- * 1. Try the change detection profiler `ng.profiler.timeChangeDetection()`
- * then hit Enter.
- */
- function enableDebugTools(ref) {
- context.ng = new common_tools_1.AngularTools(ref);
- }
- exports.enableDebugTools = enableDebugTools;
- /**
- * Disables Angular 2 tools.
- */
- function disableDebugTools() {
- delete context.ng;
- }
- exports.disableDebugTools = disableDebugTools;
- /***/ },
- /* 207 */
- /***/ function(module, exports, __webpack_require__) {
- var application_ref_1 = __webpack_require__(65);
- var lang_1 = __webpack_require__(5);
- var browser_1 = __webpack_require__(208);
- var dom_adapter_1 = __webpack_require__(178);
- /**
- * Entry point for all Angular debug tools. This object corresponds to the `ng`
- * global variable accessible in the dev console.
- */
- var AngularTools = (function () {
- function AngularTools(ref) {
- this.profiler = new AngularProfiler(ref);
- }
- return AngularTools;
- })();
- exports.AngularTools = AngularTools;
- /**
- * Entry point for all Angular profiling-related debug tools. This object
- * corresponds to the `ng.profiler` in the dev console.
- */
- var AngularProfiler = (function () {
- function AngularProfiler(ref) {
- this.appRef = ref.injector.get(application_ref_1.ApplicationRef);
- }
- /**
- * Exercises change detection in a loop and then prints the average amount of
- * time in milliseconds how long a single round of change detection takes for
- * the current state of the UI. It runs a minimum of 5 rounds for a minimum
- * of 500 milliseconds.
- *
- * Optionally, a user may pass a `config` parameter containing a map of
- * options. Supported options are:
- *
- * `record` (boolean) - causes the profiler to record a CPU profile while
- * it exercises the change detector. Example:
- *
- * ```
- * ng.profiler.timeChangeDetection({record: true})
- * ```
- */
- AngularProfiler.prototype.timeChangeDetection = function (config) {
- var record = lang_1.isPresent(config) && config['record'];
- var profileName = 'Change Detection';
- // Profiler is not available in Android browsers, nor in IE 9 without dev tools opened
- var isProfilerAvailable = lang_1.isPresent(browser_1.window.console.profile);
- if (record && isProfilerAvailable) {
- browser_1.window.console.profile(profileName);
- }
- var start = dom_adapter_1.DOM.performanceNow();
- var numTicks = 0;
- while (numTicks < 5 || (dom_adapter_1.DOM.performanceNow() - start) < 500) {
- this.appRef.tick();
- numTicks++;
- }
- var end = dom_adapter_1.DOM.performanceNow();
- if (record && isProfilerAvailable) {
- // need to cast to <any> because type checker thinks there's no argument
- // while in fact there is:
- //
- // https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd
- browser_1.window.console.profileEnd(profileName);
- }
- var msPerTick = (end - start) / numTicks;
- browser_1.window.console.log("ran " + numTicks + " change detection cycles");
- browser_1.window.console.log(lang_1.NumberWrapper.toFixed(msPerTick, 2) + " ms per check");
- };
- return AngularProfiler;
- })();
- exports.AngularProfiler = AngularProfiler;
- /***/ },
- /* 208 */
- /***/ function(module, exports) {
- /**
- * JS version of browser APIs. This library can only run in the browser.
- */
- var win = window;
- exports.window = win;
- exports.document = window.document;
- exports.location = window.location;
- exports.gc = window['gc'] ? function () { return window['gc'](); } : function () { return null; };
- exports.performance = window['performance'] ? window['performance'] : null;
- exports.Event = window['Event'];
- exports.MouseEvent = window['MouseEvent'];
- exports.KeyboardEvent = window['KeyboardEvent'];
- exports.EventTarget = window['EventTarget'];
- exports.History = window['History'];
- exports.Location = window['Location'];
- exports.EventListener = window['EventListener'];
- /***/ },
- /* 209 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * The http module provides services to perform http requests. To get started, see the {@link Http}
- * class.
- */
- var core_1 = __webpack_require__(2);
- var http_1 = __webpack_require__(210);
- var xhr_backend_1 = __webpack_require__(218);
- var jsonp_backend_1 = __webpack_require__(222);
- var browser_xhr_1 = __webpack_require__(221);
- var browser_jsonp_1 = __webpack_require__(223);
- var base_request_options_1 = __webpack_require__(216);
- var base_response_options_1 = __webpack_require__(220);
- var static_request_1 = __webpack_require__(212);
- exports.Request = static_request_1.Request;
- var static_response_1 = __webpack_require__(219);
- exports.Response = static_response_1.Response;
- var interfaces_1 = __webpack_require__(211);
- exports.Connection = interfaces_1.Connection;
- exports.ConnectionBackend = interfaces_1.ConnectionBackend;
- var browser_xhr_2 = __webpack_require__(221);
- exports.BrowserXhr = browser_xhr_2.BrowserXhr;
- var base_request_options_2 = __webpack_require__(216);
- exports.BaseRequestOptions = base_request_options_2.BaseRequestOptions;
- exports.RequestOptions = base_request_options_2.RequestOptions;
- var base_response_options_2 = __webpack_require__(220);
- exports.BaseResponseOptions = base_response_options_2.BaseResponseOptions;
- exports.ResponseOptions = base_response_options_2.ResponseOptions;
- var xhr_backend_2 = __webpack_require__(218);
- exports.XHRBackend = xhr_backend_2.XHRBackend;
- exports.XHRConnection = xhr_backend_2.XHRConnection;
- var jsonp_backend_2 = __webpack_require__(222);
- exports.JSONPBackend = jsonp_backend_2.JSONPBackend;
- exports.JSONPConnection = jsonp_backend_2.JSONPConnection;
- var http_2 = __webpack_require__(210);
- exports.Http = http_2.Http;
- exports.Jsonp = http_2.Jsonp;
- var headers_1 = __webpack_require__(213);
- exports.Headers = headers_1.Headers;
- var enums_1 = __webpack_require__(215);
- exports.ResponseType = enums_1.ResponseType;
- exports.ReadyState = enums_1.ReadyState;
- exports.RequestMethod = enums_1.RequestMethod;
- var url_search_params_1 = __webpack_require__(217);
- exports.URLSearchParams = url_search_params_1.URLSearchParams;
- /**
- * Provides a basic set of injectables to use the {@link Http} service in any application.
- *
- * The `HTTP_PROVIDERS` should be included either in a component's injector,
- * or in the root injector when bootstrapping an application.
- *
- * ### Example ([live demo](http://plnkr.co/edit/snj7Nv?p=preview))
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {NgFor} from 'angular2/common';
- * import {HTTP_PROVIDERS, Http} from 'angular2/http';
- *
- * @Component({
- * selector: 'app',
- * providers: [HTTP_PROVIDERS],
- * template: `
- * <div>
- * <h1>People</h1>
- * <ul>
- * <li *ngFor="#person of people">
- * {{person.name}}
- * </li>
- * </ul>
- * </div>
- * `,
- * directives: [NgFor]
- * })
- * export class App {
- * people: Object[];
- * constructor(http:Http) {
- * http.get('people.json').subscribe(res => {
- * this.people = res.json();
- * });
- * }
- * active:boolean = false;
- * toggleActiveState() {
- * this.active = !this.active;
- * }
- * }
- *
- * bootstrap(App)
- * .catch(err => console.error(err));
- * ```
- *
- * The primary public API included in `HTTP_PROVIDERS` is the {@link Http} class.
- * However, other providers required by `Http` are included,
- * which may be beneficial to override in certain cases.
- *
- * The providers included in `HTTP_PROVIDERS` include:
- * * {@link Http}
- * * {@link XHRBackend}
- * * `BrowserXHR` - Private factory to create `XMLHttpRequest` instances
- * * {@link RequestOptions} - Bound to {@link BaseRequestOptions} class
- * * {@link ResponseOptions} - Bound to {@link BaseResponseOptions} class
- *
- * There may be cases where it makes sense to extend the base request options,
- * such as to add a search string to be appended to all URLs.
- * To accomplish this, a new provider for {@link RequestOptions} should
- * be added in the same injector as `HTTP_PROVIDERS`.
- *
- * ### Example ([live demo](http://plnkr.co/edit/aCMEXi?p=preview))
- *
- * ```
- * import {provide} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {HTTP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
- *
- * class MyOptions extends BaseRequestOptions {
- * search: string = 'coreTeam=true';
- * }
- *
- * bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})])
- * .catch(err => console.error(err));
- * ```
- *
- * Likewise, to use a mock backend for unit tests, the {@link XHRBackend}
- * provider should be bound to {@link MockBackend}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/7LWALD?p=preview))
- *
- * ```
- * import {provide} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {HTTP_PROVIDERS, Http, Response, XHRBackend} from 'angular2/http';
- * import {MockBackend} from 'angular2/http/testing';
- *
- * var people = [{name: 'Jeff'}, {name: 'Tobias'}];
- *
- * var injector = Injector.resolveAndCreate([
- * HTTP_PROVIDERS,
- * MockBackend,
- * provide(XHRBackend, {useExisting: MockBackend})
- * ]);
- * var http = injector.get(Http);
- * var backend = injector.get(MockBackend);
- *
- * // Listen for any new requests
- * backend.connections.observer({
- * next: connection => {
- * var response = new Response({body: people});
- * setTimeout(() => {
- * // Send a response to the request
- * connection.mockRespond(response);
- * });
- * });
- *
- * http.get('people.json').observer({
- * next: res => {
- * // Response came from mock backend
- * console.log('first person', res.json()[0].name);
- * }
- * });
- * ```
- */
- exports.HTTP_PROVIDERS = [
- // TODO(pascal): use factory type annotations once supported in DI
- // issue: https://github.com/angular/angular/issues/3183
- core_1.provide(http_1.Http, {
- useFactory: function (xhrBackend, requestOptions) { return new http_1.Http(xhrBackend, requestOptions); },
- deps: [xhr_backend_1.XHRBackend, base_request_options_1.RequestOptions]
- }),
- browser_xhr_1.BrowserXhr,
- core_1.provide(base_request_options_1.RequestOptions, { useClass: base_request_options_1.BaseRequestOptions }),
- core_1.provide(base_response_options_1.ResponseOptions, { useClass: base_response_options_1.BaseResponseOptions }),
- xhr_backend_1.XHRBackend
- ];
- /**
- * See {@link HTTP_PROVIDERS} instead.
- *
- * @deprecated
- */
- exports.HTTP_BINDINGS = exports.HTTP_PROVIDERS;
- /**
- * Provides a basic set of providers to use the {@link Jsonp} service in any application.
- *
- * The `JSONP_PROVIDERS` should be included either in a component's injector,
- * or in the root injector when bootstrapping an application.
- *
- * ### Example ([live demo](http://plnkr.co/edit/vmeN4F?p=preview))
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {NgFor} from 'angular2/common';
- * import {JSONP_PROVIDERS, Jsonp} from 'angular2/http';
- *
- * @Component({
- * selector: 'app',
- * providers: [JSONP_PROVIDERS],
- * template: `
- * <div>
- * <h1>People</h1>
- * <ul>
- * <li *ngFor="#person of people">
- * {{person.name}}
- * </li>
- * </ul>
- * </div>
- * `,
- * directives: [NgFor]
- * })
- * export class App {
- * people: Array<Object>;
- * constructor(jsonp:Jsonp) {
- * jsonp.request('people.json').subscribe(res => {
- * this.people = res.json();
- * })
- * }
- * }
- * ```
- *
- * The primary public API included in `JSONP_PROVIDERS` is the {@link Jsonp} class.
- * However, other providers required by `Jsonp` are included,
- * which may be beneficial to override in certain cases.
- *
- * The providers included in `JSONP_PROVIDERS` include:
- * * {@link Jsonp}
- * * {@link JSONPBackend}
- * * `BrowserJsonp` - Private factory
- * * {@link RequestOptions} - Bound to {@link BaseRequestOptions} class
- * * {@link ResponseOptions} - Bound to {@link BaseResponseOptions} class
- *
- * There may be cases where it makes sense to extend the base request options,
- * such as to add a search string to be appended to all URLs.
- * To accomplish this, a new provider for {@link RequestOptions} should
- * be added in the same injector as `JSONP_PROVIDERS`.
- *
- * ### Example ([live demo](http://plnkr.co/edit/TFug7x?p=preview))
- *
- * ```
- * import {provide} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {JSONP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
- *
- * class MyOptions extends BaseRequestOptions {
- * search: string = 'coreTeam=true';
- * }
- *
- * bootstrap(App, [JSONP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})])
- * .catch(err => console.error(err));
- * ```
- *
- * Likewise, to use a mock backend for unit tests, the {@link JSONPBackend}
- * provider should be bound to {@link MockBackend}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/HDqZWL?p=preview))
- *
- * ```
- * import {provide, Injector} from 'angular2/core';
- * import {JSONP_PROVIDERS, Jsonp, Response, JSONPBackend} from 'angular2/http';
- * import {MockBackend} from 'angular2/http/testing';
- *
- * var people = [{name: 'Jeff'}, {name: 'Tobias'}];
- * var injector = Injector.resolveAndCreate([
- * JSONP_PROVIDERS,
- * MockBackend,
- * provide(JSONPBackend, {useExisting: MockBackend})
- * ]);
- * var jsonp = injector.get(Jsonp);
- * var backend = injector.get(MockBackend);
- *
- * // Listen for any new requests
- * backend.connections.observer({
- * next: connection => {
- * var response = new Response({body: people});
- * setTimeout(() => {
- * // Send a response to the request
- * connection.mockRespond(response);
- * });
- * });
- * jsonp.get('people.json').observer({
- * next: res => {
- * // Response came from mock backend
- * console.log('first person', res.json()[0].name);
- * }
- * });
- * ```
- */
- exports.JSONP_PROVIDERS = [
- // TODO(pascal): use factory type annotations once supported in DI
- // issue: https://github.com/angular/angular/issues/3183
- core_1.provide(http_1.Jsonp, {
- useFactory: function (jsonpBackend, requestOptions) { return new http_1.Jsonp(jsonpBackend, requestOptions); },
- deps: [jsonp_backend_1.JSONPBackend, base_request_options_1.RequestOptions]
- }),
- browser_jsonp_1.BrowserJsonp,
- core_1.provide(base_request_options_1.RequestOptions, { useClass: base_request_options_1.BaseRequestOptions }),
- core_1.provide(base_response_options_1.ResponseOptions, { useClass: base_response_options_1.BaseResponseOptions }),
- core_1.provide(jsonp_backend_1.JSONPBackend, { useClass: jsonp_backend_1.JSONPBackend_ })
- ];
- /**
- * See {@link JSONP_PROVIDERS} instead.
- *
- * @deprecated
- */
- exports.JSON_BINDINGS = exports.JSONP_PROVIDERS;
- /***/ },
- /* 210 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var core_1 = __webpack_require__(2);
- var interfaces_1 = __webpack_require__(211);
- var static_request_1 = __webpack_require__(212);
- var base_request_options_1 = __webpack_require__(216);
- var enums_1 = __webpack_require__(215);
- function httpRequest(backend, request) {
- return backend.createConnection(request).response;
- }
- function mergeOptions(defaultOpts, providedOpts, method, url) {
- var newOptions = defaultOpts;
- if (lang_1.isPresent(providedOpts)) {
- // Hack so Dart can used named parameters
- return newOptions.merge(new base_request_options_1.RequestOptions({
- method: providedOpts.method || method,
- url: providedOpts.url || url,
- search: providedOpts.search,
- headers: providedOpts.headers,
- body: providedOpts.body
- }));
- }
- if (lang_1.isPresent(method)) {
- return newOptions.merge(new base_request_options_1.RequestOptions({ method: method, url: url }));
- }
- else {
- return newOptions.merge(new base_request_options_1.RequestOptions({ url: url }));
- }
- }
- /**
- * Performs http requests using `XMLHttpRequest` as the default backend.
- *
- * `Http` is available as an injectable class, with methods to perform http requests. Calling
- * `request` returns an `Observable` which will emit a single {@link Response} when a
- * response is received.
- *
- * ### Example
- *
- * ```typescript
- * import {Http, HTTP_PROVIDERS} from 'angular2/http';
- * @Component({
- * selector: 'http-app',
- * viewProviders: [HTTP_PROVIDERS],
- * templateUrl: 'people.html'
- * })
- * class PeopleComponent {
- * constructor(http: Http) {
- * http.get('people.json')
- * // Call map on the response observable to get the parsed people object
- * .map(res => res.json())
- * // Subscribe to the observable to get the parsed people object and attach it to the
- * // component
- * .subscribe(people => this.people = people);
- * }
- * }
- * ```
- *
- *
- * ### Example
- *
- * ```
- * http.get('people.json').observer({next: (value) => this.people = value});
- * ```
- *
- * The default construct used to perform requests, `XMLHttpRequest`, is abstracted as a "Backend" (
- * {@link XHRBackend} in this case), which could be mocked with dependency injection by replacing
- * the {@link XHRBackend} provider, as in the following example:
- *
- * ### Example
- *
- * ```typescript
- * import {BaseRequestOptions, Http} from 'angular2/http';
- * import {MockBackend} from 'angular2/http/testing';
- * var injector = Injector.resolveAndCreate([
- * BaseRequestOptions,
- * MockBackend,
- * provide(Http, {useFactory:
- * function(backend, defaultOptions) {
- * return new Http(backend, defaultOptions);
- * },
- * deps: [MockBackend, BaseRequestOptions]})
- * ]);
- * var http = injector.get(Http);
- * http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));
- * ```
- *
- **/
- var Http = (function () {
- function Http(_backend, _defaultOptions) {
- this._backend = _backend;
- this._defaultOptions = _defaultOptions;
- }
- /**
- * Performs any type of http request. First argument is required, and can either be a url or
- * a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
- * object can be provided as the 2nd argument. The options object will be merged with the values
- * of {@link BaseRequestOptions} before performing the request.
- */
- Http.prototype.request = function (url, options) {
- var responseObservable;
- if (lang_1.isString(url)) {
- responseObservable = httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions, options, enums_1.RequestMethod.Get, url)));
- }
- else if (url instanceof static_request_1.Request) {
- responseObservable = httpRequest(this._backend, url);
- }
- else {
- throw exceptions_1.makeTypeError('First argument must be a url string or Request instance.');
- }
- return responseObservable;
- };
- /**
- * Performs a request with `get` http method.
- */
- Http.prototype.get = function (url, options) {
- return httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions, options, enums_1.RequestMethod.Get, url)));
- };
- /**
- * Performs a request with `post` http method.
- */
- Http.prototype.post = function (url, body, options) {
- return httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions.merge(new base_request_options_1.RequestOptions({ body: body })), options, enums_1.RequestMethod.Post, url)));
- };
- /**
- * Performs a request with `put` http method.
- */
- Http.prototype.put = function (url, body, options) {
- return httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions.merge(new base_request_options_1.RequestOptions({ body: body })), options, enums_1.RequestMethod.Put, url)));
- };
- /**
- * Performs a request with `delete` http method.
- */
- Http.prototype.delete = function (url, options) {
- return httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions, options, enums_1.RequestMethod.Delete, url)));
- };
- /**
- * Performs a request with `patch` http method.
- */
- Http.prototype.patch = function (url, body, options) {
- return httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions.merge(new base_request_options_1.RequestOptions({ body: body })), options, enums_1.RequestMethod.Patch, url)));
- };
- /**
- * Performs a request with `head` http method.
- */
- Http.prototype.head = function (url, options) {
- return httpRequest(this._backend, new static_request_1.Request(mergeOptions(this._defaultOptions, options, enums_1.RequestMethod.Head, url)));
- };
- Http = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [interfaces_1.ConnectionBackend, base_request_options_1.RequestOptions])
- ], Http);
- return Http;
- })();
- exports.Http = Http;
- var Jsonp = (function (_super) {
- __extends(Jsonp, _super);
- function Jsonp(backend, defaultOptions) {
- _super.call(this, backend, defaultOptions);
- }
- /**
- * Performs any type of http request. First argument is required, and can either be a url or
- * a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
- * object can be provided as the 2nd argument. The options object will be merged with the values
- * of {@link BaseRequestOptions} before performing the request.
- */
- Jsonp.prototype.request = function (url, options) {
- var responseObservable;
- if (lang_1.isString(url)) {
- url = new static_request_1.Request(mergeOptions(this._defaultOptions, options, enums_1.RequestMethod.Get, url));
- }
- if (url instanceof static_request_1.Request) {
- if (url.method !== enums_1.RequestMethod.Get) {
- exceptions_1.makeTypeError('JSONP requests must use GET request method.');
- }
- responseObservable = httpRequest(this._backend, url);
- }
- else {
- throw exceptions_1.makeTypeError('First argument must be a url string or Request instance.');
- }
- return responseObservable;
- };
- Jsonp = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [interfaces_1.ConnectionBackend, base_request_options_1.RequestOptions])
- ], Jsonp);
- return Jsonp;
- })(Http);
- exports.Jsonp = Jsonp;
- /***/ },
- /* 211 */
- /***/ function(module, exports) {
- /**
- * Abstract class from which real backends are derived.
- *
- * The primary purpose of a `ConnectionBackend` is to create new connections to fulfill a given
- * {@link Request}.
- */
- var ConnectionBackend = (function () {
- function ConnectionBackend() {
- }
- return ConnectionBackend;
- })();
- exports.ConnectionBackend = ConnectionBackend;
- /**
- * Abstract class from which real connections are derived.
- */
- var Connection = (function () {
- function Connection() {
- }
- return Connection;
- })();
- exports.Connection = Connection;
- /***/ },
- /* 212 */
- /***/ function(module, exports, __webpack_require__) {
- var headers_1 = __webpack_require__(213);
- var http_utils_1 = __webpack_require__(214);
- var lang_1 = __webpack_require__(5);
- // TODO(jeffbcross): properly implement body accessors
- /**
- * Creates `Request` instances from provided values.
- *
- * The Request's interface is inspired by the Request constructor defined in the [Fetch
- * Spec](https://fetch.spec.whatwg.org/#request-class),
- * but is considered a static value whose body can be accessed many times. There are other
- * differences in the implementation, but this is the most significant.
- *
- * `Request` instances are typically created by higher-level classes, like {@link Http} and
- * {@link Jsonp}, but it may occasionally be useful to explicitly create `Request` instances.
- * One such example is when creating services that wrap higher-level services, like {@link Http},
- * where it may be useful to generate a `Request` with arbitrary headers and search params.
- *
- * ```typescript
- * import {Injectable, Injector} from 'angular2/core';
- * import {HTTP_PROVIDERS, Http, Request, RequestMethod} from 'angular2/http';
- *
- * @Injectable()
- * class AutoAuthenticator {
- * constructor(public http:Http) {}
- * request(url:string) {
- * return this.http.request(new Request({
- * method: RequestMethod.Get,
- * url: url,
- * search: 'password=123'
- * }));
- * }
- * }
- *
- * var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, AutoAuthenticator]);
- * var authenticator = injector.get(AutoAuthenticator);
- * authenticator.request('people.json').subscribe(res => {
- * //URL should have included '?password=123'
- * console.log('people', res.json());
- * });
- * ```
- */
- var Request = (function () {
- function Request(requestOptions) {
- // TODO: assert that url is present
- var url = requestOptions.url;
- this.url = requestOptions.url;
- if (lang_1.isPresent(requestOptions.search)) {
- var search = requestOptions.search.toString();
- if (search.length > 0) {
- var prefix = '?';
- if (lang_1.StringWrapper.contains(this.url, '?')) {
- prefix = (this.url[this.url.length - 1] == '&') ? '' : '&';
- }
- // TODO: just delete search-query-looking string in url?
- this.url = url + prefix + search;
- }
- }
- this._body = requestOptions.body;
- this.method = http_utils_1.normalizeMethodName(requestOptions.method);
- // TODO(jeffbcross): implement behavior
- // Defaults to 'omit', consistent with browser
- // TODO(jeffbcross): implement behavior
- this.headers = new headers_1.Headers(requestOptions.headers);
- }
- /**
- * Returns the request's body as string, assuming that body exists. If body is undefined, return
- * empty
- * string.
- */
- Request.prototype.text = function () { return lang_1.isPresent(this._body) ? this._body.toString() : ''; };
- return Request;
- })();
- exports.Request = Request;
- /***/ },
- /* 213 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- /**
- * Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
- * specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class).
- *
- * The only known difference between this `Headers` implementation and the spec is the
- * lack of an `entries` method.
- *
- * ### Example ([live demo](http://plnkr.co/edit/MTdwT6?p=preview))
- *
- * ```
- * import {Headers} from 'angular2/http';
- *
- * var firstHeaders = new Headers();
- * firstHeaders.append('Content-Type', 'image/jpeg');
- * console.log(firstHeaders.get('Content-Type')) //'image/jpeg'
- *
- * // Create headers from Plain Old JavaScript Object
- * var secondHeaders = new Headers({
- * 'X-My-Custom-Header': 'Angular'
- * });
- * console.log(secondHeaders.get('X-My-Custom-Header')); //'Angular'
- *
- * var thirdHeaders = new Headers(secondHeaders);
- * console.log(thirdHeaders.get('X-My-Custom-Header')); //'Angular'
- * ```
- */
- var Headers = (function () {
- function Headers(headers) {
- var _this = this;
- if (headers instanceof Headers) {
- this._headersMap = headers._headersMap;
- return;
- }
- this._headersMap = new collection_1.Map();
- if (lang_1.isBlank(headers)) {
- return;
- }
- // headers instanceof StringMap
- collection_1.StringMapWrapper.forEach(headers, function (v, k) { _this._headersMap.set(k, collection_1.isListLikeIterable(v) ? v : [v]); });
- }
- /**
- * Returns a new Headers instance from the given DOMString of Response Headers
- */
- Headers.fromResponseHeaderString = function (headersString) {
- return headersString.trim()
- .split('\n')
- .map(function (val) { return val.split(':'); })
- .map(function (_a) {
- var key = _a[0], parts = _a.slice(1);
- return ([key.trim(), parts.join(':').trim()]);
- })
- .reduce(function (headers, _a) {
- var key = _a[0], value = _a[1];
- return !headers.set(key, value) && headers;
- }, new Headers());
- };
- /**
- * Appends a header to existing list of header values for a given header name.
- */
- Headers.prototype.append = function (name, value) {
- var mapName = this._headersMap.get(name);
- var list = collection_1.isListLikeIterable(mapName) ? mapName : [];
- list.push(value);
- this._headersMap.set(name, list);
- };
- /**
- * Deletes all header values for the given name.
- */
- Headers.prototype.delete = function (name) { this._headersMap.delete(name); };
- Headers.prototype.forEach = function (fn) {
- this._headersMap.forEach(fn);
- };
- /**
- * Returns first header that matches given name.
- */
- Headers.prototype.get = function (header) { return collection_1.ListWrapper.first(this._headersMap.get(header)); };
- /**
- * Check for existence of header by given name.
- */
- Headers.prototype.has = function (header) { return this._headersMap.has(header); };
- /**
- * Provides names of set headers
- */
- Headers.prototype.keys = function () { return collection_1.MapWrapper.keys(this._headersMap); };
- /**
- * Sets or overrides header value for given name.
- */
- Headers.prototype.set = function (header, value) {
- var list = [];
- if (collection_1.isListLikeIterable(value)) {
- var pushValue = value.join(',');
- list.push(pushValue);
- }
- else {
- list.push(value);
- }
- this._headersMap.set(header, list);
- };
- /**
- * Returns values of all headers.
- */
- Headers.prototype.values = function () { return collection_1.MapWrapper.values(this._headersMap); };
- /**
- * Returns string of all headers.
- */
- Headers.prototype.toJSON = function () { return lang_1.Json.stringify(this.values()); };
- /**
- * Returns list of header values for a given name.
- */
- Headers.prototype.getAll = function (header) {
- var headers = this._headersMap.get(header);
- return collection_1.isListLikeIterable(headers) ? headers : [];
- };
- /**
- * This method is not implemented.
- */
- Headers.prototype.entries = function () { throw new exceptions_1.BaseException('"entries" method is not implemented on Headers class'); };
- return Headers;
- })();
- exports.Headers = Headers;
- /***/ },
- /* 214 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var enums_1 = __webpack_require__(215);
- var exceptions_1 = __webpack_require__(14);
- function normalizeMethodName(method) {
- if (lang_1.isString(method)) {
- var originalMethod = method;
- method = method.replace(/(\w)(\w*)/g, function (g0, g1, g2) { return g1.toUpperCase() + g2.toLowerCase(); });
- method = enums_1.RequestMethod[method];
- if (typeof method !== 'number')
- throw exceptions_1.makeTypeError("Invalid request method. The method \"" + originalMethod + "\" is not supported.");
- }
- return method;
- }
- exports.normalizeMethodName = normalizeMethodName;
- exports.isSuccess = function (status) { return (status >= 200 && status < 300); };
- function getResponseURL(xhr) {
- if ('responseURL' in xhr) {
- return xhr.responseURL;
- }
- if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
- return xhr.getResponseHeader('X-Request-URL');
- }
- return;
- }
- exports.getResponseURL = getResponseURL;
- var lang_2 = __webpack_require__(5);
- exports.isJsObject = lang_2.isJsObject;
- /***/ },
- /* 215 */
- /***/ function(module, exports) {
- /**
- * Supported http methods.
- */
- (function (RequestMethod) {
- RequestMethod[RequestMethod["Get"] = 0] = "Get";
- RequestMethod[RequestMethod["Post"] = 1] = "Post";
- RequestMethod[RequestMethod["Put"] = 2] = "Put";
- RequestMethod[RequestMethod["Delete"] = 3] = "Delete";
- RequestMethod[RequestMethod["Options"] = 4] = "Options";
- RequestMethod[RequestMethod["Head"] = 5] = "Head";
- RequestMethod[RequestMethod["Patch"] = 6] = "Patch";
- })(exports.RequestMethod || (exports.RequestMethod = {}));
- var RequestMethod = exports.RequestMethod;
- /**
- * All possible states in which a connection can be, based on
- * [States](http://www.w3.org/TR/XMLHttpRequest/#states) from the `XMLHttpRequest` spec, but with an
- * additional "CANCELLED" state.
- */
- (function (ReadyState) {
- ReadyState[ReadyState["Unsent"] = 0] = "Unsent";
- ReadyState[ReadyState["Open"] = 1] = "Open";
- ReadyState[ReadyState["HeadersReceived"] = 2] = "HeadersReceived";
- ReadyState[ReadyState["Loading"] = 3] = "Loading";
- ReadyState[ReadyState["Done"] = 4] = "Done";
- ReadyState[ReadyState["Cancelled"] = 5] = "Cancelled";
- })(exports.ReadyState || (exports.ReadyState = {}));
- var ReadyState = exports.ReadyState;
- /**
- * Acceptable response types to be associated with a {@link Response}, based on
- * [ResponseType](https://fetch.spec.whatwg.org/#responsetype) from the Fetch spec.
- */
- (function (ResponseType) {
- ResponseType[ResponseType["Basic"] = 0] = "Basic";
- ResponseType[ResponseType["Cors"] = 1] = "Cors";
- ResponseType[ResponseType["Default"] = 2] = "Default";
- ResponseType[ResponseType["Error"] = 3] = "Error";
- ResponseType[ResponseType["Opaque"] = 4] = "Opaque";
- })(exports.ResponseType || (exports.ResponseType = {}));
- var ResponseType = exports.ResponseType;
- /***/ },
- /* 216 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var headers_1 = __webpack_require__(213);
- var enums_1 = __webpack_require__(215);
- var core_1 = __webpack_require__(2);
- var url_search_params_1 = __webpack_require__(217);
- var http_utils_1 = __webpack_require__(214);
- /**
- * Creates a request options object to be optionally provided when instantiating a
- * {@link Request}.
- *
- * This class is based on the `RequestInit` description in the [Fetch
- * Spec](https://fetch.spec.whatwg.org/#requestinit).
- *
- * All values are null by default. Typical defaults can be found in the {@link BaseRequestOptions}
- * class, which sub-classes `RequestOptions`.
- *
- * ### Example ([live demo](http://plnkr.co/edit/7Wvi3lfLq41aQPKlxB4O?p=preview))
- *
- * ```typescript
- * import {RequestOptions, Request, RequestMethod} from 'angular2/http';
- *
- * var options = new RequestOptions({
- * method: RequestMethod.Post,
- * url: 'https://google.com'
- * });
- * var req = new Request(options);
- * console.log('req.method:', RequestMethod[req.method]); // Post
- * console.log('options.url:', options.url); // https://google.com
- * ```
- */
- var RequestOptions = (function () {
- function RequestOptions(_a) {
- var _b = _a === void 0 ? {} : _a, method = _b.method, headers = _b.headers, body = _b.body, url = _b.url, search = _b.search;
- this.method = lang_1.isPresent(method) ? http_utils_1.normalizeMethodName(method) : null;
- this.headers = lang_1.isPresent(headers) ? headers : null;
- this.body = lang_1.isPresent(body) ? body : null;
- this.url = lang_1.isPresent(url) ? url : null;
- this.search = lang_1.isPresent(search) ? (lang_1.isString(search) ? new url_search_params_1.URLSearchParams((search)) :
- (search)) :
- null;
- }
- /**
- * Creates a copy of the `RequestOptions` instance, using the optional input as values to override
- * existing values. This method will not change the values of the instance on which it is being
- * called.
- *
- * Note that `headers` and `search` will override existing values completely if present in
- * the `options` object. If these values should be merged, it should be done prior to calling
- * `merge` on the `RequestOptions` instance.
- *
- * ### Example ([live demo](http://plnkr.co/edit/6w8XA8YTkDRcPYpdB9dk?p=preview))
- *
- * ```typescript
- * import {RequestOptions, Request, RequestMethod} from 'angular2/http';
- *
- * var options = new RequestOptions({
- * method: RequestMethod.Post
- * });
- * var req = new Request(options.merge({
- * url: 'https://google.com'
- * }));
- * console.log('req.method:', RequestMethod[req.method]); // Post
- * console.log('options.url:', options.url); // null
- * console.log('req.url:', req.url); // https://google.com
- * ```
- */
- RequestOptions.prototype.merge = function (options) {
- return new RequestOptions({
- method: lang_1.isPresent(options) && lang_1.isPresent(options.method) ? options.method : this.method,
- headers: lang_1.isPresent(options) && lang_1.isPresent(options.headers) ? options.headers : this.headers,
- body: lang_1.isPresent(options) && lang_1.isPresent(options.body) ? options.body : this.body,
- url: lang_1.isPresent(options) && lang_1.isPresent(options.url) ? options.url : this.url,
- search: lang_1.isPresent(options) && lang_1.isPresent(options.search) ?
- (lang_1.isString(options.search) ? new url_search_params_1.URLSearchParams((options.search)) :
- (options.search).clone()) :
- this.search
- });
- };
- return RequestOptions;
- })();
- exports.RequestOptions = RequestOptions;
- /**
- * Subclass of {@link RequestOptions}, with default values.
- *
- * Default values:
- * * method: {@link RequestMethod RequestMethod.Get}
- * * headers: empty {@link Headers} object
- *
- * This class could be extended and bound to the {@link RequestOptions} class
- * when configuring an {@link Injector}, in order to override the default options
- * used by {@link Http} to create and send {@link Request Requests}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/LEKVSx?p=preview))
- *
- * ```typescript
- * import {provide} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {HTTP_PROVIDERS, Http, BaseRequestOptions, RequestOptions} from 'angular2/http';
- * import {App} from './myapp';
- *
- * class MyOptions extends BaseRequestOptions {
- * search: string = 'coreTeam=true';
- * }
- *
- * bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})]);
- * ```
- *
- * The options could also be extended when manually creating a {@link Request}
- * object.
- *
- * ### Example ([live demo](http://plnkr.co/edit/oyBoEvNtDhOSfi9YxaVb?p=preview))
- *
- * ```
- * import {BaseRequestOptions, Request, RequestMethod} from 'angular2/http';
- *
- * var options = new BaseRequestOptions();
- * var req = new Request(options.merge({
- * method: RequestMethod.Post,
- * url: 'https://google.com'
- * }));
- * console.log('req.method:', RequestMethod[req.method]); // Post
- * console.log('options.url:', options.url); // null
- * console.log('req.url:', req.url); // https://google.com
- * ```
- */
- var BaseRequestOptions = (function (_super) {
- __extends(BaseRequestOptions, _super);
- function BaseRequestOptions() {
- _super.call(this, { method: enums_1.RequestMethod.Get, headers: new headers_1.Headers() });
- }
- BaseRequestOptions = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], BaseRequestOptions);
- return BaseRequestOptions;
- })(RequestOptions);
- exports.BaseRequestOptions = BaseRequestOptions;
- /***/ },
- /* 217 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var collection_1 = __webpack_require__(12);
- function paramParser(rawParams) {
- if (rawParams === void 0) { rawParams = ''; }
- var map = new collection_1.Map();
- if (rawParams.length > 0) {
- var params = rawParams.split('&');
- params.forEach(function (param) {
- var split = param.split('=');
- var key = split[0];
- var val = split[1];
- var list = lang_1.isPresent(map.get(key)) ? map.get(key) : [];
- list.push(val);
- map.set(key, list);
- });
- }
- return map;
- }
- /**
- * Map-like representation of url search parameters, based on
- * [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams) in the url living standard,
- * with several extensions for merging URLSearchParams objects:
- * - setAll()
- * - appendAll()
- * - replaceAll()
- */
- var URLSearchParams = (function () {
- function URLSearchParams(rawParams) {
- if (rawParams === void 0) { rawParams = ''; }
- this.rawParams = rawParams;
- this.paramsMap = paramParser(rawParams);
- }
- URLSearchParams.prototype.clone = function () {
- var clone = new URLSearchParams();
- clone.appendAll(this);
- return clone;
- };
- URLSearchParams.prototype.has = function (param) { return this.paramsMap.has(param); };
- URLSearchParams.prototype.get = function (param) {
- var storedParam = this.paramsMap.get(param);
- if (collection_1.isListLikeIterable(storedParam)) {
- return collection_1.ListWrapper.first(storedParam);
- }
- else {
- return null;
- }
- };
- URLSearchParams.prototype.getAll = function (param) {
- var mapParam = this.paramsMap.get(param);
- return lang_1.isPresent(mapParam) ? mapParam : [];
- };
- URLSearchParams.prototype.set = function (param, val) {
- var mapParam = this.paramsMap.get(param);
- var list = lang_1.isPresent(mapParam) ? mapParam : [];
- collection_1.ListWrapper.clear(list);
- list.push(val);
- this.paramsMap.set(param, list);
- };
- // A merge operation
- // For each name-values pair in `searchParams`, perform `set(name, values[0])`
- //
- // E.g: "a=[1,2,3], c=[8]" + "a=[4,5,6], b=[7]" = "a=[4], c=[8], b=[7]"
- //
- // TODO(@caitp): document this better
- URLSearchParams.prototype.setAll = function (searchParams) {
- var _this = this;
- searchParams.paramsMap.forEach(function (value, param) {
- var mapParam = _this.paramsMap.get(param);
- var list = lang_1.isPresent(mapParam) ? mapParam : [];
- collection_1.ListWrapper.clear(list);
- list.push(value[0]);
- _this.paramsMap.set(param, list);
- });
- };
- URLSearchParams.prototype.append = function (param, val) {
- var mapParam = this.paramsMap.get(param);
- var list = lang_1.isPresent(mapParam) ? mapParam : [];
- list.push(val);
- this.paramsMap.set(param, list);
- };
- // A merge operation
- // For each name-values pair in `searchParams`, perform `append(name, value)`
- // for each value in `values`.
- //
- // E.g: "a=[1,2], c=[8]" + "a=[3,4], b=[7]" = "a=[1,2,3,4], c=[8], b=[7]"
- //
- // TODO(@caitp): document this better
- URLSearchParams.prototype.appendAll = function (searchParams) {
- var _this = this;
- searchParams.paramsMap.forEach(function (value, param) {
- var mapParam = _this.paramsMap.get(param);
- var list = lang_1.isPresent(mapParam) ? mapParam : [];
- for (var i = 0; i < value.length; ++i) {
- list.push(value[i]);
- }
- _this.paramsMap.set(param, list);
- });
- };
- // A merge operation
- // For each name-values pair in `searchParams`, perform `delete(name)`,
- // followed by `set(name, values)`
- //
- // E.g: "a=[1,2,3], c=[8]" + "a=[4,5,6], b=[7]" = "a=[4,5,6], c=[8], b=[7]"
- //
- // TODO(@caitp): document this better
- URLSearchParams.prototype.replaceAll = function (searchParams) {
- var _this = this;
- searchParams.paramsMap.forEach(function (value, param) {
- var mapParam = _this.paramsMap.get(param);
- var list = lang_1.isPresent(mapParam) ? mapParam : [];
- collection_1.ListWrapper.clear(list);
- for (var i = 0; i < value.length; ++i) {
- list.push(value[i]);
- }
- _this.paramsMap.set(param, list);
- });
- };
- URLSearchParams.prototype.toString = function () {
- var paramsList = [];
- this.paramsMap.forEach(function (values, k) { values.forEach(function (v) { return paramsList.push(k + '=' + v); }); });
- return paramsList.join('&');
- };
- URLSearchParams.prototype.delete = function (param) { this.paramsMap.delete(param); };
- return URLSearchParams;
- })();
- exports.URLSearchParams = URLSearchParams;
- /***/ },
- /* 218 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var enums_1 = __webpack_require__(215);
- var static_response_1 = __webpack_require__(219);
- var headers_1 = __webpack_require__(213);
- var base_response_options_1 = __webpack_require__(220);
- var core_1 = __webpack_require__(2);
- var browser_xhr_1 = __webpack_require__(221);
- var lang_1 = __webpack_require__(5);
- var Observable_1 = __webpack_require__(62);
- var http_utils_1 = __webpack_require__(214);
- /**
- * Creates connections using `XMLHttpRequest`. Given a fully-qualified
- * request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
- * request.
- *
- * This class would typically not be created or interacted with directly inside applications, though
- * the {@link MockConnection} may be interacted with in tests.
- */
- var XHRConnection = (function () {
- function XHRConnection(req, browserXHR, baseResponseOptions) {
- var _this = this;
- this.request = req;
- this.response = new Observable_1.Observable(function (responseObserver) {
- var _xhr = browserXHR.build();
- _xhr.open(enums_1.RequestMethod[req.method].toUpperCase(), req.url);
- // load event handler
- var onLoad = function () {
- // responseText is the old-school way of retrieving response (supported by IE8 & 9)
- // response/responseType properties were introduced in XHR Level2 spec (supported by
- // IE10)
- var body = lang_1.isPresent(_xhr.response) ? _xhr.response : _xhr.responseText;
- var headers = headers_1.Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
- var url = http_utils_1.getResponseURL(_xhr);
- // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
- var status = _xhr.status === 1223 ? 204 : _xhr.status;
- // fix status code when it is 0 (0 status is undocumented).
- // Occurs when accessing file resources or on Android 4.1 stock browser
- // while retrieving files from application cache.
- if (status === 0) {
- status = body ? 200 : 0;
- }
- var responseOptions = new base_response_options_1.ResponseOptions({ body: body, status: status, headers: headers, url: url });
- if (lang_1.isPresent(baseResponseOptions)) {
- responseOptions = baseResponseOptions.merge(responseOptions);
- }
- var response = new static_response_1.Response(responseOptions);
- if (http_utils_1.isSuccess(status)) {
- responseObserver.next(response);
- // TODO(gdi2290): defer complete if array buffer until done
- responseObserver.complete();
- return;
- }
- responseObserver.error(response);
- };
- // error event handler
- var onError = function (err) {
- var responseOptions = new base_response_options_1.ResponseOptions({ body: err, type: enums_1.ResponseType.Error });
- if (lang_1.isPresent(baseResponseOptions)) {
- responseOptions = baseResponseOptions.merge(responseOptions);
- }
- responseObserver.error(new static_response_1.Response(responseOptions));
- };
- if (lang_1.isPresent(req.headers)) {
- req.headers.forEach(function (values, name) { return _xhr.setRequestHeader(name, values.join(',')); });
- }
- _xhr.addEventListener('load', onLoad);
- _xhr.addEventListener('error', onError);
- _xhr.send(_this.request.text());
- return function () {
- _xhr.removeEventListener('load', onLoad);
- _xhr.removeEventListener('error', onError);
- _xhr.abort();
- };
- });
- }
- return XHRConnection;
- })();
- exports.XHRConnection = XHRConnection;
- /**
- * Creates {@link XHRConnection} instances.
- *
- * This class would typically not be used by end users, but could be
- * overridden if a different backend implementation should be used,
- * such as in a node backend.
- *
- * ### Example
- *
- * ```
- * import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from 'angular2/http';
- * @Component({
- * viewProviders: [
- * HTTP_PROVIDERS,
- * provide(Http, {useFactory: (backend, options) => {
- * return new Http(backend, options);
- * }, deps: [MyNodeBackend, BaseRequestOptions]})]
- * })
- * class MyComponent {
- * constructor(http:Http) {
- * http.request('people.json').subscribe(res => this.people = res.json());
- * }
- * }
- * ```
- *
- **/
- var XHRBackend = (function () {
- function XHRBackend(_browserXHR, _baseResponseOptions) {
- this._browserXHR = _browserXHR;
- this._baseResponseOptions = _baseResponseOptions;
- }
- XHRBackend.prototype.createConnection = function (request) {
- return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
- };
- XHRBackend = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [browser_xhr_1.BrowserXhr, base_response_options_1.ResponseOptions])
- ], XHRBackend);
- return XHRBackend;
- })();
- exports.XHRBackend = XHRBackend;
- /***/ },
- /* 219 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var http_utils_1 = __webpack_require__(214);
- /**
- * Creates `Response` instances from provided values.
- *
- * Though this object isn't
- * usually instantiated by end-users, it is the primary object interacted with when it comes time to
- * add data to a view.
- *
- * ### Example
- *
- * ```
- * http.request('my-friends.txt').subscribe(response => this.friends = response.text());
- * ```
- *
- * The Response's interface is inspired by the Response constructor defined in the [Fetch
- * Spec](https://fetch.spec.whatwg.org/#response-class), but is considered a static value whose body
- * can be accessed many times. There are other differences in the implementation, but this is the
- * most significant.
- */
- var Response = (function () {
- function Response(responseOptions) {
- this._body = responseOptions.body;
- this.status = responseOptions.status;
- this.statusText = responseOptions.statusText;
- this.headers = responseOptions.headers;
- this.type = responseOptions.type;
- this.url = responseOptions.url;
- }
- /**
- * Not yet implemented
- */
- // TODO: Blob return type
- Response.prototype.blob = function () { throw new exceptions_1.BaseException('"blob()" method not implemented on Response superclass'); };
- /**
- * Attempts to return body as parsed `JSON` object, or raises an exception.
- */
- Response.prototype.json = function () {
- var jsonResponse;
- if (http_utils_1.isJsObject(this._body)) {
- jsonResponse = this._body;
- }
- else if (lang_1.isString(this._body)) {
- jsonResponse = lang_1.Json.parse(this._body);
- }
- return jsonResponse;
- };
- /**
- * Returns the body as a string, presuming `toString()` can be called on the response body.
- */
- Response.prototype.text = function () { return this._body.toString(); };
- /**
- * Not yet implemented
- */
- // TODO: ArrayBuffer return type
- Response.prototype.arrayBuffer = function () {
- throw new exceptions_1.BaseException('"arrayBuffer()" method not implemented on Response superclass');
- };
- return Response;
- })();
- exports.Response = Response;
- /***/ },
- /* 220 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var headers_1 = __webpack_require__(213);
- var enums_1 = __webpack_require__(215);
- /**
- * Creates a response options object to be optionally provided when instantiating a
- * {@link Response}.
- *
- * This class is based on the `ResponseInit` description in the [Fetch
- * Spec](https://fetch.spec.whatwg.org/#responseinit).
- *
- * All values are null by default. Typical defaults can be found in the
- * {@link BaseResponseOptions} class, which sub-classes `ResponseOptions`.
- *
- * This class may be used in tests to build {@link Response Responses} for
- * mock responses (see {@link MockBackend}).
- *
- * ### Example ([live demo](http://plnkr.co/edit/P9Jkk8e8cz6NVzbcxEsD?p=preview))
- *
- * ```typescript
- * import {ResponseOptions, Response} from 'angular2/http';
- *
- * var options = new ResponseOptions({
- * body: '{"name":"Jeff"}'
- * });
- * var res = new Response(options);
- *
- * console.log('res.json():', res.json()); // Object {name: "Jeff"}
- * ```
- */
- var ResponseOptions = (function () {
- function ResponseOptions(_a) {
- var _b = _a === void 0 ? {} : _a, body = _b.body, status = _b.status, headers = _b.headers, statusText = _b.statusText, type = _b.type, url = _b.url;
- this.body = lang_1.isPresent(body) ? body : null;
- this.status = lang_1.isPresent(status) ? status : null;
- this.headers = lang_1.isPresent(headers) ? headers : null;
- this.statusText = lang_1.isPresent(statusText) ? statusText : null;
- this.type = lang_1.isPresent(type) ? type : null;
- this.url = lang_1.isPresent(url) ? url : null;
- }
- /**
- * Creates a copy of the `ResponseOptions` instance, using the optional input as values to
- * override
- * existing values. This method will not change the values of the instance on which it is being
- * called.
- *
- * This may be useful when sharing a base `ResponseOptions` object inside tests,
- * where certain properties may change from test to test.
- *
- * ### Example ([live demo](http://plnkr.co/edit/1lXquqFfgduTFBWjNoRE?p=preview))
- *
- * ```typescript
- * import {ResponseOptions, Response} from 'angular2/http';
- *
- * var options = new ResponseOptions({
- * body: {name: 'Jeff'}
- * });
- * var res = new Response(options.merge({
- * url: 'https://google.com'
- * }));
- * console.log('options.url:', options.url); // null
- * console.log('res.json():', res.json()); // Object {name: "Jeff"}
- * console.log('res.url:', res.url); // https://google.com
- * ```
- */
- ResponseOptions.prototype.merge = function (options) {
- return new ResponseOptions({
- body: lang_1.isPresent(options) && lang_1.isPresent(options.body) ? options.body : this.body,
- status: lang_1.isPresent(options) && lang_1.isPresent(options.status) ? options.status : this.status,
- headers: lang_1.isPresent(options) && lang_1.isPresent(options.headers) ? options.headers : this.headers,
- statusText: lang_1.isPresent(options) && lang_1.isPresent(options.statusText) ? options.statusText :
- this.statusText,
- type: lang_1.isPresent(options) && lang_1.isPresent(options.type) ? options.type : this.type,
- url: lang_1.isPresent(options) && lang_1.isPresent(options.url) ? options.url : this.url,
- });
- };
- return ResponseOptions;
- })();
- exports.ResponseOptions = ResponseOptions;
- /**
- * Subclass of {@link ResponseOptions}, with default values.
- *
- * Default values:
- * * status: 200
- * * headers: empty {@link Headers} object
- *
- * This class could be extended and bound to the {@link ResponseOptions} class
- * when configuring an {@link Injector}, in order to override the default options
- * used by {@link Http} to create {@link Response Responses}.
- *
- * ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
- *
- * ```typescript
- * import {provide} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {HTTP_PROVIDERS, Headers, Http, BaseResponseOptions, ResponseOptions} from
- * 'angular2/http';
- * import {App} from './myapp';
- *
- * class MyOptions extends BaseResponseOptions {
- * headers:Headers = new Headers({network: 'github'});
- * }
- *
- * bootstrap(App, [HTTP_PROVIDERS, provide(ResponseOptions, {useClass: MyOptions})]);
- * ```
- *
- * The options could also be extended when manually creating a {@link Response}
- * object.
- *
- * ### Example ([live demo](http://plnkr.co/edit/VngosOWiaExEtbstDoix?p=preview))
- *
- * ```
- * import {BaseResponseOptions, Response} from 'angular2/http';
- *
- * var options = new BaseResponseOptions();
- * var res = new Response(options.merge({
- * body: 'Angular2',
- * headers: new Headers({framework: 'angular'})
- * }));
- * console.log('res.headers.get("framework"):', res.headers.get('framework')); // angular
- * console.log('res.text():', res.text()); // Angular2;
- * ```
- */
- var BaseResponseOptions = (function (_super) {
- __extends(BaseResponseOptions, _super);
- function BaseResponseOptions() {
- _super.call(this, { status: 200, statusText: 'Ok', type: enums_1.ResponseType.Default, headers: new headers_1.Headers() });
- }
- BaseResponseOptions = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], BaseResponseOptions);
- return BaseResponseOptions;
- })(ResponseOptions);
- exports.BaseResponseOptions = BaseResponseOptions;
- /***/ },
- /* 221 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- /**
- * A backend for http that uses the `XMLHttpRequest` browser API.
- *
- * Take care not to evaluate this in non-browser contexts.
- */
- var BrowserXhr = (function () {
- function BrowserXhr() {
- }
- BrowserXhr.prototype.build = function () { return (new XMLHttpRequest()); };
- BrowserXhr = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], BrowserXhr);
- return BrowserXhr;
- })();
- exports.BrowserXhr = BrowserXhr;
- /***/ },
- /* 222 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var interfaces_1 = __webpack_require__(211);
- var enums_1 = __webpack_require__(215);
- var static_response_1 = __webpack_require__(219);
- var base_response_options_1 = __webpack_require__(220);
- var core_1 = __webpack_require__(2);
- var browser_jsonp_1 = __webpack_require__(223);
- var exceptions_1 = __webpack_require__(14);
- var lang_1 = __webpack_require__(5);
- var Observable_1 = __webpack_require__(62);
- var JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
- var JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';
- /**
- * Abstract base class for an in-flight JSONP request.
- */
- var JSONPConnection = (function () {
- function JSONPConnection() {
- }
- return JSONPConnection;
- })();
- exports.JSONPConnection = JSONPConnection;
- var JSONPConnection_ = (function (_super) {
- __extends(JSONPConnection_, _super);
- function JSONPConnection_(req, _dom, baseResponseOptions) {
- var _this = this;
- _super.call(this);
- this._dom = _dom;
- this.baseResponseOptions = baseResponseOptions;
- this._finished = false;
- if (req.method !== enums_1.RequestMethod.Get) {
- throw exceptions_1.makeTypeError(JSONP_ERR_WRONG_METHOD);
- }
- this.request = req;
- this.response = new Observable_1.Observable(function (responseObserver) {
- _this.readyState = enums_1.ReadyState.Loading;
- var id = _this._id = _dom.nextRequestID();
- _dom.exposeConnection(id, _this);
- // Workaround Dart
- // url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
- var callback = _dom.requestCallback(_this._id);
- var url = req.url;
- if (url.indexOf('=JSONP_CALLBACK&') > -1) {
- url = lang_1.StringWrapper.replace(url, '=JSONP_CALLBACK&', "=" + callback + "&");
- }
- else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
- url = url.substring(0, url.length - '=JSONP_CALLBACK'.length) + ("=" + callback);
- }
- var script = _this._script = _dom.build(url);
- var onLoad = function (event) {
- if (_this.readyState === enums_1.ReadyState.Cancelled)
- return;
- _this.readyState = enums_1.ReadyState.Done;
- _dom.cleanup(script);
- if (!_this._finished) {
- var responseOptions_1 = new base_response_options_1.ResponseOptions({ body: JSONP_ERR_NO_CALLBACK, type: enums_1.ResponseType.Error, url: url });
- if (lang_1.isPresent(baseResponseOptions)) {
- responseOptions_1 = baseResponseOptions.merge(responseOptions_1);
- }
- responseObserver.error(new static_response_1.Response(responseOptions_1));
- return;
- }
- var responseOptions = new base_response_options_1.ResponseOptions({ body: _this._responseData, url: url });
- if (lang_1.isPresent(_this.baseResponseOptions)) {
- responseOptions = _this.baseResponseOptions.merge(responseOptions);
- }
- responseObserver.next(new static_response_1.Response(responseOptions));
- responseObserver.complete();
- };
- var onError = function (error) {
- if (_this.readyState === enums_1.ReadyState.Cancelled)
- return;
- _this.readyState = enums_1.ReadyState.Done;
- _dom.cleanup(script);
- var responseOptions = new base_response_options_1.ResponseOptions({ body: error.message, type: enums_1.ResponseType.Error });
- if (lang_1.isPresent(baseResponseOptions)) {
- responseOptions = baseResponseOptions.merge(responseOptions);
- }
- responseObserver.error(new static_response_1.Response(responseOptions));
- };
- script.addEventListener('load', onLoad);
- script.addEventListener('error', onError);
- _dom.send(script);
- return function () {
- _this.readyState = enums_1.ReadyState.Cancelled;
- script.removeEventListener('load', onLoad);
- script.removeEventListener('error', onError);
- if (lang_1.isPresent(script)) {
- _this._dom.cleanup(script);
- }
- };
- });
- }
- JSONPConnection_.prototype.finished = function (data) {
- // Don't leak connections
- this._finished = true;
- this._dom.removeConnection(this._id);
- if (this.readyState === enums_1.ReadyState.Cancelled)
- return;
- this._responseData = data;
- };
- return JSONPConnection_;
- })(JSONPConnection);
- exports.JSONPConnection_ = JSONPConnection_;
- /**
- * A {@link ConnectionBackend} that uses the JSONP strategy of making requests.
- */
- var JSONPBackend = (function (_super) {
- __extends(JSONPBackend, _super);
- function JSONPBackend() {
- _super.apply(this, arguments);
- }
- return JSONPBackend;
- })(interfaces_1.ConnectionBackend);
- exports.JSONPBackend = JSONPBackend;
- var JSONPBackend_ = (function (_super) {
- __extends(JSONPBackend_, _super);
- function JSONPBackend_(_browserJSONP, _baseResponseOptions) {
- _super.call(this);
- this._browserJSONP = _browserJSONP;
- this._baseResponseOptions = _baseResponseOptions;
- }
- JSONPBackend_.prototype.createConnection = function (request) {
- return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
- };
- JSONPBackend_ = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [browser_jsonp_1.BrowserJsonp, base_response_options_1.ResponseOptions])
- ], JSONPBackend_);
- return JSONPBackend_;
- })(JSONPBackend);
- exports.JSONPBackend_ = JSONPBackend_;
- /***/ },
- /* 223 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var _nextRequestId = 0;
- exports.JSONP_HOME = '__ng_jsonp__';
- var _jsonpConnections = null;
- function _getJsonpConnections() {
- if (_jsonpConnections === null) {
- _jsonpConnections = lang_1.global[exports.JSONP_HOME] = {};
- }
- return _jsonpConnections;
- }
- // Make sure not to evaluate this in a non-browser environment!
- var BrowserJsonp = (function () {
- function BrowserJsonp() {
- }
- // Construct a <script> element with the specified URL
- BrowserJsonp.prototype.build = function (url) {
- var node = document.createElement('script');
- node.src = url;
- return node;
- };
- BrowserJsonp.prototype.nextRequestID = function () { return "__req" + _nextRequestId++; };
- BrowserJsonp.prototype.requestCallback = function (id) { return exports.JSONP_HOME + "." + id + ".finished"; };
- BrowserJsonp.prototype.exposeConnection = function (id, connection) {
- var connections = _getJsonpConnections();
- connections[id] = connection;
- };
- BrowserJsonp.prototype.removeConnection = function (id) {
- var connections = _getJsonpConnections();
- connections[id] = null;
- };
- // Attach the <script> element to the DOM
- BrowserJsonp.prototype.send = function (node) { document.body.appendChild((node)); };
- // Remove <script> element from the DOM
- BrowserJsonp.prototype.cleanup = function (node) {
- if (node.parentNode) {
- node.parentNode.removeChild((node));
- }
- };
- BrowserJsonp = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], BrowserJsonp);
- return BrowserJsonp;
- })();
- exports.BrowserJsonp = BrowserJsonp;
- /***/ },
- /* 224 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * Maps application URLs into application states, to support deep-linking and navigation.
- */
- function __export(m) {
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- var router_1 = __webpack_require__(225);
- exports.Router = router_1.Router;
- var router_outlet_1 = __webpack_require__(241);
- exports.RouterOutlet = router_outlet_1.RouterOutlet;
- var router_link_1 = __webpack_require__(243);
- exports.RouterLink = router_link_1.RouterLink;
- var instruction_1 = __webpack_require__(229);
- exports.RouteParams = instruction_1.RouteParams;
- exports.RouteData = instruction_1.RouteData;
- var platform_location_1 = __webpack_require__(244);
- exports.PlatformLocation = platform_location_1.PlatformLocation;
- var route_registry_1 = __webpack_require__(226);
- exports.RouteRegistry = route_registry_1.RouteRegistry;
- exports.ROUTER_PRIMARY_COMPONENT = route_registry_1.ROUTER_PRIMARY_COMPONENT;
- var location_strategy_1 = __webpack_require__(238);
- exports.LocationStrategy = location_strategy_1.LocationStrategy;
- exports.APP_BASE_HREF = location_strategy_1.APP_BASE_HREF;
- var hash_location_strategy_1 = __webpack_require__(245);
- exports.HashLocationStrategy = hash_location_strategy_1.HashLocationStrategy;
- var path_location_strategy_1 = __webpack_require__(246);
- exports.PathLocationStrategy = path_location_strategy_1.PathLocationStrategy;
- var location_1 = __webpack_require__(237);
- exports.Location = location_1.Location;
- __export(__webpack_require__(236));
- __export(__webpack_require__(247));
- var lifecycle_annotations_1 = __webpack_require__(242);
- exports.CanActivate = lifecycle_annotations_1.CanActivate;
- var instruction_2 = __webpack_require__(229);
- exports.Instruction = instruction_2.Instruction;
- exports.ComponentInstruction = instruction_2.ComponentInstruction;
- var core_1 = __webpack_require__(2);
- exports.OpaqueToken = core_1.OpaqueToken;
- var platform_location_2 = __webpack_require__(244);
- var location_strategy_2 = __webpack_require__(238);
- var path_location_strategy_2 = __webpack_require__(246);
- var router_2 = __webpack_require__(225);
- var router_outlet_2 = __webpack_require__(241);
- var router_link_2 = __webpack_require__(243);
- var route_registry_2 = __webpack_require__(226);
- var location_2 = __webpack_require__(237);
- var core_2 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- /**
- * A list of directives. To use the router directives like {@link RouterOutlet} and
- * {@link RouterLink}, add this to your `directives` array in the {@link View} decorator of your
- * component.
- *
- * ### Example ([live demo](http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm))
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * // ...
- * }
- *
- * bootstrap(AppCmp, [ROUTER_PROVIDERS]);
- * ```
- */
- exports.ROUTER_DIRECTIVES = lang_1.CONST_EXPR([router_outlet_2.RouterOutlet, router_link_2.RouterLink]);
- /**
- * A list of {@link Provider}s. To use the router, you must add this to your application.
- *
- * ### Example ([live demo](http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm))
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {
- * ROUTER_DIRECTIVES,
- * ROUTER_PROVIDERS,
- * RouteConfig
- * } from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * // ...
- * }
- *
- * bootstrap(AppCmp, [ROUTER_PROVIDERS]);
- * ```
- */
- exports.ROUTER_PROVIDERS = lang_1.CONST_EXPR([
- route_registry_2.RouteRegistry,
- lang_1.CONST_EXPR(new core_2.Provider(location_strategy_2.LocationStrategy, { useClass: path_location_strategy_2.PathLocationStrategy })),
- platform_location_2.PlatformLocation,
- location_2.Location,
- lang_1.CONST_EXPR(new core_2.Provider(router_2.Router, {
- useFactory: routerFactory,
- deps: lang_1.CONST_EXPR([route_registry_2.RouteRegistry, location_2.Location, route_registry_2.ROUTER_PRIMARY_COMPONENT, core_2.ApplicationRef])
- })),
- lang_1.CONST_EXPR(new core_2.Provider(route_registry_2.ROUTER_PRIMARY_COMPONENT, { useFactory: routerPrimaryComponentFactory, deps: lang_1.CONST_EXPR([core_2.ApplicationRef]) }))
- ]);
- /**
- * Use {@link ROUTER_PROVIDERS} instead.
- *
- * @deprecated
- */
- exports.ROUTER_BINDINGS = exports.ROUTER_PROVIDERS;
- function routerFactory(registry, location, primaryComponent, appRef) {
- var rootRouter = new router_2.RootRouter(registry, location, primaryComponent);
- appRef.registerDisposeListener(function () { return rootRouter.dispose(); });
- return rootRouter;
- }
- function routerPrimaryComponentFactory(app) {
- if (app.componentTypes.length == 0) {
- throw new exceptions_1.BaseException("Bootstrap at least one component before injecting Router.");
- }
- return app.componentTypes[0];
- }
- /***/ },
- /* 225 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var async_1 = __webpack_require__(60);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var core_1 = __webpack_require__(2);
- var route_registry_1 = __webpack_require__(226);
- var location_1 = __webpack_require__(237);
- var route_lifecycle_reflector_1 = __webpack_require__(239);
- var _resolveToTrue = async_1.PromiseWrapper.resolve(true);
- var _resolveToFalse = async_1.PromiseWrapper.resolve(false);
- /**
- * The `Router` is responsible for mapping URLs to components.
- *
- * You can see the state of the router by inspecting the read-only field `router.navigating`.
- * This may be useful for showing a spinner, for instance.
- *
- * ## Concepts
- *
- * Routers and component instances have a 1:1 correspondence.
- *
- * The router holds reference to a number of {@link RouterOutlet}.
- * An outlet is a placeholder that the router dynamically fills in depending on the current URL.
- *
- * When the router navigates from a URL, it must first recognize it and serialize it into an
- * `Instruction`.
- * The router uses the `RouteRegistry` to get an `Instruction`.
- */
- var Router = (function () {
- function Router(registry, parent, hostComponent) {
- this.registry = registry;
- this.parent = parent;
- this.hostComponent = hostComponent;
- this.navigating = false;
- this._currentInstruction = null;
- this._currentNavigation = _resolveToTrue;
- this._outlet = null;
- this._auxRouters = new collection_1.Map();
- this._subject = new async_1.EventEmitter();
- }
- /**
- * Constructs a child router. You probably don't need to use this unless you're writing a reusable
- * component.
- */
- Router.prototype.childRouter = function (hostComponent) {
- return this._childRouter = new ChildRouter(this, hostComponent);
- };
- /**
- * Constructs a child router. You probably don't need to use this unless you're writing a reusable
- * component.
- */
- Router.prototype.auxRouter = function (hostComponent) { return new ChildRouter(this, hostComponent); };
- /**
- * Register an outlet to be notified of primary route changes.
- *
- * You probably don't need to use this unless you're writing a reusable component.
- */
- Router.prototype.registerPrimaryOutlet = function (outlet) {
- if (lang_1.isPresent(outlet.name)) {
- throw new exceptions_1.BaseException("registerPrimaryOutlet expects to be called with an unnamed outlet.");
- }
- this._outlet = outlet;
- if (lang_1.isPresent(this._currentInstruction)) {
- return this.commit(this._currentInstruction, false);
- }
- return _resolveToTrue;
- };
- /**
- * Register an outlet to notified of auxiliary route changes.
- *
- * You probably don't need to use this unless you're writing a reusable component.
- */
- Router.prototype.registerAuxOutlet = function (outlet) {
- var outletName = outlet.name;
- if (lang_1.isBlank(outletName)) {
- throw new exceptions_1.BaseException("registerAuxOutlet expects to be called with an outlet with a name.");
- }
- // TODO...
- // what is the host of an aux route???
- var router = this.auxRouter(this.hostComponent);
- this._auxRouters.set(outletName, router);
- router._outlet = outlet;
- var auxInstruction;
- if (lang_1.isPresent(this._currentInstruction) &&
- lang_1.isPresent(auxInstruction = this._currentInstruction.auxInstruction[outletName])) {
- return router.commit(auxInstruction);
- }
- return _resolveToTrue;
- };
- /**
- * Given an instruction, returns `true` if the instruction is currently active,
- * otherwise `false`.
- */
- Router.prototype.isRouteActive = function (instruction) {
- var router = this;
- while (lang_1.isPresent(router.parent) && lang_1.isPresent(instruction.child)) {
- router = router.parent;
- instruction = instruction.child;
- }
- return lang_1.isPresent(this._currentInstruction) &&
- this._currentInstruction.component == instruction.component;
- };
- /**
- * Dynamically update the routing configuration and trigger a navigation.
- *
- * ### Usage
- *
- * ```
- * router.config([
- * { 'path': '/', 'component': IndexComp },
- * { 'path': '/user/:id', 'component': UserComp },
- * ]);
- * ```
- */
- Router.prototype.config = function (definitions) {
- var _this = this;
- definitions.forEach(function (routeDefinition) { _this.registry.config(_this.hostComponent, routeDefinition); });
- return this.renavigate();
- };
- /**
- * Navigate based on the provided Route Link DSL. It's preferred to navigate with this method
- * over `navigateByUrl`.
- *
- * ### Usage
- *
- * This method takes an array representing the Route Link DSL:
- * ```
- * ['./MyCmp', {param: 3}]
- * ```
- * See the {@link RouterLink} directive for more.
- */
- Router.prototype.navigate = function (linkParams) {
- var instruction = this.generate(linkParams);
- return this.navigateByInstruction(instruction, false);
- };
- /**
- * Navigate to a URL. Returns a promise that resolves when navigation is complete.
- * It's preferred to navigate with `navigate` instead of this method, since URLs are more brittle.
- *
- * If the given URL begins with a `/`, router will navigate absolutely.
- * If the given URL does not begin with `/`, the router will navigate relative to this component.
- */
- Router.prototype.navigateByUrl = function (url, _skipLocationChange) {
- var _this = this;
- if (_skipLocationChange === void 0) { _skipLocationChange = false; }
- return this._currentNavigation = this._currentNavigation.then(function (_) {
- _this.lastNavigationAttempt = url;
- _this._startNavigating();
- return _this._afterPromiseFinishNavigating(_this.recognize(url).then(function (instruction) {
- if (lang_1.isBlank(instruction)) {
- return false;
- }
- return _this._navigate(instruction, _skipLocationChange);
- }));
- });
- };
- /**
- * Navigate via the provided instruction. Returns a promise that resolves when navigation is
- * complete.
- */
- Router.prototype.navigateByInstruction = function (instruction, _skipLocationChange) {
- var _this = this;
- if (_skipLocationChange === void 0) { _skipLocationChange = false; }
- if (lang_1.isBlank(instruction)) {
- return _resolveToFalse;
- }
- return this._currentNavigation = this._currentNavigation.then(function (_) {
- _this._startNavigating();
- return _this._afterPromiseFinishNavigating(_this._navigate(instruction, _skipLocationChange));
- });
- };
- /** @internal */
- Router.prototype._navigate = function (instruction, _skipLocationChange) {
- var _this = this;
- return this._settleInstruction(instruction)
- .then(function (_) { return _this._routerCanReuse(instruction); })
- .then(function (_) { return _this._canActivate(instruction); })
- .then(function (result) {
- if (!result) {
- return false;
- }
- return _this._routerCanDeactivate(instruction)
- .then(function (result) {
- if (result) {
- return _this.commit(instruction, _skipLocationChange)
- .then(function (_) {
- _this._emitNavigationFinish(instruction.toRootUrl());
- return true;
- });
- }
- });
- });
- };
- /** @internal */
- Router.prototype._settleInstruction = function (instruction) {
- var _this = this;
- return instruction.resolveComponent().then(function (_) {
- instruction.component.reuse = false;
- var unsettledInstructions = [];
- if (lang_1.isPresent(instruction.child)) {
- unsettledInstructions.push(_this._settleInstruction(instruction.child));
- }
- collection_1.StringMapWrapper.forEach(instruction.auxInstruction, function (instruction, _) {
- unsettledInstructions.push(_this._settleInstruction(instruction));
- });
- return async_1.PromiseWrapper.all(unsettledInstructions);
- });
- };
- Router.prototype._emitNavigationFinish = function (url) { async_1.ObservableWrapper.callEmit(this._subject, url); };
- Router.prototype._afterPromiseFinishNavigating = function (promise) {
- var _this = this;
- return async_1.PromiseWrapper.catchError(promise.then(function (_) { return _this._finishNavigating(); }), function (err) {
- _this._finishNavigating();
- throw err;
- });
- };
- /*
- * Recursively set reuse flags
- */
- /** @internal */
- Router.prototype._routerCanReuse = function (instruction) {
- var _this = this;
- if (lang_1.isBlank(this._outlet)) {
- return _resolveToFalse;
- }
- return this._outlet.routerCanReuse(instruction.component)
- .then(function (result) {
- instruction.component.reuse = result;
- if (result && lang_1.isPresent(_this._childRouter) && lang_1.isPresent(instruction.child)) {
- return _this._childRouter._routerCanReuse(instruction.child);
- }
- });
- };
- Router.prototype._canActivate = function (nextInstruction) {
- return canActivateOne(nextInstruction, this._currentInstruction);
- };
- Router.prototype._routerCanDeactivate = function (instruction) {
- var _this = this;
- if (lang_1.isBlank(this._outlet)) {
- return _resolveToTrue;
- }
- var next;
- var childInstruction = null;
- var reuse = false;
- var componentInstruction = null;
- if (lang_1.isPresent(instruction)) {
- childInstruction = instruction.child;
- componentInstruction = instruction.component;
- reuse = instruction.component.reuse;
- }
- if (reuse) {
- next = _resolveToTrue;
- }
- else {
- next = this._outlet.routerCanDeactivate(componentInstruction);
- }
- // TODO: aux route lifecycle hooks
- return next.then(function (result) {
- if (result == false) {
- return false;
- }
- if (lang_1.isPresent(_this._childRouter)) {
- return _this._childRouter._routerCanDeactivate(childInstruction);
- }
- return true;
- });
- };
- /**
- * Updates this router and all descendant routers according to the given instruction
- */
- Router.prototype.commit = function (instruction, _skipLocationChange) {
- var _this = this;
- if (_skipLocationChange === void 0) { _skipLocationChange = false; }
- this._currentInstruction = instruction;
- var next = _resolveToTrue;
- if (lang_1.isPresent(this._outlet)) {
- var componentInstruction = instruction.component;
- if (componentInstruction.reuse) {
- next = this._outlet.reuse(componentInstruction);
- }
- else {
- next =
- this.deactivate(instruction).then(function (_) { return _this._outlet.activate(componentInstruction); });
- }
- if (lang_1.isPresent(instruction.child)) {
- next = next.then(function (_) {
- if (lang_1.isPresent(_this._childRouter)) {
- return _this._childRouter.commit(instruction.child);
- }
- });
- }
- }
- var promises = [];
- this._auxRouters.forEach(function (router, name) {
- if (lang_1.isPresent(instruction.auxInstruction[name])) {
- promises.push(router.commit(instruction.auxInstruction[name]));
- }
- });
- return next.then(function (_) { return async_1.PromiseWrapper.all(promises); });
- };
- /** @internal */
- Router.prototype._startNavigating = function () { this.navigating = true; };
- /** @internal */
- Router.prototype._finishNavigating = function () { this.navigating = false; };
- /**
- * Subscribe to URL updates from the router
- */
- Router.prototype.subscribe = function (onNext) {
- return async_1.ObservableWrapper.subscribe(this._subject, onNext);
- };
- /**
- * Removes the contents of this router's outlet and all descendant outlets
- */
- Router.prototype.deactivate = function (instruction) {
- var _this = this;
- var childInstruction = null;
- var componentInstruction = null;
- if (lang_1.isPresent(instruction)) {
- childInstruction = instruction.child;
- componentInstruction = instruction.component;
- }
- var next = _resolveToTrue;
- if (lang_1.isPresent(this._childRouter)) {
- next = this._childRouter.deactivate(childInstruction);
- }
- if (lang_1.isPresent(this._outlet)) {
- next = next.then(function (_) { return _this._outlet.deactivate(componentInstruction); });
- }
- // TODO: handle aux routes
- return next;
- };
- /**
- * Given a URL, returns an instruction representing the component graph
- */
- Router.prototype.recognize = function (url) {
- var ancestorComponents = this._getAncestorInstructions();
- return this.registry.recognize(url, ancestorComponents);
- };
- Router.prototype._getAncestorInstructions = function () {
- var ancestorComponents = [];
- var ancestorRouter = this;
- while (lang_1.isPresent(ancestorRouter.parent) &&
- lang_1.isPresent(ancestorRouter.parent._currentInstruction)) {
- ancestorRouter = ancestorRouter.parent;
- ancestorComponents.unshift(ancestorRouter._currentInstruction);
- }
- return ancestorComponents;
- };
- /**
- * Navigates to either the last URL successfully navigated to, or the last URL requested if the
- * router has yet to successfully navigate.
- */
- Router.prototype.renavigate = function () {
- if (lang_1.isBlank(this.lastNavigationAttempt)) {
- return this._currentNavigation;
- }
- return this.navigateByUrl(this.lastNavigationAttempt);
- };
- /**
- * Generate an `Instruction` based on the provided Route Link DSL.
- */
- Router.prototype.generate = function (linkParams) {
- var ancestorInstructions = this._getAncestorInstructions();
- return this.registry.generate(linkParams, ancestorInstructions);
- };
- return Router;
- })();
- exports.Router = Router;
- var RootRouter = (function (_super) {
- __extends(RootRouter, _super);
- function RootRouter(registry, location, primaryComponent) {
- var _this = this;
- _super.call(this, registry, null, primaryComponent);
- this._location = location;
- this._locationSub = this._location.subscribe(function (change) {
- // we call recognize ourselves
- _this.recognize(change['url'])
- .then(function (instruction) {
- _this.navigateByInstruction(instruction, lang_1.isPresent(change['pop']))
- .then(function (_) {
- // this is a popstate event; no need to change the URL
- if (lang_1.isPresent(change['pop']) && change['type'] != 'hashchange') {
- return;
- }
- var emitPath = instruction.toUrlPath();
- var emitQuery = instruction.toUrlQuery();
- if (emitPath.length > 0) {
- emitPath = '/' + emitPath;
- }
- // Because we've opted to use All hashchange events occur outside Angular.
- // However, apps that are migrating might have hash links that operate outside
- // angular to which routing must respond.
- // To support these cases where we respond to hashchanges and redirect as a
- // result, we need to replace the top item on the stack.
- if (change['type'] == 'hashchange') {
- if (instruction.toRootUrl() != _this._location.path()) {
- _this._location.replaceState(emitPath, emitQuery);
- }
- }
- else {
- _this._location.go(emitPath, emitQuery);
- }
- });
- });
- });
- this.registry.configFromComponent(primaryComponent);
- this.navigateByUrl(location.path());
- }
- RootRouter.prototype.commit = function (instruction, _skipLocationChange) {
- var _this = this;
- if (_skipLocationChange === void 0) { _skipLocationChange = false; }
- var emitPath = instruction.toUrlPath();
- var emitQuery = instruction.toUrlQuery();
- if (emitPath.length > 0) {
- emitPath = '/' + emitPath;
- }
- var promise = _super.prototype.commit.call(this, instruction);
- if (!_skipLocationChange) {
- promise = promise.then(function (_) { _this._location.go(emitPath, emitQuery); });
- }
- return promise;
- };
- RootRouter.prototype.dispose = function () {
- if (lang_1.isPresent(this._locationSub)) {
- async_1.ObservableWrapper.dispose(this._locationSub);
- this._locationSub = null;
- }
- };
- RootRouter = __decorate([
- core_1.Injectable(),
- __param(2, core_1.Inject(route_registry_1.ROUTER_PRIMARY_COMPONENT)),
- __metadata('design:paramtypes', [route_registry_1.RouteRegistry, location_1.Location, lang_1.Type])
- ], RootRouter);
- return RootRouter;
- })(Router);
- exports.RootRouter = RootRouter;
- var ChildRouter = (function (_super) {
- __extends(ChildRouter, _super);
- function ChildRouter(parent, hostComponent) {
- _super.call(this, parent.registry, parent, hostComponent);
- this.parent = parent;
- }
- ChildRouter.prototype.navigateByUrl = function (url, _skipLocationChange) {
- if (_skipLocationChange === void 0) { _skipLocationChange = false; }
- // Delegate navigation to the root router
- return this.parent.navigateByUrl(url, _skipLocationChange);
- };
- ChildRouter.prototype.navigateByInstruction = function (instruction, _skipLocationChange) {
- if (_skipLocationChange === void 0) { _skipLocationChange = false; }
- // Delegate navigation to the root router
- return this.parent.navigateByInstruction(instruction, _skipLocationChange);
- };
- return ChildRouter;
- })(Router);
- function canActivateOne(nextInstruction, prevInstruction) {
- var next = _resolveToTrue;
- if (lang_1.isPresent(nextInstruction.child)) {
- next = canActivateOne(nextInstruction.child, lang_1.isPresent(prevInstruction) ? prevInstruction.child : null);
- }
- return next.then(function (result) {
- if (result == false) {
- return false;
- }
- if (nextInstruction.component.reuse) {
- return true;
- }
- var hook = route_lifecycle_reflector_1.getCanActivateHook(nextInstruction.component.componentType);
- if (lang_1.isPresent(hook)) {
- return hook(nextInstruction.component, lang_1.isPresent(prevInstruction) ? prevInstruction.component : null);
- }
- return true;
- });
- }
- /***/ },
- /* 226 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var collection_1 = __webpack_require__(12);
- var async_1 = __webpack_require__(60);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var reflection_1 = __webpack_require__(16);
- var core_1 = __webpack_require__(2);
- var route_config_impl_1 = __webpack_require__(227);
- var route_recognizer_1 = __webpack_require__(228);
- var component_recognizer_1 = __webpack_require__(232);
- var instruction_1 = __webpack_require__(229);
- var route_config_nomalizer_1 = __webpack_require__(235);
- var url_parser_1 = __webpack_require__(231);
- var _resolveToNull = async_1.PromiseWrapper.resolve(null);
- /**
- * Token used to bind the component with the top-level {@link RouteConfig}s for the
- * application.
- *
- * ### Example ([live demo](http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm))
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {
- * ROUTER_DIRECTIVES,
- * ROUTER_PROVIDERS,
- * RouteConfig
- * } from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * // ...
- * }
- *
- * bootstrap(AppCmp, [ROUTER_PROVIDERS]);
- * ```
- */
- exports.ROUTER_PRIMARY_COMPONENT = lang_1.CONST_EXPR(new core_1.OpaqueToken('RouterPrimaryComponent'));
- /**
- * The RouteRegistry holds route configurations for each component in an Angular app.
- * It is responsible for creating Instructions from URLs, and generating URLs based on route and
- * parameters.
- */
- var RouteRegistry = (function () {
- function RouteRegistry(_rootComponent) {
- this._rootComponent = _rootComponent;
- this._rules = new collection_1.Map();
- }
- /**
- * Given a component and a configuration object, add the route to this registry
- */
- RouteRegistry.prototype.config = function (parentComponent, config) {
- config = route_config_nomalizer_1.normalizeRouteConfig(config, this);
- // this is here because Dart type guard reasons
- if (config instanceof route_config_impl_1.Route) {
- route_config_nomalizer_1.assertComponentExists(config.component, config.path);
- }
- else if (config instanceof route_config_impl_1.AuxRoute) {
- route_config_nomalizer_1.assertComponentExists(config.component, config.path);
- }
- var recognizer = this._rules.get(parentComponent);
- if (lang_1.isBlank(recognizer)) {
- recognizer = new component_recognizer_1.ComponentRecognizer();
- this._rules.set(parentComponent, recognizer);
- }
- var terminal = recognizer.config(config);
- if (config instanceof route_config_impl_1.Route) {
- if (terminal) {
- assertTerminalComponent(config.component, config.path);
- }
- else {
- this.configFromComponent(config.component);
- }
- }
- };
- /**
- * Reads the annotations of a component and configures the registry based on them
- */
- RouteRegistry.prototype.configFromComponent = function (component) {
- var _this = this;
- if (!lang_1.isType(component)) {
- return;
- }
- // Don't read the annotations from a type more than once –
- // this prevents an infinite loop if a component routes recursively.
- if (this._rules.has(component)) {
- return;
- }
- var annotations = reflection_1.reflector.annotations(component);
- if (lang_1.isPresent(annotations)) {
- for (var i = 0; i < annotations.length; i++) {
- var annotation = annotations[i];
- if (annotation instanceof route_config_impl_1.RouteConfig) {
- var routeCfgs = annotation.configs;
- routeCfgs.forEach(function (config) { return _this.config(component, config); });
- }
- }
- }
- };
- /**
- * Given a URL and a parent component, return the most specific instruction for navigating
- * the application into the state specified by the url
- */
- RouteRegistry.prototype.recognize = function (url, ancestorInstructions) {
- var parsedUrl = url_parser_1.parser.parse(url);
- return this._recognize(parsedUrl, ancestorInstructions);
- };
- /**
- * Recognizes all parent-child routes, but creates unresolved auxiliary routes
- */
- RouteRegistry.prototype._recognize = function (parsedUrl, ancestorInstructions, _aux) {
- var _this = this;
- if (_aux === void 0) { _aux = false; }
- var parentComponent = ancestorInstructions.length > 0 ?
- ancestorInstructions[ancestorInstructions.length - 1].component.componentType :
- this._rootComponent;
- var componentRecognizer = this._rules.get(parentComponent);
- if (lang_1.isBlank(componentRecognizer)) {
- return _resolveToNull;
- }
- // Matches some beginning part of the given URL
- var possibleMatches = _aux ? componentRecognizer.recognizeAuxiliary(parsedUrl) :
- componentRecognizer.recognize(parsedUrl);
- var matchPromises = possibleMatches.map(function (candidate) { return candidate.then(function (candidate) {
- if (candidate instanceof route_recognizer_1.PathMatch) {
- var auxParentInstructions = ancestorInstructions.length > 0 ?
- [ancestorInstructions[ancestorInstructions.length - 1]] :
- [];
- var auxInstructions = _this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions);
- var instruction = new instruction_1.ResolvedInstruction(candidate.instruction, null, auxInstructions);
- if (candidate.instruction.terminal) {
- return instruction;
- }
- var newAncestorComponents = ancestorInstructions.concat([instruction]);
- return _this._recognize(candidate.remaining, newAncestorComponents)
- .then(function (childInstruction) {
- if (lang_1.isBlank(childInstruction)) {
- return null;
- }
- // redirect instructions are already absolute
- if (childInstruction instanceof instruction_1.RedirectInstruction) {
- return childInstruction;
- }
- instruction.child = childInstruction;
- return instruction;
- });
- }
- if (candidate instanceof route_recognizer_1.RedirectMatch) {
- var instruction = _this.generate(candidate.redirectTo, ancestorInstructions);
- return new instruction_1.RedirectInstruction(instruction.component, instruction.child, instruction.auxInstruction);
- }
- }); });
- if ((lang_1.isBlank(parsedUrl) || parsedUrl.path == '') && possibleMatches.length == 0) {
- return async_1.PromiseWrapper.resolve(this.generateDefault(parentComponent));
- }
- return async_1.PromiseWrapper.all(matchPromises).then(mostSpecific);
- };
- RouteRegistry.prototype._auxRoutesToUnresolved = function (auxRoutes, parentInstructions) {
- var _this = this;
- var unresolvedAuxInstructions = {};
- auxRoutes.forEach(function (auxUrl) {
- unresolvedAuxInstructions[auxUrl.path] = new instruction_1.UnresolvedInstruction(function () { return _this._recognize(auxUrl, parentInstructions, true); });
- });
- return unresolvedAuxInstructions;
- };
- /**
- * Given a normalized list with component names and params like: `['user', {id: 3 }]`
- * generates a url with a leading slash relative to the provided `parentComponent`.
- *
- * If the optional param `_aux` is `true`, then we generate starting at an auxiliary
- * route boundary.
- */
- RouteRegistry.prototype.generate = function (linkParams, ancestorInstructions, _aux) {
- if (_aux === void 0) { _aux = false; }
- var normalizedLinkParams = splitAndFlattenLinkParams(linkParams);
- var first = collection_1.ListWrapper.first(normalizedLinkParams);
- var rest = collection_1.ListWrapper.slice(normalizedLinkParams, 1);
- // The first segment should be either '.' (generate from parent) or '' (generate from root).
- // When we normalize above, we strip all the slashes, './' becomes '.' and '/' becomes ''.
- if (first == '') {
- ancestorInstructions = [];
- }
- else if (first == '..') {
- // we already captured the first instance of "..", so we need to pop off an ancestor
- ancestorInstructions.pop();
- while (collection_1.ListWrapper.first(rest) == '..') {
- rest = collection_1.ListWrapper.slice(rest, 1);
- ancestorInstructions.pop();
- if (ancestorInstructions.length <= 0) {
- throw new exceptions_1.BaseException("Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" has too many \"../\" segments.");
- }
- }
- }
- else if (first != '.') {
- var parentComponent = this._rootComponent;
- var grandparentComponent = null;
- if (ancestorInstructions.length > 1) {
- parentComponent =
- ancestorInstructions[ancestorInstructions.length - 1].component.componentType;
- grandparentComponent =
- ancestorInstructions[ancestorInstructions.length - 2].component.componentType;
- }
- else if (ancestorInstructions.length == 1) {
- parentComponent = ancestorInstructions[0].component.componentType;
- grandparentComponent = this._rootComponent;
- }
- // For a link with no leading `./`, `/`, or `../`, we look for a sibling and child.
- // If both exist, we throw. Otherwise, we prefer whichever exists.
- var childRouteExists = this.hasRoute(first, parentComponent);
- var parentRouteExists = lang_1.isPresent(grandparentComponent) && this.hasRoute(first, grandparentComponent);
- if (parentRouteExists && childRouteExists) {
- var msg = "Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" is ambiguous, use \"./\" or \"../\" to disambiguate.";
- throw new exceptions_1.BaseException(msg);
- }
- if (parentRouteExists) {
- ancestorInstructions.pop();
- }
- rest = linkParams;
- }
- if (rest[rest.length - 1] == '') {
- rest.pop();
- }
- if (rest.length < 1) {
- var msg = "Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" must include a route name.";
- throw new exceptions_1.BaseException(msg);
- }
- var generatedInstruction = this._generate(rest, ancestorInstructions, _aux);
- for (var i = ancestorInstructions.length - 1; i >= 0; i--) {
- var ancestorInstruction = ancestorInstructions[i];
- generatedInstruction = ancestorInstruction.replaceChild(generatedInstruction);
- }
- return generatedInstruction;
- };
- /*
- * Internal helper that does not make any assertions about the beginning of the link DSL
- */
- RouteRegistry.prototype._generate = function (linkParams, ancestorInstructions, _aux) {
- var _this = this;
- if (_aux === void 0) { _aux = false; }
- var parentComponent = ancestorInstructions.length > 0 ?
- ancestorInstructions[ancestorInstructions.length - 1].component.componentType :
- this._rootComponent;
- if (linkParams.length == 0) {
- return this.generateDefault(parentComponent);
- }
- var linkIndex = 0;
- var routeName = linkParams[linkIndex];
- if (!lang_1.isString(routeName)) {
- throw new exceptions_1.BaseException("Unexpected segment \"" + routeName + "\" in link DSL. Expected a string.");
- }
- else if (routeName == '' || routeName == '.' || routeName == '..') {
- throw new exceptions_1.BaseException("\"" + routeName + "/\" is only allowed at the beginning of a link DSL.");
- }
- var params = {};
- if (linkIndex + 1 < linkParams.length) {
- var nextSegment_1 = linkParams[linkIndex + 1];
- if (lang_1.isStringMap(nextSegment_1) && !lang_1.isArray(nextSegment_1)) {
- params = nextSegment_1;
- linkIndex += 1;
- }
- }
- var auxInstructions = {};
- var nextSegment;
- while (linkIndex + 1 < linkParams.length && lang_1.isArray(nextSegment = linkParams[linkIndex + 1])) {
- var auxParentInstruction = ancestorInstructions.length > 0 ?
- [ancestorInstructions[ancestorInstructions.length - 1]] :
- [];
- var auxInstruction = this._generate(nextSegment, auxParentInstruction, true);
- // TODO: this will not work for aux routes with parameters or multiple segments
- auxInstructions[auxInstruction.component.urlPath] = auxInstruction;
- linkIndex += 1;
- }
- var componentRecognizer = this._rules.get(parentComponent);
- if (lang_1.isBlank(componentRecognizer)) {
- throw new exceptions_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(parentComponent) + "\" has no route config.");
- }
- var routeRecognizer = (_aux ? componentRecognizer.auxNames : componentRecognizer.names).get(routeName);
- if (!lang_1.isPresent(routeRecognizer)) {
- throw new exceptions_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(parentComponent) + "\" has no route named \"" + routeName + "\".");
- }
- if (!lang_1.isPresent(routeRecognizer.handler.componentType)) {
- var compInstruction = routeRecognizer.generateComponentPathValues(params);
- return new instruction_1.UnresolvedInstruction(function () {
- return routeRecognizer.handler.resolveComponentType().then(function (_) { return _this._generate(linkParams, ancestorInstructions, _aux); });
- }, compInstruction['urlPath'], compInstruction['urlParams']);
- }
- var componentInstruction = _aux ? componentRecognizer.generateAuxiliary(routeName, params) :
- componentRecognizer.generate(routeName, params);
- var remaining = linkParams.slice(linkIndex + 1);
- var instruction = new instruction_1.ResolvedInstruction(componentInstruction, null, auxInstructions);
- // the component is sync
- if (lang_1.isPresent(componentInstruction.componentType)) {
- var childInstruction = null;
- if (linkIndex + 1 < linkParams.length) {
- var childAncestorComponents = ancestorInstructions.concat([instruction]);
- childInstruction = this._generate(remaining, childAncestorComponents);
- }
- else if (!componentInstruction.terminal) {
- // ... look for defaults
- childInstruction = this.generateDefault(componentInstruction.componentType);
- if (lang_1.isBlank(childInstruction)) {
- throw new exceptions_1.BaseException("Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" does not resolve to a terminal instruction.");
- }
- }
- instruction.child = childInstruction;
- }
- return instruction;
- };
- RouteRegistry.prototype.hasRoute = function (name, parentComponent) {
- var componentRecognizer = this._rules.get(parentComponent);
- if (lang_1.isBlank(componentRecognizer)) {
- return false;
- }
- return componentRecognizer.hasRoute(name);
- };
- RouteRegistry.prototype.generateDefault = function (componentCursor) {
- var _this = this;
- if (lang_1.isBlank(componentCursor)) {
- return null;
- }
- var componentRecognizer = this._rules.get(componentCursor);
- if (lang_1.isBlank(componentRecognizer) || lang_1.isBlank(componentRecognizer.defaultRoute)) {
- return null;
- }
- var defaultChild = null;
- if (lang_1.isPresent(componentRecognizer.defaultRoute.handler.componentType)) {
- var componentInstruction = componentRecognizer.defaultRoute.generate({});
- if (!componentRecognizer.defaultRoute.terminal) {
- defaultChild = this.generateDefault(componentRecognizer.defaultRoute.handler.componentType);
- }
- return new instruction_1.DefaultInstruction(componentInstruction, defaultChild);
- }
- return new instruction_1.UnresolvedInstruction(function () {
- return componentRecognizer.defaultRoute.handler.resolveComponentType().then(function (_) { return _this.generateDefault(componentCursor); });
- });
- };
- RouteRegistry = __decorate([
- core_1.Injectable(),
- __param(0, core_1.Inject(exports.ROUTER_PRIMARY_COMPONENT)),
- __metadata('design:paramtypes', [lang_1.Type])
- ], RouteRegistry);
- return RouteRegistry;
- })();
- exports.RouteRegistry = RouteRegistry;
- /*
- * Given: ['/a/b', {c: 2}]
- * Returns: ['', 'a', 'b', {c: 2}]
- */
- function splitAndFlattenLinkParams(linkParams) {
- return linkParams.reduce(function (accumulation, item) {
- if (lang_1.isString(item)) {
- var strItem = item;
- return accumulation.concat(strItem.split('/'));
- }
- accumulation.push(item);
- return accumulation;
- }, []);
- }
- /*
- * Given a list of instructions, returns the most specific instruction
- */
- function mostSpecific(instructions) {
- return collection_1.ListWrapper.maximum(instructions, function (instruction) { return instruction.specificity; });
- }
- function assertTerminalComponent(component, path) {
- if (!lang_1.isType(component)) {
- return;
- }
- var annotations = reflection_1.reflector.annotations(component);
- if (lang_1.isPresent(annotations)) {
- for (var i = 0; i < annotations.length; i++) {
- var annotation = annotations[i];
- if (annotation instanceof route_config_impl_1.RouteConfig) {
- throw new exceptions_1.BaseException("Child routes are not allowed for \"" + path + "\". Use \"...\" on the parent's route path.");
- }
- }
- }
- }
- /***/ },
- /* 227 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- /**
- * The `RouteConfig` decorator defines routes for a given component.
- *
- * It takes an array of {@link RouteDefinition}s.
- */
- var RouteConfig = (function () {
- function RouteConfig(configs) {
- this.configs = configs;
- }
- RouteConfig = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Array])
- ], RouteConfig);
- return RouteConfig;
- })();
- exports.RouteConfig = RouteConfig;
- /**
- * `Route` is a type of {@link RouteDefinition} used to route a path to a component.
- *
- * It has the following properties:
- * - `path` is a string that uses the route matcher DSL.
- * - `component` a component type.
- * - `name` is an optional `CamelCase` string representing the name of the route.
- * - `data` is an optional property of any type representing arbitrary route metadata for the given
- * route. It is injectable via {@link RouteData}.
- * - `useAsDefault` is a boolean value. If `true`, the child route will be navigated to if no child
- * route is specified during the navigation.
- *
- * ### Example
- * ```
- * import {RouteConfig} from 'angular2/router';
- *
- * @RouteConfig([
- * {path: '/home', component: HomeCmp, name: 'HomeCmp' }
- * ])
- * class MyApp {}
- * ```
- */
- var Route = (function () {
- function Route(_a) {
- var path = _a.path, component = _a.component, name = _a.name, data = _a.data, useAsDefault = _a.useAsDefault;
- // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
- this.aux = null;
- this.loader = null;
- this.redirectTo = null;
- this.path = path;
- this.component = component;
- this.name = name;
- this.data = data;
- this.useAsDefault = useAsDefault;
- }
- Route = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], Route);
- return Route;
- })();
- exports.Route = Route;
- /**
- * `AuxRoute` is a type of {@link RouteDefinition} used to define an auxiliary route.
- *
- * It takes an object with the following properties:
- * - `path` is a string that uses the route matcher DSL.
- * - `component` a component type.
- * - `name` is an optional `CamelCase` string representing the name of the route.
- * - `data` is an optional property of any type representing arbitrary route metadata for the given
- * route. It is injectable via {@link RouteData}.
- *
- * ### Example
- * ```
- * import {RouteConfig, AuxRoute} from 'angular2/router';
- *
- * @RouteConfig([
- * new AuxRoute({path: '/home', component: HomeCmp})
- * ])
- * class MyApp {}
- * ```
- */
- var AuxRoute = (function () {
- function AuxRoute(_a) {
- var path = _a.path, component = _a.component, name = _a.name;
- this.data = null;
- // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
- this.aux = null;
- this.loader = null;
- this.redirectTo = null;
- this.useAsDefault = false;
- this.path = path;
- this.component = component;
- this.name = name;
- }
- AuxRoute = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], AuxRoute);
- return AuxRoute;
- })();
- exports.AuxRoute = AuxRoute;
- /**
- * `AsyncRoute` is a type of {@link RouteDefinition} used to route a path to an asynchronously
- * loaded component.
- *
- * It has the following properties:
- * - `path` is a string that uses the route matcher DSL.
- * - `loader` is a function that returns a promise that resolves to a component.
- * - `name` is an optional `CamelCase` string representing the name of the route.
- * - `data` is an optional property of any type representing arbitrary route metadata for the given
- * route. It is injectable via {@link RouteData}.
- * - `useAsDefault` is a boolean value. If `true`, the child route will be navigated to if no child
- * route is specified during the navigation.
- *
- * ### Example
- * ```
- * import {RouteConfig} from 'angular2/router';
- *
- * @RouteConfig([
- * {path: '/home', loader: () => Promise.resolve(MyLoadedCmp), name: 'MyLoadedCmp'}
- * ])
- * class MyApp {}
- * ```
- */
- var AsyncRoute = (function () {
- function AsyncRoute(_a) {
- var path = _a.path, loader = _a.loader, name = _a.name, data = _a.data, useAsDefault = _a.useAsDefault;
- this.aux = null;
- this.path = path;
- this.loader = loader;
- this.name = name;
- this.data = data;
- this.useAsDefault = useAsDefault;
- }
- AsyncRoute = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], AsyncRoute);
- return AsyncRoute;
- })();
- exports.AsyncRoute = AsyncRoute;
- /**
- * `Redirect` is a type of {@link RouteDefinition} used to route a path to a canonical route.
- *
- * It has the following properties:
- * - `path` is a string that uses the route matcher DSL.
- * - `redirectTo` is an array representing the link DSL.
- *
- * Note that redirects **do not** affect how links are generated. For that, see the `useAsDefault`
- * option.
- *
- * ### Example
- * ```
- * import {RouteConfig} from 'angular2/router';
- *
- * @RouteConfig([
- * {path: '/', redirectTo: ['/Home'] },
- * {path: '/home', component: HomeCmp, name: 'Home'}
- * ])
- * class MyApp {}
- * ```
- */
- var Redirect = (function () {
- function Redirect(_a) {
- var path = _a.path, redirectTo = _a.redirectTo;
- this.name = null;
- // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
- this.loader = null;
- this.data = null;
- this.aux = null;
- this.useAsDefault = false;
- this.path = path;
- this.redirectTo = redirectTo;
- }
- Redirect = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Object])
- ], Redirect);
- return Redirect;
- })();
- exports.Redirect = Redirect;
- /***/ },
- /* 228 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var promise_1 = __webpack_require__(61);
- var collection_1 = __webpack_require__(12);
- var instruction_1 = __webpack_require__(229);
- var path_recognizer_1 = __webpack_require__(230);
- var RouteMatch = (function () {
- function RouteMatch() {
- }
- return RouteMatch;
- })();
- exports.RouteMatch = RouteMatch;
- var PathMatch = (function (_super) {
- __extends(PathMatch, _super);
- function PathMatch(instruction, remaining, remainingAux) {
- _super.call(this);
- this.instruction = instruction;
- this.remaining = remaining;
- this.remainingAux = remainingAux;
- }
- return PathMatch;
- })(RouteMatch);
- exports.PathMatch = PathMatch;
- var RedirectMatch = (function (_super) {
- __extends(RedirectMatch, _super);
- function RedirectMatch(redirectTo, specificity) {
- _super.call(this);
- this.redirectTo = redirectTo;
- this.specificity = specificity;
- }
- return RedirectMatch;
- })(RouteMatch);
- exports.RedirectMatch = RedirectMatch;
- var RedirectRecognizer = (function () {
- function RedirectRecognizer(path, redirectTo) {
- this.path = path;
- this.redirectTo = redirectTo;
- this._pathRecognizer = new path_recognizer_1.PathRecognizer(path);
- this.hash = this._pathRecognizer.hash;
- }
- /**
- * Returns `null` or a `ParsedUrl` representing the new path to match
- */
- RedirectRecognizer.prototype.recognize = function (beginningSegment) {
- var match = null;
- if (lang_1.isPresent(this._pathRecognizer.recognize(beginningSegment))) {
- match = new RedirectMatch(this.redirectTo, this._pathRecognizer.specificity);
- }
- return promise_1.PromiseWrapper.resolve(match);
- };
- RedirectRecognizer.prototype.generate = function (params) {
- throw new exceptions_1.BaseException("Tried to generate a redirect.");
- };
- return RedirectRecognizer;
- })();
- exports.RedirectRecognizer = RedirectRecognizer;
- // represents something like '/foo/:bar'
- var RouteRecognizer = (function () {
- // TODO: cache component instruction instances by params and by ParsedUrl instance
- function RouteRecognizer(path, handler) {
- this.path = path;
- this.handler = handler;
- this.terminal = true;
- this._cache = new collection_1.Map();
- this._pathRecognizer = new path_recognizer_1.PathRecognizer(path);
- this.specificity = this._pathRecognizer.specificity;
- this.hash = this._pathRecognizer.hash;
- this.terminal = this._pathRecognizer.terminal;
- }
- RouteRecognizer.prototype.recognize = function (beginningSegment) {
- var _this = this;
- var res = this._pathRecognizer.recognize(beginningSegment);
- if (lang_1.isBlank(res)) {
- return null;
- }
- return this.handler.resolveComponentType().then(function (_) {
- var componentInstruction = _this._getInstruction(res['urlPath'], res['urlParams'], res['allParams']);
- return new PathMatch(componentInstruction, res['nextSegment'], res['auxiliary']);
- });
- };
- RouteRecognizer.prototype.generate = function (params) {
- var generated = this._pathRecognizer.generate(params);
- var urlPath = generated['urlPath'];
- var urlParams = generated['urlParams'];
- return this._getInstruction(urlPath, urlParams, params);
- };
- RouteRecognizer.prototype.generateComponentPathValues = function (params) {
- return this._pathRecognizer.generate(params);
- };
- RouteRecognizer.prototype._getInstruction = function (urlPath, urlParams, params) {
- if (lang_1.isBlank(this.handler.componentType)) {
- throw new exceptions_1.BaseException("Tried to get instruction before the type was loaded.");
- }
- var hashKey = urlPath + '?' + urlParams.join('?');
- if (this._cache.has(hashKey)) {
- return this._cache.get(hashKey);
- }
- var instruction = new instruction_1.ComponentInstruction(urlPath, urlParams, this.handler.data, this.handler.componentType, this.terminal, this.specificity, params);
- this._cache.set(hashKey, instruction);
- return instruction;
- };
- return RouteRecognizer;
- })();
- exports.RouteRecognizer = RouteRecognizer;
- /***/ },
- /* 229 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var async_1 = __webpack_require__(60);
- /**
- * `RouteParams` is an immutable map of parameters for the given route
- * based on the url matcher and optional parameters for that route.
- *
- * You can inject `RouteParams` into the constructor of a component to use it.
- *
- * ### Example
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {path: '/user/:id', component: UserCmp, as: 'UserCmp'},
- * ])
- * class AppCmp {}
- *
- * @Component({ template: 'user: {{id}}' })
- * class UserCmp {
- * id: string;
- * constructor(params: RouteParams) {
- * this.id = params.get('id');
- * }
- * }
- *
- * bootstrap(AppCmp, ROUTER_PROVIDERS);
- * ```
- */
- var RouteParams = (function () {
- function RouteParams(params) {
- this.params = params;
- }
- RouteParams.prototype.get = function (param) { return lang_1.normalizeBlank(collection_1.StringMapWrapper.get(this.params, param)); };
- return RouteParams;
- })();
- exports.RouteParams = RouteParams;
- /**
- * `RouteData` is an immutable map of additional data you can configure in your {@link Route}.
- *
- * You can inject `RouteData` into the constructor of a component to use it.
- *
- * ### Example
- *
- * ```
- * import {Component, View} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {Router, ROUTER_DIRECTIVES, routerBindings, RouteConfig} from 'angular2/router';
- *
- * @Component({...})
- * @View({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {path: '/user/:id', component: UserCmp, as: 'UserCmp', data: {isAdmin: true}},
- * ])
- * class AppCmp {}
- *
- * @Component({...})
- * @View({ template: 'user: {{isAdmin}}' })
- * class UserCmp {
- * string: isAdmin;
- * constructor(data: RouteData) {
- * this.isAdmin = data.get('isAdmin');
- * }
- * }
- *
- * bootstrap(AppCmp, routerBindings(AppCmp));
- * ```
- */
- var RouteData = (function () {
- function RouteData(data) {
- if (data === void 0) { data = lang_1.CONST_EXPR({}); }
- this.data = data;
- }
- RouteData.prototype.get = function (key) { return lang_1.normalizeBlank(collection_1.StringMapWrapper.get(this.data, key)); };
- return RouteData;
- })();
- exports.RouteData = RouteData;
- exports.BLANK_ROUTE_DATA = new RouteData();
- /**
- * `Instruction` is a tree of {@link ComponentInstruction}s with all the information needed
- * to transition each component in the app to a given route, including all auxiliary routes.
- *
- * `Instruction`s can be created using {@link Router#generate}, and can be used to
- * perform route changes with {@link Router#navigateByInstruction}.
- *
- * ### Example
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {bootstrap} from 'angular2/platform/browser';
- * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * constructor(router: Router) {
- * var instruction = router.generate(['/MyRoute']);
- * router.navigateByInstruction(instruction);
- * }
- * }
- *
- * bootstrap(AppCmp, ROUTER_PROVIDERS);
- * ```
- */
- var Instruction = (function () {
- function Instruction() {
- this.auxInstruction = {};
- }
- Object.defineProperty(Instruction.prototype, "urlPath", {
- get: function () { return this.component.urlPath; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Instruction.prototype, "urlParams", {
- get: function () { return this.component.urlParams; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(Instruction.prototype, "specificity", {
- get: function () {
- var total = 0;
- if (lang_1.isPresent(this.component)) {
- total += this.component.specificity;
- }
- if (lang_1.isPresent(this.child)) {
- total += this.child.specificity;
- }
- return total;
- },
- enumerable: true,
- configurable: true
- });
- /**
- * converts the instruction into a URL string
- */
- Instruction.prototype.toRootUrl = function () { return this.toUrlPath() + this.toUrlQuery(); };
- /** @internal */
- Instruction.prototype._toNonRootUrl = function () {
- return this._stringifyPathMatrixAuxPrefixed() +
- (lang_1.isPresent(this.child) ? this.child._toNonRootUrl() : '');
- };
- Instruction.prototype.toUrlQuery = function () { return this.urlParams.length > 0 ? ('?' + this.urlParams.join('&')) : ''; };
- /**
- * Returns a new instruction that shares the state of the existing instruction, but with
- * the given child {@link Instruction} replacing the existing child.
- */
- Instruction.prototype.replaceChild = function (child) {
- return new ResolvedInstruction(this.component, child, this.auxInstruction);
- };
- /**
- * If the final URL for the instruction is ``
- */
- Instruction.prototype.toUrlPath = function () {
- return this.urlPath + this._stringifyAux() +
- (lang_1.isPresent(this.child) ? this.child._toNonRootUrl() : '');
- };
- // default instructions override these
- Instruction.prototype.toLinkUrl = function () {
- return this.urlPath + this._stringifyAux() +
- (lang_1.isPresent(this.child) ? this.child._toLinkUrl() : '');
- };
- // this is the non-root version (called recursively)
- /** @internal */
- Instruction.prototype._toLinkUrl = function () {
- return this._stringifyPathMatrixAuxPrefixed() +
- (lang_1.isPresent(this.child) ? this.child._toLinkUrl() : '');
- };
- /** @internal */
- Instruction.prototype._stringifyPathMatrixAuxPrefixed = function () {
- var primary = this._stringifyPathMatrixAux();
- if (primary.length > 0) {
- primary = '/' + primary;
- }
- return primary;
- };
- /** @internal */
- Instruction.prototype._stringifyMatrixParams = function () {
- return this.urlParams.length > 0 ? (';' + this.component.urlParams.join(';')) : '';
- };
- /** @internal */
- Instruction.prototype._stringifyPathMatrixAux = function () {
- if (lang_1.isBlank(this.component)) {
- return '';
- }
- return this.urlPath + this._stringifyMatrixParams() + this._stringifyAux();
- };
- /** @internal */
- Instruction.prototype._stringifyAux = function () {
- var routes = [];
- collection_1.StringMapWrapper.forEach(this.auxInstruction, function (auxInstruction, _) {
- routes.push(auxInstruction._stringifyPathMatrixAux());
- });
- if (routes.length > 0) {
- return '(' + routes.join('//') + ')';
- }
- return '';
- };
- return Instruction;
- })();
- exports.Instruction = Instruction;
- /**
- * a resolved instruction has an outlet instruction for itself, but maybe not for...
- */
- var ResolvedInstruction = (function (_super) {
- __extends(ResolvedInstruction, _super);
- function ResolvedInstruction(component, child, auxInstruction) {
- _super.call(this);
- this.component = component;
- this.child = child;
- this.auxInstruction = auxInstruction;
- }
- ResolvedInstruction.prototype.resolveComponent = function () {
- return async_1.PromiseWrapper.resolve(this.component);
- };
- return ResolvedInstruction;
- })(Instruction);
- exports.ResolvedInstruction = ResolvedInstruction;
- /**
- * Represents a resolved default route
- */
- var DefaultInstruction = (function (_super) {
- __extends(DefaultInstruction, _super);
- function DefaultInstruction(component, child) {
- _super.call(this);
- this.component = component;
- this.child = child;
- }
- DefaultInstruction.prototype.resolveComponent = function () {
- return async_1.PromiseWrapper.resolve(this.component);
- };
- DefaultInstruction.prototype.toLinkUrl = function () { return ''; };
- /** @internal */
- DefaultInstruction.prototype._toLinkUrl = function () { return ''; };
- return DefaultInstruction;
- })(Instruction);
- exports.DefaultInstruction = DefaultInstruction;
- /**
- * Represents a component that may need to do some redirection or lazy loading at a later time.
- */
- var UnresolvedInstruction = (function (_super) {
- __extends(UnresolvedInstruction, _super);
- function UnresolvedInstruction(_resolver, _urlPath, _urlParams) {
- if (_urlPath === void 0) { _urlPath = ''; }
- if (_urlParams === void 0) { _urlParams = lang_1.CONST_EXPR([]); }
- _super.call(this);
- this._resolver = _resolver;
- this._urlPath = _urlPath;
- this._urlParams = _urlParams;
- }
- Object.defineProperty(UnresolvedInstruction.prototype, "urlPath", {
- get: function () {
- if (lang_1.isPresent(this.component)) {
- return this.component.urlPath;
- }
- if (lang_1.isPresent(this._urlPath)) {
- return this._urlPath;
- }
- return '';
- },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(UnresolvedInstruction.prototype, "urlParams", {
- get: function () {
- if (lang_1.isPresent(this.component)) {
- return this.component.urlParams;
- }
- if (lang_1.isPresent(this._urlParams)) {
- return this._urlParams;
- }
- return [];
- },
- enumerable: true,
- configurable: true
- });
- UnresolvedInstruction.prototype.resolveComponent = function () {
- var _this = this;
- if (lang_1.isPresent(this.component)) {
- return async_1.PromiseWrapper.resolve(this.component);
- }
- return this._resolver().then(function (resolution) {
- _this.child = resolution.child;
- return _this.component = resolution.component;
- });
- };
- return UnresolvedInstruction;
- })(Instruction);
- exports.UnresolvedInstruction = UnresolvedInstruction;
- var RedirectInstruction = (function (_super) {
- __extends(RedirectInstruction, _super);
- function RedirectInstruction(component, child, auxInstruction) {
- _super.call(this, component, child, auxInstruction);
- }
- return RedirectInstruction;
- })(ResolvedInstruction);
- exports.RedirectInstruction = RedirectInstruction;
- /**
- * A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
- * composed of a tree of these `ComponentInstruction`s.
- *
- * `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
- * to route lifecycle hooks, like {@link CanActivate}.
- *
- * `ComponentInstruction`s are [https://en.wikipedia.org/wiki/Hash_consing](hash consed). You should
- * never construct one yourself with "new." Instead, rely on {@link Router/RouteRecognizer} to
- * construct `ComponentInstruction`s.
- *
- * You should not modify this object. It should be treated as immutable.
- */
- var ComponentInstruction = (function () {
- function ComponentInstruction(urlPath, urlParams, data, componentType, terminal, specificity, params) {
- if (params === void 0) { params = null; }
- this.urlPath = urlPath;
- this.urlParams = urlParams;
- this.componentType = componentType;
- this.terminal = terminal;
- this.specificity = specificity;
- this.params = params;
- this.reuse = false;
- this.routeData = lang_1.isPresent(data) ? data : exports.BLANK_ROUTE_DATA;
- }
- return ComponentInstruction;
- })();
- exports.ComponentInstruction = ComponentInstruction;
- /***/ },
- /* 230 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var url_parser_1 = __webpack_require__(231);
- var TouchMap = (function () {
- function TouchMap(map) {
- var _this = this;
- this.map = {};
- this.keys = {};
- if (lang_1.isPresent(map)) {
- collection_1.StringMapWrapper.forEach(map, function (value, key) {
- _this.map[key] = lang_1.isPresent(value) ? value.toString() : null;
- _this.keys[key] = true;
- });
- }
- }
- TouchMap.prototype.get = function (key) {
- collection_1.StringMapWrapper.delete(this.keys, key);
- return this.map[key];
- };
- TouchMap.prototype.getUnused = function () {
- var _this = this;
- var unused = {};
- var keys = collection_1.StringMapWrapper.keys(this.keys);
- keys.forEach(function (key) { return unused[key] = collection_1.StringMapWrapper.get(_this.map, key); });
- return unused;
- };
- return TouchMap;
- })();
- function normalizeString(obj) {
- if (lang_1.isBlank(obj)) {
- return null;
- }
- else {
- return obj.toString();
- }
- }
- var ContinuationSegment = (function () {
- function ContinuationSegment() {
- this.name = '';
- }
- ContinuationSegment.prototype.generate = function (params) { return ''; };
- ContinuationSegment.prototype.match = function (path) { return true; };
- return ContinuationSegment;
- })();
- var StaticSegment = (function () {
- function StaticSegment(path) {
- this.path = path;
- this.name = '';
- }
- StaticSegment.prototype.match = function (path) { return path == this.path; };
- StaticSegment.prototype.generate = function (params) { return this.path; };
- return StaticSegment;
- })();
- var DynamicSegment = (function () {
- function DynamicSegment(name) {
- this.name = name;
- }
- DynamicSegment.prototype.match = function (path) { return path.length > 0; };
- DynamicSegment.prototype.generate = function (params) {
- if (!collection_1.StringMapWrapper.contains(params.map, this.name)) {
- throw new exceptions_1.BaseException("Route generator for '" + this.name + "' was not included in parameters passed.");
- }
- return normalizeString(params.get(this.name));
- };
- return DynamicSegment;
- })();
- var StarSegment = (function () {
- function StarSegment(name) {
- this.name = name;
- }
- StarSegment.prototype.match = function (path) { return true; };
- StarSegment.prototype.generate = function (params) { return normalizeString(params.get(this.name)); };
- return StarSegment;
- })();
- var paramMatcher = /^:([^\/]+)$/g;
- var wildcardMatcher = /^\*([^\/]+)$/g;
- function parsePathString(route) {
- // normalize route as not starting with a "/". Recognition will
- // also normalize.
- if (route.startsWith("/")) {
- route = route.substring(1);
- }
- var segments = splitBySlash(route);
- var results = [];
- var specificity = 0;
- // The "specificity" of a path is used to determine which route is used when multiple routes match
- // a URL.
- // Static segments (like "/foo") are the most specific, followed by dynamic segments (like
- // "/:id"). Star segments
- // add no specificity. Segments at the start of the path are more specific than proceeding ones.
- // The code below uses place values to combine the different types of segments into a single
- // integer that we can
- // sort later. Each static segment is worth hundreds of points of specificity (10000, 9900, ...,
- // 200), and each
- // dynamic segment is worth single points of specificity (100, 99, ... 2).
- if (segments.length > 98) {
- throw new exceptions_1.BaseException("'" + route + "' has more than the maximum supported number of segments.");
- }
- var limit = segments.length - 1;
- for (var i = 0; i <= limit; i++) {
- var segment = segments[i], match;
- if (lang_1.isPresent(match = lang_1.RegExpWrapper.firstMatch(paramMatcher, segment))) {
- results.push(new DynamicSegment(match[1]));
- specificity += (100 - i);
- }
- else if (lang_1.isPresent(match = lang_1.RegExpWrapper.firstMatch(wildcardMatcher, segment))) {
- results.push(new StarSegment(match[1]));
- }
- else if (segment == '...') {
- if (i < limit) {
- throw new exceptions_1.BaseException("Unexpected \"...\" before the end of the path for \"" + route + "\".");
- }
- results.push(new ContinuationSegment());
- }
- else {
- results.push(new StaticSegment(segment));
- specificity += 100 * (100 - i);
- }
- }
- var result = collection_1.StringMapWrapper.create();
- collection_1.StringMapWrapper.set(result, 'segments', results);
- collection_1.StringMapWrapper.set(result, 'specificity', specificity);
- return result;
- }
- // this function is used to determine whether a route config path like `/foo/:id` collides with
- // `/foo/:name`
- function pathDslHash(segments) {
- return segments.map(function (segment) {
- if (segment instanceof StarSegment) {
- return '*';
- }
- else if (segment instanceof ContinuationSegment) {
- return '...';
- }
- else if (segment instanceof DynamicSegment) {
- return ':';
- }
- else if (segment instanceof StaticSegment) {
- return segment.path;
- }
- })
- .join('/');
- }
- function splitBySlash(url) {
- return url.split('/');
- }
- var RESERVED_CHARS = lang_1.RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
- function assertPath(path) {
- if (lang_1.StringWrapper.contains(path, '#')) {
- throw new exceptions_1.BaseException("Path \"" + path + "\" should not include \"#\". Use \"HashLocationStrategy\" instead.");
- }
- var illegalCharacter = lang_1.RegExpWrapper.firstMatch(RESERVED_CHARS, path);
- if (lang_1.isPresent(illegalCharacter)) {
- throw new exceptions_1.BaseException("Path \"" + path + "\" contains \"" + illegalCharacter[0] + "\" which is not allowed in a route config.");
- }
- }
- /**
- * Parses a URL string using a given matcher DSL, and generates URLs from param maps
- */
- var PathRecognizer = (function () {
- function PathRecognizer(path) {
- this.path = path;
- this.terminal = true;
- assertPath(path);
- var parsed = parsePathString(path);
- this._segments = parsed['segments'];
- this.specificity = parsed['specificity'];
- this.hash = pathDslHash(this._segments);
- var lastSegment = this._segments[this._segments.length - 1];
- this.terminal = !(lastSegment instanceof ContinuationSegment);
- }
- PathRecognizer.prototype.recognize = function (beginningSegment) {
- var nextSegment = beginningSegment;
- var currentSegment;
- var positionalParams = {};
- var captured = [];
- for (var i = 0; i < this._segments.length; i += 1) {
- var segment = this._segments[i];
- currentSegment = nextSegment;
- if (segment instanceof ContinuationSegment) {
- break;
- }
- if (lang_1.isPresent(currentSegment)) {
- captured.push(currentSegment.path);
- // the star segment consumes all of the remaining URL, including matrix params
- if (segment instanceof StarSegment) {
- positionalParams[segment.name] = currentSegment.toString();
- nextSegment = null;
- break;
- }
- if (segment instanceof DynamicSegment) {
- positionalParams[segment.name] = currentSegment.path;
- }
- else if (!segment.match(currentSegment.path)) {
- return null;
- }
- nextSegment = currentSegment.child;
- }
- else if (!segment.match('')) {
- return null;
- }
- }
- if (this.terminal && lang_1.isPresent(nextSegment)) {
- return null;
- }
- var urlPath = captured.join('/');
- var auxiliary;
- var urlParams;
- var allParams;
- if (lang_1.isPresent(currentSegment)) {
- // If this is the root component, read query params. Otherwise, read matrix params.
- var paramsSegment = beginningSegment instanceof url_parser_1.RootUrl ? beginningSegment : currentSegment;
- allParams = lang_1.isPresent(paramsSegment.params) ?
- collection_1.StringMapWrapper.merge(paramsSegment.params, positionalParams) :
- positionalParams;
- urlParams = url_parser_1.serializeParams(paramsSegment.params);
- auxiliary = currentSegment.auxiliary;
- }
- else {
- allParams = positionalParams;
- auxiliary = [];
- urlParams = [];
- }
- return { urlPath: urlPath, urlParams: urlParams, allParams: allParams, auxiliary: auxiliary, nextSegment: nextSegment };
- };
- PathRecognizer.prototype.generate = function (params) {
- var paramTokens = new TouchMap(params);
- var path = [];
- for (var i = 0; i < this._segments.length; i++) {
- var segment = this._segments[i];
- if (!(segment instanceof ContinuationSegment)) {
- path.push(segment.generate(paramTokens));
- }
- }
- var urlPath = path.join('/');
- var nonPositionalParams = paramTokens.getUnused();
- var urlParams = url_parser_1.serializeParams(nonPositionalParams);
- return { urlPath: urlPath, urlParams: urlParams };
- };
- return PathRecognizer;
- })();
- exports.PathRecognizer = PathRecognizer;
- /***/ },
- /* 231 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- /**
- * This class represents a parsed URL
- */
- var Url = (function () {
- function Url(path, child, auxiliary, params) {
- if (child === void 0) { child = null; }
- if (auxiliary === void 0) { auxiliary = lang_1.CONST_EXPR([]); }
- if (params === void 0) { params = null; }
- this.path = path;
- this.child = child;
- this.auxiliary = auxiliary;
- this.params = params;
- }
- Url.prototype.toString = function () {
- return this.path + this._matrixParamsToString() + this._auxToString() + this._childString();
- };
- Url.prototype.segmentToString = function () { return this.path + this._matrixParamsToString(); };
- /** @internal */
- Url.prototype._auxToString = function () {
- return this.auxiliary.length > 0 ?
- ('(' + this.auxiliary.map(function (sibling) { return sibling.toString(); }).join('//') + ')') :
- '';
- };
- Url.prototype._matrixParamsToString = function () {
- if (lang_1.isBlank(this.params)) {
- return '';
- }
- return ';' + serializeParams(this.params).join(';');
- };
- /** @internal */
- Url.prototype._childString = function () { return lang_1.isPresent(this.child) ? ('/' + this.child.toString()) : ''; };
- return Url;
- })();
- exports.Url = Url;
- var RootUrl = (function (_super) {
- __extends(RootUrl, _super);
- function RootUrl(path, child, auxiliary, params) {
- if (child === void 0) { child = null; }
- if (auxiliary === void 0) { auxiliary = lang_1.CONST_EXPR([]); }
- if (params === void 0) { params = null; }
- _super.call(this, path, child, auxiliary, params);
- }
- RootUrl.prototype.toString = function () {
- return this.path + this._auxToString() + this._childString() + this._queryParamsToString();
- };
- RootUrl.prototype.segmentToString = function () { return this.path + this._queryParamsToString(); };
- RootUrl.prototype._queryParamsToString = function () {
- if (lang_1.isBlank(this.params)) {
- return '';
- }
- return '?' + serializeParams(this.params).join('&');
- };
- return RootUrl;
- })(Url);
- exports.RootUrl = RootUrl;
- function pathSegmentsToUrl(pathSegments) {
- var url = new Url(pathSegments[pathSegments.length - 1]);
- for (var i = pathSegments.length - 2; i >= 0; i -= 1) {
- url = new Url(pathSegments[i], url);
- }
- return url;
- }
- exports.pathSegmentsToUrl = pathSegmentsToUrl;
- var SEGMENT_RE = lang_1.RegExpWrapper.create('^[^\\/\\(\\)\\?;=&#]+');
- function matchUrlSegment(str) {
- var match = lang_1.RegExpWrapper.firstMatch(SEGMENT_RE, str);
- return lang_1.isPresent(match) ? match[0] : '';
- }
- var UrlParser = (function () {
- function UrlParser() {
- }
- UrlParser.prototype.peekStartsWith = function (str) { return this._remaining.startsWith(str); };
- UrlParser.prototype.capture = function (str) {
- if (!this._remaining.startsWith(str)) {
- throw new exceptions_1.BaseException("Expected \"" + str + "\".");
- }
- this._remaining = this._remaining.substring(str.length);
- };
- UrlParser.prototype.parse = function (url) {
- this._remaining = url;
- if (url == '' || url == '/') {
- return new Url('');
- }
- return this.parseRoot();
- };
- // segment + (aux segments) + (query params)
- UrlParser.prototype.parseRoot = function () {
- if (this.peekStartsWith('/')) {
- this.capture('/');
- }
- var path = matchUrlSegment(this._remaining);
- this.capture(path);
- var aux = [];
- if (this.peekStartsWith('(')) {
- aux = this.parseAuxiliaryRoutes();
- }
- if (this.peekStartsWith(';')) {
- // TODO: should these params just be dropped?
- this.parseMatrixParams();
- }
- var child = null;
- if (this.peekStartsWith('/') && !this.peekStartsWith('//')) {
- this.capture('/');
- child = this.parseSegment();
- }
- var queryParams = null;
- if (this.peekStartsWith('?')) {
- queryParams = this.parseQueryParams();
- }
- return new RootUrl(path, child, aux, queryParams);
- };
- // segment + (matrix params) + (aux segments)
- UrlParser.prototype.parseSegment = function () {
- if (this._remaining.length == 0) {
- return null;
- }
- if (this.peekStartsWith('/')) {
- this.capture('/');
- }
- var path = matchUrlSegment(this._remaining);
- this.capture(path);
- var matrixParams = null;
- if (this.peekStartsWith(';')) {
- matrixParams = this.parseMatrixParams();
- }
- var aux = [];
- if (this.peekStartsWith('(')) {
- aux = this.parseAuxiliaryRoutes();
- }
- var child = null;
- if (this.peekStartsWith('/') && !this.peekStartsWith('//')) {
- this.capture('/');
- child = this.parseSegment();
- }
- return new Url(path, child, aux, matrixParams);
- };
- UrlParser.prototype.parseQueryParams = function () {
- var params = {};
- this.capture('?');
- this.parseParam(params);
- while (this._remaining.length > 0 && this.peekStartsWith('&')) {
- this.capture('&');
- this.parseParam(params);
- }
- return params;
- };
- UrlParser.prototype.parseMatrixParams = function () {
- var params = {};
- while (this._remaining.length > 0 && this.peekStartsWith(';')) {
- this.capture(';');
- this.parseParam(params);
- }
- return params;
- };
- UrlParser.prototype.parseParam = function (params) {
- var key = matchUrlSegment(this._remaining);
- if (lang_1.isBlank(key)) {
- return;
- }
- this.capture(key);
- var value = true;
- if (this.peekStartsWith('=')) {
- this.capture('=');
- var valueMatch = matchUrlSegment(this._remaining);
- if (lang_1.isPresent(valueMatch)) {
- value = valueMatch;
- this.capture(value);
- }
- }
- params[key] = value;
- };
- UrlParser.prototype.parseAuxiliaryRoutes = function () {
- var routes = [];
- this.capture('(');
- while (!this.peekStartsWith(')') && this._remaining.length > 0) {
- routes.push(this.parseSegment());
- if (this.peekStartsWith('//')) {
- this.capture('//');
- }
- }
- this.capture(')');
- return routes;
- };
- return UrlParser;
- })();
- exports.UrlParser = UrlParser;
- exports.parser = new UrlParser();
- function serializeParams(paramMap) {
- var params = [];
- if (lang_1.isPresent(paramMap)) {
- collection_1.StringMapWrapper.forEach(paramMap, function (value, key) {
- if (value == true) {
- params.push(key);
- }
- else {
- params.push(key + '=' + value);
- }
- });
- }
- return params;
- }
- exports.serializeParams = serializeParams;
- /***/ },
- /* 232 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var collection_1 = __webpack_require__(12);
- var async_1 = __webpack_require__(60);
- var route_recognizer_1 = __webpack_require__(228);
- var route_config_impl_1 = __webpack_require__(227);
- var async_route_handler_1 = __webpack_require__(233);
- var sync_route_handler_1 = __webpack_require__(234);
- /**
- * `ComponentRecognizer` is responsible for recognizing routes for a single component.
- * It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
- * components.
- */
- var ComponentRecognizer = (function () {
- function ComponentRecognizer() {
- this.names = new collection_1.Map();
- // map from name to recognizer
- this.auxNames = new collection_1.Map();
- // map from starting path to recognizer
- this.auxRoutes = new collection_1.Map();
- // TODO: optimize this into a trie
- this.matchers = [];
- this.defaultRoute = null;
- }
- /**
- * returns whether or not the config is terminal
- */
- ComponentRecognizer.prototype.config = function (config) {
- var handler;
- if (lang_1.isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) {
- var suggestedName = config.name[0].toUpperCase() + config.name.substring(1);
- throw new exceptions_1.BaseException("Route \"" + config.path + "\" with name \"" + config.name + "\" does not begin with an uppercase letter. Route names should be CamelCase like \"" + suggestedName + "\".");
- }
- if (config instanceof route_config_impl_1.AuxRoute) {
- handler = new sync_route_handler_1.SyncRouteHandler(config.component, config.data);
- var path = config.path.startsWith('/') ? config.path.substring(1) : config.path;
- var recognizer = new route_recognizer_1.RouteRecognizer(config.path, handler);
- this.auxRoutes.set(path, recognizer);
- if (lang_1.isPresent(config.name)) {
- this.auxNames.set(config.name, recognizer);
- }
- return recognizer.terminal;
- }
- var useAsDefault = false;
- if (config instanceof route_config_impl_1.Redirect) {
- var redirector = new route_recognizer_1.RedirectRecognizer(config.path, config.redirectTo);
- this._assertNoHashCollision(redirector.hash, config.path);
- this.matchers.push(redirector);
- return true;
- }
- if (config instanceof route_config_impl_1.Route) {
- handler = new sync_route_handler_1.SyncRouteHandler(config.component, config.data);
- useAsDefault = lang_1.isPresent(config.useAsDefault) && config.useAsDefault;
- }
- else if (config instanceof route_config_impl_1.AsyncRoute) {
- handler = new async_route_handler_1.AsyncRouteHandler(config.loader, config.data);
- useAsDefault = lang_1.isPresent(config.useAsDefault) && config.useAsDefault;
- }
- var recognizer = new route_recognizer_1.RouteRecognizer(config.path, handler);
- this._assertNoHashCollision(recognizer.hash, config.path);
- if (useAsDefault) {
- if (lang_1.isPresent(this.defaultRoute)) {
- throw new exceptions_1.BaseException("Only one route can be default");
- }
- this.defaultRoute = recognizer;
- }
- this.matchers.push(recognizer);
- if (lang_1.isPresent(config.name)) {
- this.names.set(config.name, recognizer);
- }
- return recognizer.terminal;
- };
- ComponentRecognizer.prototype._assertNoHashCollision = function (hash, path) {
- this.matchers.forEach(function (matcher) {
- if (hash == matcher.hash) {
- throw new exceptions_1.BaseException("Configuration '" + path + "' conflicts with existing route '" + matcher.path + "'");
- }
- });
- };
- /**
- * Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route.
- */
- ComponentRecognizer.prototype.recognize = function (urlParse) {
- var solutions = [];
- this.matchers.forEach(function (routeRecognizer) {
- var pathMatch = routeRecognizer.recognize(urlParse);
- if (lang_1.isPresent(pathMatch)) {
- solutions.push(pathMatch);
- }
- });
- return solutions;
- };
- ComponentRecognizer.prototype.recognizeAuxiliary = function (urlParse) {
- var routeRecognizer = this.auxRoutes.get(urlParse.path);
- if (lang_1.isPresent(routeRecognizer)) {
- return [routeRecognizer.recognize(urlParse)];
- }
- return [async_1.PromiseWrapper.resolve(null)];
- };
- ComponentRecognizer.prototype.hasRoute = function (name) { return this.names.has(name); };
- ComponentRecognizer.prototype.componentLoaded = function (name) {
- return this.hasRoute(name) && lang_1.isPresent(this.names.get(name).handler.componentType);
- };
- ComponentRecognizer.prototype.loadComponent = function (name) {
- return this.names.get(name).handler.resolveComponentType();
- };
- ComponentRecognizer.prototype.generate = function (name, params) {
- var pathRecognizer = this.names.get(name);
- if (lang_1.isBlank(pathRecognizer)) {
- return null;
- }
- return pathRecognizer.generate(params);
- };
- ComponentRecognizer.prototype.generateAuxiliary = function (name, params) {
- var pathRecognizer = this.auxNames.get(name);
- if (lang_1.isBlank(pathRecognizer)) {
- return null;
- }
- return pathRecognizer.generate(params);
- };
- return ComponentRecognizer;
- })();
- exports.ComponentRecognizer = ComponentRecognizer;
- /***/ },
- /* 233 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var instruction_1 = __webpack_require__(229);
- var AsyncRouteHandler = (function () {
- function AsyncRouteHandler(_loader, data) {
- if (data === void 0) { data = null; }
- this._loader = _loader;
- /** @internal */
- this._resolvedComponent = null;
- this.data = lang_1.isPresent(data) ? new instruction_1.RouteData(data) : instruction_1.BLANK_ROUTE_DATA;
- }
- AsyncRouteHandler.prototype.resolveComponentType = function () {
- var _this = this;
- if (lang_1.isPresent(this._resolvedComponent)) {
- return this._resolvedComponent;
- }
- return this._resolvedComponent = this._loader().then(function (componentType) {
- _this.componentType = componentType;
- return componentType;
- });
- };
- return AsyncRouteHandler;
- })();
- exports.AsyncRouteHandler = AsyncRouteHandler;
- /***/ },
- /* 234 */
- /***/ function(module, exports, __webpack_require__) {
- var async_1 = __webpack_require__(60);
- var lang_1 = __webpack_require__(5);
- var instruction_1 = __webpack_require__(229);
- var SyncRouteHandler = (function () {
- function SyncRouteHandler(componentType, data) {
- this.componentType = componentType;
- /** @internal */
- this._resolvedComponent = null;
- this._resolvedComponent = async_1.PromiseWrapper.resolve(componentType);
- this.data = lang_1.isPresent(data) ? new instruction_1.RouteData(data) : instruction_1.BLANK_ROUTE_DATA;
- }
- SyncRouteHandler.prototype.resolveComponentType = function () { return this._resolvedComponent; };
- return SyncRouteHandler;
- })();
- exports.SyncRouteHandler = SyncRouteHandler;
- /***/ },
- /* 235 */
- /***/ function(module, exports, __webpack_require__) {
- var route_config_decorator_1 = __webpack_require__(236);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- /**
- * Given a JS Object that represents a route config, returns a corresponding Route, AsyncRoute,
- * AuxRoute or Redirect object.
- *
- * Also wraps an AsyncRoute's loader function to add the loaded component's route config to the
- * `RouteRegistry`.
- */
- function normalizeRouteConfig(config, registry) {
- if (config instanceof route_config_decorator_1.AsyncRoute) {
- var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry);
- return new route_config_decorator_1.AsyncRoute({
- path: config.path,
- loader: wrappedLoader,
- name: config.name,
- data: config.data,
- useAsDefault: config.useAsDefault
- });
- }
- if (config instanceof route_config_decorator_1.Route || config instanceof route_config_decorator_1.Redirect || config instanceof route_config_decorator_1.AuxRoute) {
- return config;
- }
- if ((+!!config.component) + (+!!config.redirectTo) + (+!!config.loader) != 1) {
- throw new exceptions_1.BaseException("Route config should contain exactly one \"component\", \"loader\", or \"redirectTo\" property.");
- }
- if (config.as && config.name) {
- throw new exceptions_1.BaseException("Route config should contain exactly one \"as\" or \"name\" property.");
- }
- if (config.as) {
- config.name = config.as;
- }
- if (config.loader) {
- var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry);
- return new route_config_decorator_1.AsyncRoute({
- path: config.path,
- loader: wrappedLoader,
- name: config.name,
- useAsDefault: config.useAsDefault
- });
- }
- if (config.aux) {
- return new route_config_decorator_1.AuxRoute({ path: config.aux, component: config.component, name: config.name });
- }
- if (config.component) {
- if (typeof config.component == 'object') {
- var componentDefinitionObject = config.component;
- if (componentDefinitionObject.type == 'constructor') {
- return new route_config_decorator_1.Route({
- path: config.path,
- component: componentDefinitionObject.constructor,
- name: config.name,
- data: config.data,
- useAsDefault: config.useAsDefault
- });
- }
- else if (componentDefinitionObject.type == 'loader') {
- return new route_config_decorator_1.AsyncRoute({
- path: config.path,
- loader: componentDefinitionObject.loader,
- name: config.name,
- useAsDefault: config.useAsDefault
- });
- }
- else {
- throw new exceptions_1.BaseException("Invalid component type \"" + componentDefinitionObject.type + "\". Valid types are \"constructor\" and \"loader\".");
- }
- }
- return new route_config_decorator_1.Route(config);
- }
- if (config.redirectTo) {
- return new route_config_decorator_1.Redirect({ path: config.path, redirectTo: config.redirectTo });
- }
- return config;
- }
- exports.normalizeRouteConfig = normalizeRouteConfig;
- function wrapLoaderToReconfigureRegistry(loader, registry) {
- return function () {
- return loader().then(function (componentType) {
- registry.configFromComponent(componentType);
- return componentType;
- });
- };
- }
- function assertComponentExists(component, path) {
- if (!lang_1.isType(component)) {
- throw new exceptions_1.BaseException("Component for route \"" + path + "\" is not defined, or is not a class.");
- }
- }
- exports.assertComponentExists = assertComponentExists;
- /***/ },
- /* 236 */
- /***/ function(module, exports, __webpack_require__) {
- var route_config_impl_1 = __webpack_require__(227);
- var decorators_1 = __webpack_require__(9);
- var route_config_impl_2 = __webpack_require__(227);
- exports.Route = route_config_impl_2.Route;
- exports.Redirect = route_config_impl_2.Redirect;
- exports.AuxRoute = route_config_impl_2.AuxRoute;
- exports.AsyncRoute = route_config_impl_2.AsyncRoute;
- // Copied from RouteConfig in route_config_impl.
- /**
- * The `RouteConfig` decorator defines routes for a given component.
- *
- * It takes an array of {@link RouteDefinition}s.
- */
- exports.RouteConfig = decorators_1.makeDecorator(route_config_impl_1.RouteConfig);
- /***/ },
- /* 237 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var location_strategy_1 = __webpack_require__(238);
- var async_1 = __webpack_require__(60);
- var core_1 = __webpack_require__(2);
- /**
- * `Location` is a service that applications can use to interact with a browser's URL.
- * Depending on which {@link LocationStrategy} is used, `Location` will either persist
- * to the URL's path or the URL's hash segment.
- *
- * Note: it's better to use {@link Router#navigate} service to trigger route changes. Use
- * `Location` only if you need to interact with or create normalized URLs outside of
- * routing.
- *
- * `Location` is responsible for normalizing the URL against the application's base href.
- * A normalized URL is absolute from the URL host, includes the application's base href, and has no
- * trailing slash:
- * - `/my/app/user/123` is normalized
- * - `my/app/user/123` **is not** normalized
- * - `/my/app/user/123/` **is not** normalized
- *
- * ### Example
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {
- * ROUTER_DIRECTIVES,
- * ROUTER_PROVIDERS,
- * RouteConfig,
- * Location
- * } from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * constructor(location: Location) {
- * location.go('/foo');
- * }
- * }
- *
- * bootstrap(AppCmp, [ROUTER_PROVIDERS]);
- * ```
- */
- var Location = (function () {
- function Location(platformStrategy) {
- var _this = this;
- this.platformStrategy = platformStrategy;
- /** @internal */
- this._subject = new async_1.EventEmitter();
- var browserBaseHref = this.platformStrategy.getBaseHref();
- this._baseHref = stripTrailingSlash(stripIndexHtml(browserBaseHref));
- this.platformStrategy.onPopState(function (ev) {
- async_1.ObservableWrapper.callEmit(_this._subject, { 'url': _this.path(), 'pop': true, 'type': ev.type });
- });
- }
- /**
- * Returns the normalized URL path.
- */
- Location.prototype.path = function () { return this.normalize(this.platformStrategy.path()); };
- /**
- * Given a string representing a URL, returns the normalized URL path without leading or
- * trailing slashes
- */
- Location.prototype.normalize = function (url) {
- return stripTrailingSlash(_stripBaseHref(this._baseHref, stripIndexHtml(url)));
- };
- /**
- * Given a string representing a URL, returns the platform-specific external URL path.
- * If the given URL doesn't begin with a leading slash (`'/'`), this method adds one
- * before normalizing. This method will also add a hash if `HashLocationStrategy` is
- * used, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use.
- */
- Location.prototype.prepareExternalUrl = function (url) {
- if (url.length > 0 && !url.startsWith('/')) {
- url = '/' + url;
- }
- return this.platformStrategy.prepareExternalUrl(url);
- };
- // TODO: rename this method to pushState
- /**
- * Changes the browsers URL to the normalized version of the given URL, and pushes a
- * new item onto the platform's history.
- */
- Location.prototype.go = function (path, query) {
- if (query === void 0) { query = ''; }
- this.platformStrategy.pushState(null, '', path, query);
- };
- /**
- * Changes the browsers URL to the normalized version of the given URL, and replaces
- * the top item on the platform's history stack.
- */
- Location.prototype.replaceState = function (path, query) {
- if (query === void 0) { query = ''; }
- this.platformStrategy.replaceState(null, '', path, query);
- };
- /**
- * Navigates forward in the platform's history.
- */
- Location.prototype.forward = function () { this.platformStrategy.forward(); };
- /**
- * Navigates back in the platform's history.
- */
- Location.prototype.back = function () { this.platformStrategy.back(); };
- /**
- * Subscribe to the platform's `popState` events.
- */
- Location.prototype.subscribe = function (onNext, onThrow, onReturn) {
- if (onThrow === void 0) { onThrow = null; }
- if (onReturn === void 0) { onReturn = null; }
- return async_1.ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);
- };
- Location = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [location_strategy_1.LocationStrategy])
- ], Location);
- return Location;
- })();
- exports.Location = Location;
- function _stripBaseHref(baseHref, url) {
- if (baseHref.length > 0 && url.startsWith(baseHref)) {
- return url.substring(baseHref.length);
- }
- return url;
- }
- function stripIndexHtml(url) {
- if (/\/index.html$/g.test(url)) {
- // '/index.html'.length == 11
- return url.substring(0, url.length - 11);
- }
- return url;
- }
- function stripTrailingSlash(url) {
- if (/\/$/g.test(url)) {
- url = url.substring(0, url.length - 1);
- }
- return url;
- }
- /***/ },
- /* 238 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var core_1 = __webpack_require__(2);
- /**
- * `LocationStrategy` is responsible for representing and reading route state
- * from the browser's URL. Angular provides two strategies:
- * {@link HashLocationStrategy} (default) and {@link PathLocationStrategy}.
- *
- * This is used under the hood of the {@link Location} service.
- *
- * Applications should use the {@link Router} or {@link Location} services to
- * interact with application route state.
- *
- * For instance, {@link HashLocationStrategy} produces URLs like
- * `http://example.com#/foo`, and {@link PathLocationStrategy} produces
- * `http://example.com/foo` as an equivalent URL.
- *
- * See these two classes for more.
- */
- var LocationStrategy = (function () {
- function LocationStrategy() {
- }
- return LocationStrategy;
- })();
- exports.LocationStrategy = LocationStrategy;
- /**
- * The `APP_BASE_HREF` token represents the base href to be used with the
- * {@link PathLocationStrategy}.
- *
- * If you're using {@link PathLocationStrategy}, you must provide a provider to a string
- * representing the URL prefix that should be preserved when generating and recognizing
- * URLs.
- *
- * ### Example
- *
- * ```
- * import {Component} from 'angular2/core';
- * import {ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * // ...
- * }
- *
- * bootstrap(AppCmp, [
- * ROUTER_PROVIDERS,
- * PathLocationStrategy,
- * provide(APP_BASE_HREF, {useValue: '/my/app'})
- * ]);
- * ```
- */
- exports.APP_BASE_HREF = lang_1.CONST_EXPR(new core_1.OpaqueToken('appBaseHref'));
- function normalizeQueryParams(params) {
- return (params.length > 0 && params.substring(0, 1) != '?') ? ('?' + params) : params;
- }
- exports.normalizeQueryParams = normalizeQueryParams;
- function joinWithSlash(start, end) {
- if (start.length == 0) {
- return end;
- }
- if (end.length == 0) {
- return start;
- }
- var slashes = 0;
- if (start.endsWith('/')) {
- slashes++;
- }
- if (end.startsWith('/')) {
- slashes++;
- }
- if (slashes == 2) {
- return start + end.substring(1);
- }
- if (slashes == 1) {
- return start + end;
- }
- return start + '/' + end;
- }
- exports.joinWithSlash = joinWithSlash;
- /***/ },
- /* 239 */
- /***/ function(module, exports, __webpack_require__) {
- var lang_1 = __webpack_require__(5);
- var lifecycle_annotations_impl_1 = __webpack_require__(240);
- var reflection_1 = __webpack_require__(16);
- function hasLifecycleHook(e, type) {
- if (!(type instanceof lang_1.Type))
- return false;
- return e.name in type.prototype;
- }
- exports.hasLifecycleHook = hasLifecycleHook;
- function getCanActivateHook(type) {
- var annotations = reflection_1.reflector.annotations(type);
- for (var i = 0; i < annotations.length; i += 1) {
- var annotation = annotations[i];
- if (annotation instanceof lifecycle_annotations_impl_1.CanActivate) {
- return annotation.fn;
- }
- }
- return null;
- }
- exports.getCanActivateHook = getCanActivateHook;
- /***/ },
- /* 240 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var lang_1 = __webpack_require__(5);
- var RouteLifecycleHook = (function () {
- function RouteLifecycleHook(name) {
- this.name = name;
- }
- RouteLifecycleHook = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [String])
- ], RouteLifecycleHook);
- return RouteLifecycleHook;
- })();
- exports.RouteLifecycleHook = RouteLifecycleHook;
- var CanActivate = (function () {
- function CanActivate(fn) {
- this.fn = fn;
- }
- CanActivate = __decorate([
- lang_1.CONST(),
- __metadata('design:paramtypes', [Function])
- ], CanActivate);
- return CanActivate;
- })();
- exports.CanActivate = CanActivate;
- exports.routerCanReuse = lang_1.CONST_EXPR(new RouteLifecycleHook("routerCanReuse"));
- exports.routerCanDeactivate = lang_1.CONST_EXPR(new RouteLifecycleHook("routerCanDeactivate"));
- exports.routerOnActivate = lang_1.CONST_EXPR(new RouteLifecycleHook("routerOnActivate"));
- exports.routerOnReuse = lang_1.CONST_EXPR(new RouteLifecycleHook("routerOnReuse"));
- exports.routerOnDeactivate = lang_1.CONST_EXPR(new RouteLifecycleHook("routerOnDeactivate"));
- /***/ },
- /* 241 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var async_1 = __webpack_require__(60);
- var collection_1 = __webpack_require__(12);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var core_1 = __webpack_require__(2);
- var routerMod = __webpack_require__(225);
- var instruction_1 = __webpack_require__(229);
- var hookMod = __webpack_require__(242);
- var route_lifecycle_reflector_1 = __webpack_require__(239);
- var _resolveToTrue = async_1.PromiseWrapper.resolve(true);
- /**
- * A router outlet is a placeholder that Angular dynamically fills based on the application's route.
- *
- * ## Use
- *
- * ```
- * <router-outlet></router-outlet>
- * ```
- */
- var RouterOutlet = (function () {
- function RouterOutlet(_elementRef, _loader, _parentRouter, nameAttr) {
- this._elementRef = _elementRef;
- this._loader = _loader;
- this._parentRouter = _parentRouter;
- this.name = null;
- this._componentRef = null;
- this._currentInstruction = null;
- if (lang_1.isPresent(nameAttr)) {
- this.name = nameAttr;
- this._parentRouter.registerAuxOutlet(this);
- }
- else {
- this._parentRouter.registerPrimaryOutlet(this);
- }
- }
- /**
- * Called by the Router to instantiate a new component during the commit phase of a navigation.
- * This method in turn is responsible for calling the `routerOnActivate` hook of its child.
- */
- RouterOutlet.prototype.activate = function (nextInstruction) {
- var _this = this;
- var previousInstruction = this._currentInstruction;
- this._currentInstruction = nextInstruction;
- var componentType = nextInstruction.componentType;
- var childRouter = this._parentRouter.childRouter(componentType);
- var providers = core_1.Injector.resolve([
- core_1.provide(instruction_1.RouteData, { useValue: nextInstruction.routeData }),
- core_1.provide(instruction_1.RouteParams, { useValue: new instruction_1.RouteParams(nextInstruction.params) }),
- core_1.provide(routerMod.Router, { useValue: childRouter })
- ]);
- return this._loader.loadNextToLocation(componentType, this._elementRef, providers)
- .then(function (componentRef) {
- _this._componentRef = componentRef;
- if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnActivate, componentType)) {
- return _this._componentRef.instance
- .routerOnActivate(nextInstruction, previousInstruction);
- }
- });
- };
- /**
- * Called by the {@link Router} during the commit phase of a navigation when an outlet
- * reuses a component between different routes.
- * This method in turn is responsible for calling the `routerOnReuse` hook of its child.
- */
- RouterOutlet.prototype.reuse = function (nextInstruction) {
- var previousInstruction = this._currentInstruction;
- this._currentInstruction = nextInstruction;
- if (lang_1.isBlank(this._componentRef)) {
- throw new exceptions_1.BaseException("Cannot reuse an outlet that does not contain a component.");
- }
- return async_1.PromiseWrapper.resolve(route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnReuse, this._currentInstruction.componentType) ?
- this._componentRef.instance
- .routerOnReuse(nextInstruction, previousInstruction) :
- true);
- };
- /**
- * Called by the {@link Router} when an outlet disposes of a component's contents.
- * This method in turn is responsible for calling the `routerOnDeactivate` hook of its child.
- */
- RouterOutlet.prototype.deactivate = function (nextInstruction) {
- var _this = this;
- var next = _resolveToTrue;
- if (lang_1.isPresent(this._componentRef) && lang_1.isPresent(this._currentInstruction) &&
- route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnDeactivate, this._currentInstruction.componentType)) {
- next = async_1.PromiseWrapper.resolve(this._componentRef.instance
- .routerOnDeactivate(nextInstruction, this._currentInstruction));
- }
- return next.then(function (_) {
- if (lang_1.isPresent(_this._componentRef)) {
- _this._componentRef.dispose();
- _this._componentRef = null;
- }
- });
- };
- /**
- * Called by the {@link Router} during recognition phase of a navigation.
- *
- * If this resolves to `false`, the given navigation is cancelled.
- *
- * This method delegates to the child component's `routerCanDeactivate` hook if it exists,
- * and otherwise resolves to true.
- */
- RouterOutlet.prototype.routerCanDeactivate = function (nextInstruction) {
- if (lang_1.isBlank(this._currentInstruction)) {
- return _resolveToTrue;
- }
- if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerCanDeactivate, this._currentInstruction.componentType)) {
- return async_1.PromiseWrapper.resolve(this._componentRef.instance
- .routerCanDeactivate(nextInstruction, this._currentInstruction));
- }
- return _resolveToTrue;
- };
- /**
- * Called by the {@link Router} during recognition phase of a navigation.
- *
- * If the new child component has a different Type than the existing child component,
- * this will resolve to `false`. You can't reuse an old component when the new component
- * is of a different Type.
- *
- * Otherwise, this method delegates to the child component's `routerCanReuse` hook if it exists,
- * or resolves to true if the hook is not present.
- */
- RouterOutlet.prototype.routerCanReuse = function (nextInstruction) {
- var result;
- if (lang_1.isBlank(this._currentInstruction) ||
- this._currentInstruction.componentType != nextInstruction.componentType) {
- result = false;
- }
- else if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerCanReuse, this._currentInstruction.componentType)) {
- result = this._componentRef.instance
- .routerCanReuse(nextInstruction, this._currentInstruction);
- }
- else {
- result = nextInstruction == this._currentInstruction ||
- (lang_1.isPresent(nextInstruction.params) && lang_1.isPresent(this._currentInstruction.params) &&
- collection_1.StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params));
- }
- return async_1.PromiseWrapper.resolve(result);
- };
- RouterOutlet = __decorate([
- core_1.Directive({ selector: 'router-outlet' }),
- __param(3, core_1.Attribute('name')),
- __metadata('design:paramtypes', [core_1.ElementRef, core_1.DynamicComponentLoader, routerMod.Router, String])
- ], RouterOutlet);
- return RouterOutlet;
- })();
- exports.RouterOutlet = RouterOutlet;
- /***/ },
- /* 242 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * This indirection is needed to free up Component, etc symbols in the public API
- * to be used by the decorator versions of these annotations.
- */
- var decorators_1 = __webpack_require__(9);
- var lifecycle_annotations_impl_1 = __webpack_require__(240);
- var lifecycle_annotations_impl_2 = __webpack_require__(240);
- exports.routerCanReuse = lifecycle_annotations_impl_2.routerCanReuse;
- exports.routerCanDeactivate = lifecycle_annotations_impl_2.routerCanDeactivate;
- exports.routerOnActivate = lifecycle_annotations_impl_2.routerOnActivate;
- exports.routerOnReuse = lifecycle_annotations_impl_2.routerOnReuse;
- exports.routerOnDeactivate = lifecycle_annotations_impl_2.routerOnDeactivate;
- /**
- * Defines route lifecycle hook `CanActivate`, which is called by the router to determine
- * if a component can be instantiated as part of a navigation.
- *
- * <aside class="is-right">
- * Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
- * This is because the `CanActivate` function is called before the component is instantiated.
- * </aside>
- *
- * The `CanActivate` hook is called with two {@link ComponentInstruction}s as parameters, the first
- * representing the current route being navigated to, and the second parameter representing the
- * previous route or `null`.
- *
- * ```typescript
- * @CanActivate((next, prev) => boolean | Promise<boolean>)
- * ```
- *
- * If `CanActivate` returns or resolves to `false`, the navigation is cancelled.
- * If `CanActivate` throws or rejects, the navigation is also cancelled.
- * If `CanActivate` returns or resolves to `true`, navigation continues, the component is
- * instantiated, and the {@link OnActivate} hook of that component is called if implemented.
- *
- * ### Example
- *
- * {@example router/ts/can_activate/can_activate_example.ts region='canActivate' }
- */
- exports.CanActivate = decorators_1.makeDecorator(lifecycle_annotations_impl_1.CanActivate);
- /***/ },
- /* 243 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var router_1 = __webpack_require__(225);
- var location_1 = __webpack_require__(237);
- /**
- * The RouterLink directive lets you link to specific parts of your app.
- *
- * Consider the following route configuration:
- * ```
- * @RouteConfig([
- * { path: '/user', component: UserCmp, as: 'User' }
- * ]);
- * class MyComp {}
- * ```
- *
- * When linking to this `User` route, you can write:
- *
- * ```
- * <a [routerLink]="['./User']">link to user component</a>
- * ```
- *
- * RouterLink expects the value to be an array of route names, followed by the params
- * for that level of routing. For instance `['/Team', {teamId: 1}, 'User', {userId: 2}]`
- * means that we want to generate a link for the `Team` route with params `{teamId: 1}`,
- * and with a child route `User` with params `{userId: 2}`.
- *
- * The first route name should be prepended with `/`, `./`, or `../`.
- * If the route begins with `/`, the router will look up the route from the root of the app.
- * If the route begins with `./`, the router will instead look in the current component's
- * children for the route. And if the route begins with `../`, the router will look at the
- * current component's parent.
- */
- var RouterLink = (function () {
- function RouterLink(_router, _location) {
- this._router = _router;
- this._location = _location;
- }
- Object.defineProperty(RouterLink.prototype, "isRouteActive", {
- get: function () { return this._router.isRouteActive(this._navigationInstruction); },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(RouterLink.prototype, "routeParams", {
- set: function (changes) {
- this._routeParams = changes;
- this._navigationInstruction = this._router.generate(this._routeParams);
- var navigationHref = this._navigationInstruction.toLinkUrl();
- this.visibleHref = this._location.prepareExternalUrl(navigationHref);
- },
- enumerable: true,
- configurable: true
- });
- RouterLink.prototype.onClick = function () {
- // If no target, or if target is _self, prevent default browser behavior
- if (!lang_1.isString(this.target) || this.target == '_self') {
- this._router.navigateByInstruction(this._navigationInstruction);
- return false;
- }
- return true;
- };
- RouterLink = __decorate([
- core_1.Directive({
- selector: '[routerLink]',
- inputs: ['routeParams: routerLink', 'target: target'],
- host: {
- '(click)': 'onClick()',
- '[attr.href]': 'visibleHref',
- '[class.router-link-active]': 'isRouteActive'
- }
- }),
- __metadata('design:paramtypes', [router_1.Router, location_1.Location])
- ], RouterLink);
- return RouterLink;
- })();
- exports.RouterLink = RouterLink;
- /***/ },
- /* 244 */
- /***/ function(module, exports, __webpack_require__) {
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var dom_adapter_1 = __webpack_require__(178);
- var core_1 = __webpack_require__(2);
- /**
- * `PlatformLocation` encapsulates all of the direct calls to platform APIs.
- * This class should not be used directly by an application developer. Instead, use
- * {@link Location}.
- */
- var PlatformLocation = (function () {
- function PlatformLocation() {
- this._init();
- }
- // This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it
- /** @internal */
- PlatformLocation.prototype._init = function () {
- this._location = dom_adapter_1.DOM.getLocation();
- this._history = dom_adapter_1.DOM.getHistory();
- };
- PlatformLocation.prototype.getBaseHrefFromDOM = function () { return dom_adapter_1.DOM.getBaseHref(); };
- PlatformLocation.prototype.onPopState = function (fn) {
- dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false);
- };
- PlatformLocation.prototype.onHashChange = function (fn) {
- dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('hashchange', fn, false);
- };
- Object.defineProperty(PlatformLocation.prototype, "pathname", {
- get: function () { return this._location.pathname; },
- set: function (newPath) { this._location.pathname = newPath; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PlatformLocation.prototype, "search", {
- get: function () { return this._location.search; },
- enumerable: true,
- configurable: true
- });
- Object.defineProperty(PlatformLocation.prototype, "hash", {
- get: function () { return this._location.hash; },
- enumerable: true,
- configurable: true
- });
- PlatformLocation.prototype.pushState = function (state, title, url) {
- this._history.pushState(state, title, url);
- };
- PlatformLocation.prototype.replaceState = function (state, title, url) {
- this._history.replaceState(state, title, url);
- };
- PlatformLocation.prototype.forward = function () { this._history.forward(); };
- PlatformLocation.prototype.back = function () { this._history.back(); };
- PlatformLocation = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [])
- ], PlatformLocation);
- return PlatformLocation;
- })();
- exports.PlatformLocation = PlatformLocation;
- /***/ },
- /* 245 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var location_strategy_1 = __webpack_require__(238);
- var lang_1 = __webpack_require__(5);
- var platform_location_1 = __webpack_require__(244);
- /**
- * `HashLocationStrategy` is a {@link LocationStrategy} used to configure the
- * {@link Location} service to represent its state in the
- * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax)
- * of the browser's URL.
- *
- * For instance, if you call `location.go('/foo')`, the browser's URL will become
- * `example.com#/foo`.
- *
- * ### Example
- *
- * ```
- * import {Component, provide} from 'angular2/core';
- * import {
- * ROUTER_DIRECTIVES,
- * ROUTER_PROVIDERS,
- * RouteConfig,
- * Location,
- * LocationStrategy,
- * HashLocationStrategy
- * } from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * constructor(location: Location) {
- * location.go('/foo');
- * }
- * }
- *
- * bootstrap(AppCmp, [
- * ROUTER_PROVIDERS,
- * provide(LocationStrategy, {useClass: HashLocationStrategy})
- * ]);
- * ```
- */
- var HashLocationStrategy = (function (_super) {
- __extends(HashLocationStrategy, _super);
- function HashLocationStrategy(_platformLocation, _baseHref) {
- _super.call(this);
- this._platformLocation = _platformLocation;
- this._baseHref = '';
- if (lang_1.isPresent(_baseHref)) {
- this._baseHref = _baseHref;
- }
- }
- HashLocationStrategy.prototype.onPopState = function (fn) {
- this._platformLocation.onPopState(fn);
- this._platformLocation.onHashChange(fn);
- };
- HashLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; };
- HashLocationStrategy.prototype.path = function () {
- // the hash value is always prefixed with a `#`
- // and if it is empty then it will stay empty
- var path = this._platformLocation.hash;
- // Dart will complain if a call to substring is
- // executed with a position value that extends the
- // length of string.
- return (path.length > 0 ? path.substring(1) : path) +
- location_strategy_1.normalizeQueryParams(this._platformLocation.search);
- };
- HashLocationStrategy.prototype.prepareExternalUrl = function (internal) {
- var url = location_strategy_1.joinWithSlash(this._baseHref, internal);
- return url.length > 0 ? ('#' + url) : url;
- };
- HashLocationStrategy.prototype.pushState = function (state, title, path, queryParams) {
- var url = this.prepareExternalUrl(path + location_strategy_1.normalizeQueryParams(queryParams));
- if (url.length == 0) {
- url = this._platformLocation.pathname;
- }
- this._platformLocation.pushState(state, title, url);
- };
- HashLocationStrategy.prototype.replaceState = function (state, title, path, queryParams) {
- var url = this.prepareExternalUrl(path + location_strategy_1.normalizeQueryParams(queryParams));
- if (url.length == 0) {
- url = this._platformLocation.pathname;
- }
- this._platformLocation.replaceState(state, title, url);
- };
- HashLocationStrategy.prototype.forward = function () { this._platformLocation.forward(); };
- HashLocationStrategy.prototype.back = function () { this._platformLocation.back(); };
- HashLocationStrategy = __decorate([
- core_1.Injectable(),
- __param(1, core_1.Optional()),
- __param(1, core_1.Inject(location_strategy_1.APP_BASE_HREF)),
- __metadata('design:paramtypes', [platform_location_1.PlatformLocation, String])
- ], HashLocationStrategy);
- return HashLocationStrategy;
- })(location_strategy_1.LocationStrategy);
- exports.HashLocationStrategy = HashLocationStrategy;
- /***/ },
- /* 246 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var __param = (this && this.__param) || function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
- var core_1 = __webpack_require__(2);
- var lang_1 = __webpack_require__(5);
- var exceptions_1 = __webpack_require__(14);
- var location_strategy_1 = __webpack_require__(238);
- var platform_location_1 = __webpack_require__(244);
- /**
- * `PathLocationStrategy` is a {@link LocationStrategy} used to configure the
- * {@link Location} service to represent its state in the
- * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the
- * browser's URL.
- *
- * `PathLocationStrategy` is the default binding for {@link LocationStrategy}
- * provided in {@link ROUTER_PROVIDERS}.
- *
- * If you're using `PathLocationStrategy`, you must provide a provider for
- * {@link APP_BASE_HREF} to a string representing the URL prefix that should
- * be preserved when generating and recognizing URLs.
- *
- * For instance, if you provide an `APP_BASE_HREF` of `'/my/app'` and call
- * `location.go('/foo')`, the browser's URL will become
- * `example.com/my/app/foo`.
- *
- * ### Example
- *
- * ```
- * import {Component, provide} from 'angular2/core';
- * import {
- * APP_BASE_HREF
- * ROUTER_DIRECTIVES,
- * ROUTER_PROVIDERS,
- * RouteConfig,
- * Location
- * } from 'angular2/router';
- *
- * @Component({directives: [ROUTER_DIRECTIVES]})
- * @RouteConfig([
- * {...},
- * ])
- * class AppCmp {
- * constructor(location: Location) {
- * location.go('/foo');
- * }
- * }
- *
- * bootstrap(AppCmp, [
- * ROUTER_PROVIDERS, // includes binding to PathLocationStrategy
- * provide(APP_BASE_HREF, {useValue: '/my/app'})
- * ]);
- * ```
- */
- var PathLocationStrategy = (function (_super) {
- __extends(PathLocationStrategy, _super);
- function PathLocationStrategy(_platformLocation, href) {
- _super.call(this);
- this._platformLocation = _platformLocation;
- if (lang_1.isBlank(href)) {
- href = this._platformLocation.getBaseHrefFromDOM();
- }
- if (lang_1.isBlank(href)) {
- throw new exceptions_1.BaseException("No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.");
- }
- this._baseHref = href;
- }
- PathLocationStrategy.prototype.onPopState = function (fn) {
- this._platformLocation.onPopState(fn);
- this._platformLocation.onHashChange(fn);
- };
- PathLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; };
- PathLocationStrategy.prototype.prepareExternalUrl = function (internal) { return location_strategy_1.joinWithSlash(this._baseHref, internal); };
- PathLocationStrategy.prototype.path = function () {
- return this._platformLocation.pathname + location_strategy_1.normalizeQueryParams(this._platformLocation.search);
- };
- PathLocationStrategy.prototype.pushState = function (state, title, url, queryParams) {
- var externalUrl = this.prepareExternalUrl(url + location_strategy_1.normalizeQueryParams(queryParams));
- this._platformLocation.pushState(state, title, externalUrl);
- };
- PathLocationStrategy.prototype.replaceState = function (state, title, url, queryParams) {
- var externalUrl = this.prepareExternalUrl(url + location_strategy_1.normalizeQueryParams(queryParams));
- this._platformLocation.replaceState(state, title, externalUrl);
- };
- PathLocationStrategy.prototype.forward = function () { this._platformLocation.forward(); };
- PathLocationStrategy.prototype.back = function () { this._platformLocation.back(); };
- PathLocationStrategy = __decorate([
- core_1.Injectable(),
- __param(1, core_1.Optional()),
- __param(1, core_1.Inject(location_strategy_1.APP_BASE_HREF)),
- __metadata('design:paramtypes', [platform_location_1.PlatformLocation, String])
- ], PathLocationStrategy);
- return PathLocationStrategy;
- })(location_strategy_1.LocationStrategy);
- exports.PathLocationStrategy = PathLocationStrategy;
- /***/ },
- /* 247 */
- /***/ function(module, exports) {
-
- /***/ },
- /* 248 */
- /***/ function(module, exports, __webpack_require__) {
- var compiler_1 = __webpack_require__(147);
- var core_1 = __webpack_require__(2);
- var router_link_transform_1 = __webpack_require__(249);
- var lang_1 = __webpack_require__(5);
- var router_link_transform_2 = __webpack_require__(249);
- exports.RouterLinkTransform = router_link_transform_2.RouterLinkTransform;
- /**
- * Enables the router link DSL.
- *
- * Warning. This feature is experimental and can change.
- *
- * To enable the transformer pass the router link DSL provider to `bootstrap`.
- *
- * ## Example:
- * ```
- * import {bootstrap} from 'angular2/platform/browser';
- * import {ROUTER_LINK_DSL_PROVIDER} from 'angular2/router/router_link_dsl';
- *
- * bootstrap(CustomApp, [ROUTER_LINK_DSL_PROVIDER]);
- * ```
- *
- * The DSL allows you to express router links as follows:
- * ```
- * <a [routerLink]="route:User"> <!-- Same as <a [routerLink]="['User']"> -->
- * <a [routerLink]="route:/User"> <!-- Same as <a [routerLink]="['User']"> -->
- * <a [routerLink]="route:./User"> <!-- Same as <a [routerLink]="['./User']"> -->
- * <a [routerLink]="./User(id: value, name: 'Bob')"> <!-- Same as <a [routerLink]="['./User', {id:
- * value, name: 'Bob'}]"> -->
- * <a [routerLink]="/User/Modal"> <!-- Same as <a [routerLink]="['/User', 'Modal']"> -->
- * <a [routerLink]="User[Modal]"> <!-- Same as <a [routerLink]="['User', ['Modal']]"> -->
- * ```
- */
- exports.ROUTER_LINK_DSL_PROVIDER = lang_1.CONST_EXPR(new core_1.Provider(compiler_1.TEMPLATE_TRANSFORMS, { useClass: router_link_transform_1.RouterLinkTransform, multi: true }));
- /***/ },
- /* 249 */
- /***/ function(module, exports, __webpack_require__) {
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
- var __metadata = (this && this.__metadata) || function (k, v) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
- };
- var compiler_1 = __webpack_require__(147);
- var ast_1 = __webpack_require__(30);
- var exceptions_1 = __webpack_require__(14);
- var core_1 = __webpack_require__(2);
- var parser_1 = __webpack_require__(32);
- /**
- * e.g., './User', 'Modal' in ./User[Modal(param: value)]
- */
- var FixedPart = (function () {
- function FixedPart(value) {
- this.value = value;
- }
- return FixedPart;
- })();
- /**
- * The square bracket
- */
- var AuxiliaryStart = (function () {
- function AuxiliaryStart() {
- }
- return AuxiliaryStart;
- })();
- /**
- * The square bracket
- */
- var AuxiliaryEnd = (function () {
- function AuxiliaryEnd() {
- }
- return AuxiliaryEnd;
- })();
- /**
- * e.g., param:value in ./User[Modal(param: value)]
- */
- var Params = (function () {
- function Params(ast) {
- this.ast = ast;
- }
- return Params;
- })();
- var RouterLinkLexer = (function () {
- function RouterLinkLexer(parser, exp) {
- this.parser = parser;
- this.exp = exp;
- this.index = 0;
- }
- RouterLinkLexer.prototype.tokenize = function () {
- var tokens = [];
- while (this.index < this.exp.length) {
- tokens.push(this._parseToken());
- }
- return tokens;
- };
- RouterLinkLexer.prototype._parseToken = function () {
- var c = this.exp[this.index];
- if (c == '[') {
- this.index++;
- return new AuxiliaryStart();
- }
- else if (c == ']') {
- this.index++;
- return new AuxiliaryEnd();
- }
- else if (c == '(') {
- return this._parseParams();
- }
- else if (c == '/' && this.index !== 0) {
- this.index++;
- return this._parseFixedPart();
- }
- else {
- return this._parseFixedPart();
- }
- };
- RouterLinkLexer.prototype._parseParams = function () {
- var start = this.index;
- for (; this.index < this.exp.length; ++this.index) {
- var c = this.exp[this.index];
- if (c == ')') {
- var paramsContent = this.exp.substring(start + 1, this.index);
- this.index++;
- return new Params(this.parser.parseBinding("{" + paramsContent + "}", null).ast);
- }
- }
- throw new exceptions_1.BaseException("Cannot find ')'");
- };
- RouterLinkLexer.prototype._parseFixedPart = function () {
- var start = this.index;
- var sawNonSlash = false;
- for (; this.index < this.exp.length; ++this.index) {
- var c = this.exp[this.index];
- if (c == '(' || c == '[' || c == ']' || (c == '/' && sawNonSlash)) {
- break;
- }
- if (c != '.' && c != '/') {
- sawNonSlash = true;
- }
- }
- var fixed = this.exp.substring(start, this.index);
- if (start === this.index || !sawNonSlash || fixed.startsWith('//')) {
- throw new exceptions_1.BaseException("Invalid router link");
- }
- return new FixedPart(fixed);
- };
- return RouterLinkLexer;
- })();
- var RouterLinkAstGenerator = (function () {
- function RouterLinkAstGenerator(tokens) {
- this.tokens = tokens;
- this.index = 0;
- }
- RouterLinkAstGenerator.prototype.generate = function () { return this._genAuxiliary(); };
- RouterLinkAstGenerator.prototype._genAuxiliary = function () {
- var arr = [];
- for (; this.index < this.tokens.length; this.index++) {
- var r = this.tokens[this.index];
- if (r instanceof FixedPart) {
- arr.push(new ast_1.LiteralPrimitive(r.value));
- }
- else if (r instanceof Params) {
- arr.push(r.ast);
- }
- else if (r instanceof AuxiliaryEnd) {
- break;
- }
- else if (r instanceof AuxiliaryStart) {
- this.index++;
- arr.push(this._genAuxiliary());
- }
- }
- return new ast_1.LiteralArray(arr);
- };
- return RouterLinkAstGenerator;
- })();
- var RouterLinkAstTransformer = (function (_super) {
- __extends(RouterLinkAstTransformer, _super);
- function RouterLinkAstTransformer(parser) {
- _super.call(this);
- this.parser = parser;
- }
- RouterLinkAstTransformer.prototype.visitQuote = function (ast) {
- if (ast.prefix == "route") {
- return parseRouterLinkExpression(this.parser, ast.uninterpretedExpression);
- }
- else {
- return _super.prototype.visitQuote.call(this, ast);
- }
- };
- return RouterLinkAstTransformer;
- })(ast_1.AstTransformer);
- function parseRouterLinkExpression(parser, exp) {
- var tokens = new RouterLinkLexer(parser, exp.trim()).tokenize();
- return new RouterLinkAstGenerator(tokens).generate();
- }
- exports.parseRouterLinkExpression = parseRouterLinkExpression;
- /**
- * A compiler plugin that implements the router link DSL.
- */
- var RouterLinkTransform = (function () {
- function RouterLinkTransform(parser) {
- this.astTransformer = new RouterLinkAstTransformer(parser);
- }
- RouterLinkTransform.prototype.visitNgContent = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitEmbeddedTemplate = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitElement = function (ast, context) {
- var _this = this;
- var updatedChildren = ast.children.map(function (c) { return c.visit(_this, context); });
- var updatedInputs = ast.inputs.map(function (c) { return c.visit(_this, context); });
- var updatedDirectives = ast.directives.map(function (c) { return c.visit(_this, context); });
- return new compiler_1.ElementAst(ast.name, ast.attrs, updatedInputs, ast.outputs, ast.exportAsVars, updatedDirectives, updatedChildren, ast.ngContentIndex, ast.sourceSpan);
- };
- RouterLinkTransform.prototype.visitVariable = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitEvent = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitElementProperty = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitAttr = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitBoundText = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitText = function (ast, context) { return ast; };
- RouterLinkTransform.prototype.visitDirective = function (ast, context) {
- var _this = this;
- var updatedInputs = ast.inputs.map(function (c) { return c.visit(_this, context); });
- return new compiler_1.DirectiveAst(ast.directive, updatedInputs, ast.hostProperties, ast.hostEvents, ast.exportAsVars, ast.sourceSpan);
- };
- RouterLinkTransform.prototype.visitDirectiveProperty = function (ast, context) {
- var transformedValue = ast.value.visit(this.astTransformer);
- return new compiler_1.BoundDirectivePropertyAst(ast.directiveName, ast.templateName, transformedValue, ast.sourceSpan);
- };
- RouterLinkTransform = __decorate([
- core_1.Injectable(),
- __metadata('design:paramtypes', [parser_1.Parser])
- ], RouterLinkTransform);
- return RouterLinkTransform;
- })();
- exports.RouterLinkTransform = RouterLinkTransform;
- /***/ },
- /* 250 */
- /***/ function(module, exports, __webpack_require__) {
- var profile_1 = __webpack_require__(45);
- exports.wtfCreateScope = profile_1.wtfCreateScope;
- exports.wtfLeave = profile_1.wtfLeave;
- exports.wtfStartTimeRange = profile_1.wtfStartTimeRange;
- exports.wtfEndTimeRange = profile_1.wtfEndTimeRange;
- /***/ },
- /* 251 */
- /***/ function(module, exports, __webpack_require__) {
- /**
- * @module
- * @description
- * Adapter allowing AngularJS v1 and Angular v2 to run side by side in the same application.
- */
- var upgrade_adapter_1 = __webpack_require__(252);
- exports.UpgradeAdapter = upgrade_adapter_1.UpgradeAdapter;
- exports.UpgradeAdapterRef = upgrade_adapter_1.UpgradeAdapterRef;
- /***/ },
- /* 252 */
- /***/ function(module, exports, __webpack_require__) {
- var core_1 = __webpack_require__(2);
- var async_1 = __webpack_require__(60);
- var browser_1 = __webpack_require__(179);
- var metadata_1 = __webpack_require__(253);
- var util_1 = __webpack_require__(254);
- var constants_1 = __webpack_require__(255);
- var downgrade_ng2_adapter_1 = __webpack_require__(256);
- var upgrade_ng1_adapter_1 = __webpack_require__(257);
- var angular = __webpack_require__(258);
- var upgradeCount = 0;
- /**
- * Use `UpgradeAdapter` to allow AngularJS v1 and Angular v2 to coexist in a single application.
- *
- * The `UpgradeAdapter` allows:
- * 1. creation of Angular v2 component from AngularJS v1 component directive
- * (See [UpgradeAdapter#upgradeNg1Component()])
- * 2. creation of AngularJS v1 directive from Angular v2 component.
- * (See [UpgradeAdapter#downgradeNg2Component()])
- * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
- * coexisting in a single application.
- *
- * ## Mental Model
- *
- * When reasoning about how a hybrid application works it is useful to have a mental model which
- * describes what is happening and explains what is happening at the lowest level.
- *
- * 1. There are two independent frameworks running in a single application, each framework treats
- * the other as a black box.
- * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
- * instantiated the element is the owner. Each framework only updates/interacts with its own
- * DOM elements and ignores others.
- * 3. AngularJS v1 directives always execute inside AngularJS v1 framework codebase regardless of
- * where they are instantiated.
- * 4. Angular v2 components always execute inside Angular v2 framework codebase regardless of
- * where they are instantiated.
- * 5. An AngularJS v1 component can be upgraded to an Angular v2 component. This creates an
- * Angular v2 directive, which bootstraps the AngularJS v1 component directive in that location.
- * 6. An Angular v2 component can be downgraded to an AngularJS v1 component directive. This creates
- * an AngularJS v1 directive, which bootstraps the Angular v2 component in that location.
- * 7. Whenever an adapter component is instantiated the host element is owned by the framework
- * doing the instantiation. The other framework then instantiates and owns the view for that
- * component. This implies that component bindings will always follow the semantics of the
- * instantiation framework. The syntax is always that of Angular v2 syntax.
- * 8. AngularJS v1 is always bootstrapped first and owns the bottom most view.
- * 9. The new application is running in Angular v2 zone, and therefore it no longer needs calls to
- * `$apply()`.
- *
- * ### Example
- *
- * ```
- * var adapter = new UpgradeAdapter();
- * var module = angular.module('myExample', []);
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
- *
- * module.directive('ng1', function() {
- * return {
- * scope: { title: '=' },
- * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
- * };
- * });
- *
- *
- * @Component({
- * selector: 'ng2',
- * inputs: ['name'],
- * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)',
- * directives: [adapter.upgradeNg1Component('ng1')]
- * })
- * class Ng2 {
- * }
- *
- * document.body.innerHTML = '<ng2 name="World">project</ng2>';
- *
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
- * expect(document.body.textContent).toEqual(
- * "ng2[ng1[Hello World!](transclude)](project)");
- * });
- * ```
- */
- var UpgradeAdapter = (function () {
- function UpgradeAdapter() {
- /* @internal */
- this.idPrefix = "NG2_UPGRADE_" + upgradeCount++ + "_";
- /* @internal */
- this.upgradedComponents = [];
- /* @internal */
- this.downgradedComponents = {};
- /* @internal */
- this.providers = [];
- }
- /**
- * Allows Angular v2 Component to be used from AngularJS v1.
- *
- * Use `downgradeNg2Component` to create an AngularJS v1 Directive Definition Factory from
- * Angular v2 Component. The adapter will bootstrap Angular v2 component from within the
- * AngularJS v1 template.
- *
- * ## Mental Model
- *
- * 1. The component is instantiated by being listed in AngularJS v1 template. This means that the
- * host element is controlled by AngularJS v1, but the component's view will be controlled by
- * Angular v2.
- * 2. Even thought the component is instantiated in AngularJS v1, it will be using Angular v2
- * syntax. This has to be done, this way because we must follow Angular v2 components do not
- * declare how the attributes should be interpreted.
- *
- * ## Supported Features
- *
- * - Bindings:
- * - Attribute: `<comp name="World">`
- * - Interpolation: `<comp greeting="Hello {{name}}!">`
- * - Expression: `<comp [name]="username">`
- * - Event: `<comp (close)="doSomething()">`
- * - Content projection: yes
- *
- * ### Example
- *
- * ```
- * var adapter = new UpgradeAdapter();
- * var module = angular.module('myExample', []);
- * module.directive('greet', adapter.downgradeNg2Component(Greeter));
- *
- * @Component({
- * selector: 'greet',
- * template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
- * })
- * class Greeter {
- * @Input() salutation: string;
- * @Input() name: string;
- * }
- *
- * document.body.innerHTML =
- * 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
- *
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
- * expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
- * });
- * ```
- */
- UpgradeAdapter.prototype.downgradeNg2Component = function (type) {
- this.upgradedComponents.push(type);
- var info = metadata_1.getComponentInfo(type);
- return ng1ComponentDirective(info, "" + this.idPrefix + info.selector + "_c");
- };
- /**
- * Allows AngularJS v1 Component to be used from Angular v2.
- *
- * Use `upgradeNg1Component` to create an Angular v2 component from AngularJS v1 Component
- * directive. The adapter will bootstrap AngularJS v1 component from within the Angular v2
- * template.
- *
- * ## Mental Model
- *
- * 1. The component is instantiated by being listed in Angular v2 template. This means that the
- * host element is controlled by Angular v2, but the component's view will be controlled by
- * AngularJS v1.
- *
- * ## Supported Features
- *
- * - Bindings:
- * - Attribute: `<comp name="World">`
- * - Interpolation: `<comp greeting="Hello {{name}}!">`
- * - Expression: `<comp [name]="username">`
- * - Event: `<comp (close)="doSomething()">`
- * - Transclusion: yes
- * - Only some of the features of
- * [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
- * supported:
- * - `compile`: not supported because the host element is owned by Angular v2, which does
- * not allow modifying DOM structure during compilation.
- * - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
- * - `controllerAs': supported.
- * - `bindToController': supported.
- * - `link': supported. (NOTE: only pre-link function is supported.)
- * - `name': supported.
- * - `priority': ignored.
- * - `replace': not supported.
- * - `require`: supported.
- * - `restrict`: must be set to 'E'.
- * - `scope`: supported.
- * - `template`: supported.
- * - `templateUrl`: supported.
- * - `terminal`: ignored.
- * - `transclude`: supported.
- *
- *
- * ### Example
- *
- * ```
- * var adapter = new UpgradeAdapter();
- * var module = angular.module('myExample', []);
- *
- * module.directive('greet', function() {
- * return {
- * scope: {salutation: '=', name: '=' },
- * template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
- * };
- * });
- *
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
- *
- * @Component({
- * selector: 'ng2',
- * template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
- * directives: [adapter.upgradeNg1Component('greet')]
- * })
- * class Ng2 {
- * }
- *
- * document.body.innerHTML = '<ng2></ng2>';
- *
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
- * expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
- * });
- * ```
- */
- UpgradeAdapter.prototype.upgradeNg1Component = function (name) {
- if (this.downgradedComponents.hasOwnProperty(name)) {
- return this.downgradedComponents[name].type;
- }
- else {
- return (this.downgradedComponents[name] = new upgrade_ng1_adapter_1.UpgradeNg1ComponentAdapterBuilder(name)).type;
- }
- };
- /**
- * Bootstrap a hybrid AngularJS v1 / Angular v2 application.
- *
- * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS v1
- * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
- * AngularJS v1, this bootstrap is asynchronous.
- *
- * ### Example
- *
- * ```
- * var adapter = new UpgradeAdapter();
- * var module = angular.module('myExample', []);
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
- *
- * module.directive('ng1', function() {
- * return {
- * scope: { title: '=' },
- * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
- * };
- * });
- *
- *
- * @Component({
- * selector: 'ng2',
- * inputs: ['name'],
- * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)',
- * directives: [adapter.upgradeNg1Component('ng1')]
- * })
- * class Ng2 {
- * }
- *
- * document.body.innerHTML = '<ng2 name="World">project</ng2>';
- *
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
- * expect(document.body.textContent).toEqual(
- * "ng2[ng1[Hello World!](transclude)](project)");
- * });
- * ```
- */
- UpgradeAdapter.prototype.bootstrap = function (element, modules, config) {
- var _this = this;
- var upgrade = new UpgradeAdapterRef();
- var ng1Injector = null;
- var platformRef = core_1.platform(browser_1.BROWSER_PROVIDERS);
- var applicationRef = platformRef.application([
- browser_1.BROWSER_APP_PROVIDERS,
- core_1.provide(constants_1.NG1_INJECTOR, { useFactory: function () { return ng1Injector; } }),
- core_1.provide(constants_1.NG1_COMPILE, { useFactory: function () { return ng1Injector.get(constants_1.NG1_COMPILE); } }),
- this.providers
- ]);
- var injector = applicationRef.injector;
- var ngZone = injector.get(core_1.NgZone);
- var compiler = injector.get(core_1.Compiler);
- var delayApplyExps = [];
- var original$applyFn;
- var rootScopePrototype;
- var rootScope;
- var protoViewRefMap = {};
- var ng1Module = angular.module(this.idPrefix, modules);
- var ng1compilePromise = null;
- ng1Module.value(constants_1.NG2_INJECTOR, injector)
- .value(constants_1.NG2_ZONE, ngZone)
- .value(constants_1.NG2_COMPILER, compiler)
- .value(constants_1.NG2_PROTO_VIEW_REF_MAP, protoViewRefMap)
- .value(constants_1.NG2_APP_VIEW_MANAGER, injector.get(core_1.AppViewManager))
- .config([
- '$provide',
- function (provide) {
- provide.decorator(constants_1.NG1_ROOT_SCOPE, [
- '$delegate',
- function (rootScopeDelegate) {
- rootScopePrototype = rootScopeDelegate.constructor.prototype;
- if (rootScopePrototype.hasOwnProperty('$apply')) {
- original$applyFn = rootScopePrototype.$apply;
- rootScopePrototype.$apply = function (exp) { return delayApplyExps.push(exp); };
- }
- else {
- throw new Error("Failed to find '$apply' on '$rootScope'!");
- }
- return rootScope = rootScopeDelegate;
- }
- ]);
- }
- ])
- .run([
- '$injector',
- '$rootScope',
- function (injector, rootScope) {
- ng1Injector = injector;
- async_1.ObservableWrapper.subscribe(ngZone.onTurnDone, function (_) { ngZone.run(function () { return rootScope.$apply(); }); });
- ng1compilePromise =
- upgrade_ng1_adapter_1.UpgradeNg1ComponentAdapterBuilder.resolve(_this.downgradedComponents, injector);
- }
- ]);
- angular.element(element).data(util_1.controllerKey(constants_1.NG2_INJECTOR), injector);
- ngZone.run(function () { angular.bootstrap(element, [_this.idPrefix], config); });
- Promise.all([this.compileNg2Components(compiler, protoViewRefMap), ng1compilePromise])
- .then(function () {
- ngZone.run(function () {
- if (rootScopePrototype) {
- rootScopePrototype.$apply = original$applyFn; // restore original $apply
- while (delayApplyExps.length) {
- rootScope.$apply(delayApplyExps.shift());
- }
- upgrade._bootstrapDone(applicationRef, ng1Injector);
- rootScopePrototype = null;
- }
- });
- }, util_1.onError);
- return upgrade;
- };
- /**
- * Adds a provider to the top level environment of a hybrid AngularJS v1 / Angular v2 application.
- *
- * In hybrid AngularJS v1 / Angular v2 application, there is no one root Angular v2 component,
- * for this reason we provide an application global way of registering providers which is
- * consistent with single global injection in AngularJS v1.
- *
- * ### Example
- *
- * ```
- * class Greeter {
- * greet(name) {
- * alert('Hello ' + name + '!');
- * }
- * }
- *
- * @Component({
- * selector: 'app',
- * template: ''
- * })
- * class App {
- * constructor(greeter: Greeter) {
- * this.greeter('World');
- * }
- * }
- *
- * var adapter = new UpgradeAdapter();
- * adapter.addProvider(Greeter);
- *
- * var module = angular.module('myExample', []);
- * module.directive('app', adapter.downgradeNg2Component(App));
- *
- * document.body.innerHTML = '<app></app>'
- * adapter.bootstrap(document.body, ['myExample']);
- *```
- */
- UpgradeAdapter.prototype.addProvider = function (provider) { this.providers.push(provider); };
- /**
- * Allows AngularJS v1 service to be accessible from Angular v2.
- *
- *
- * ### Example
- *
- * ```
- * class Login { ... }
- * class Server { ... }
- *
- * @Injectable()
- * class Example {
- * constructor(@Inject('server') server, login: Login) {
- * ...
- * }
- * }
- *
- * var module = angular.module('myExample', []);
- * module.service('server', Server);
- * module.service('login', Login);
- *
- * var adapter = new UpgradeAdapter();
- * adapter.upgradeNg1Provider('server');
- * adapter.upgradeNg1Provider('login', {asToken: Login});
- * adapter.addProvider(Example);
- *
- * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
- * var example: Example = ref.ng2Injector.get(Example);
- * });
- *
- * ```
- */
- UpgradeAdapter.prototype.upgradeNg1Provider = function (name, options) {
- var token = options && options.asToken || name;
- this.providers.push(core_1.provide(token, {
- useFactory: function (ng1Injector) { return ng1Injector.get(name); },
- deps: [constants_1.NG1_INJECTOR]
- }));
- };
- /**
- * Allows Angular v2 service to be accessible from AngularJS v1.
- *
- *
- * ### Example
- *
- * ```
- * class Example {
- * }
- *
- * var adapter = new UpgradeAdapter();
- * adapter.addProvider(Example);
- *
- * var module = angular.module('myExample', []);
- * module.factory('example', adapter.downgradeNg2Provider(Example));
- *
- * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
- * var example: Example = ref.ng1Injector.get('example');
- * });
- *
- * ```
- */
- UpgradeAdapter.prototype.downgradeNg2Provider = function (token) {
- var factory = function (injector) { return injector.get(token); };
- factory.$inject = [constants_1.NG2_INJECTOR];
- return factory;
- };
- /* @internal */
- UpgradeAdapter.prototype.compileNg2Components = function (compiler, protoViewRefMap) {
- var _this = this;
- var promises = [];
- var types = this.upgradedComponents;
- for (var i = 0; i < types.length; i++) {
- promises.push(compiler.compileInHost(types[i]));
- }
- return Promise.all(promises).then(function (protoViews) {
- var types = _this.upgradedComponents;
- for (var i = 0; i < protoViews.length; i++) {
- protoViewRefMap[metadata_1.getComponentInfo(types[i]).selector] = protoViews[i];
- }
- return protoViewRefMap;
- }, util_1.onError);
- };
- return UpgradeAdapter;
- })();
- exports.UpgradeAdapter = UpgradeAdapter;
- function ng1ComponentDirective(info, idPrefix) {
- directiveFactory.$inject = [constants_1.NG2_PROTO_VIEW_REF_MAP, constants_1.NG2_APP_VIEW_MANAGER, constants_1.NG1_PARSE];
- function directiveFactory(protoViewRefMap, viewManager, parse) {
- var protoView = protoViewRefMap[info.selector];
- if (!protoView)
- throw new Error('Expecting ProtoViewRef for: ' + info.selector);
- var idCount = 0;
- return {
- restrict: 'E',
- require: constants_1.REQUIRE_INJECTOR,
- link: {
- post: function (scope, element, attrs, parentInjector, transclude) {
- var domElement = element[0];
- var facade = new downgrade_ng2_adapter_1.DowngradeNg2ComponentAdapter(idPrefix + (idCount++), info, element, attrs, scope, parentInjector, parse, viewManager, protoView);
- facade.setupInputs();
- facade.bootstrapNg2();
- facade.projectContent();
- facade.setupOutputs();
- facade.registerCleanup();
- }
- }
- };
- }
- return directiveFactory;
- }
- /**
- * Use `UgradeAdapterRef` to control a hybrid AngularJS v1 / Angular v2 application.
- */
- var UpgradeAdapterRef = (function () {
- function UpgradeAdapterRef() {
- /* @internal */
- this._readyFn = null;
- this.ng1RootScope = null;
- this.ng1Injector = null;
- this.ng2ApplicationRef = null;
- this.ng2Injector = null;
- }
- /* @internal */
- UpgradeAdapterRef.prototype._bootstrapDone = function (applicationRef, ng1Injector) {
- this.ng2ApplicationRef = applicationRef;
- this.ng2Injector = applicationRef.injector;
- this.ng1Injector = ng1Injector;
- this.ng1RootScope = ng1Injector.get(constants_1.NG1_ROOT_SCOPE);
- this._readyFn && this._readyFn(this);
- };
- /**
- * Register a callback function which is notified upon successful hybrid AngularJS v1 / Angular v2
- * application has been bootstrapped.
- *
- * The `ready` callback function is invoked inside the Angular v2 zone, therefore it does not
- * require a call to `$apply()`.
- */
- UpgradeAdapterRef.prototype.ready = function (fn) { this._readyFn = fn; };
- /**
- * Dispose of running hybrid AngularJS v1 / Angular v2 application.
- */
- UpgradeAdapterRef.prototype.dispose = function () {
- this.ng1Injector.get(constants_1.NG1_ROOT_SCOPE).$destroy();
- this.ng2ApplicationRef.dispose();
- };
- return UpgradeAdapterRef;
- })();
- exports.UpgradeAdapterRef = UpgradeAdapterRef;
- /***/ },
- /* 253 */
- /***/ function(module, exports, __webpack_require__) {
- var core_1 = __webpack_require__(2);
- var COMPONENT_SELECTOR = /^[\w|-]*$/;
- var SKEWER_CASE = /-(\w)/g;
- var directiveResolver = new core_1.DirectiveResolver();
- function getComponentInfo(type) {
- var resolvedMetadata = directiveResolver.resolve(type);
- var selector = resolvedMetadata.selector;
- if (!selector.match(COMPONENT_SELECTOR)) {
- throw new Error('Only selectors matching element names are supported, got: ' + selector);
- }
- var selector = selector.replace(SKEWER_CASE, function (all, letter) { return letter.toUpperCase(); });
- return {
- type: type,
- selector: selector,
- inputs: parseFields(resolvedMetadata.inputs),
- outputs: parseFields(resolvedMetadata.outputs)
- };
- }
- exports.getComponentInfo = getComponentInfo;
- function parseFields(names) {
- var attrProps = [];
- if (names) {
- for (var i = 0; i < names.length; i++) {
- var parts = names[i].split(':');
- var prop = parts[0].trim();
- var attr = (parts[1] || parts[0]).trim();
- var capitalAttr = attr.charAt(0).toUpperCase() + attr.substr(1);
- attrProps.push({
- prop: prop,
- attr: attr,
- bracketAttr: "[" + attr + "]",
- parenAttr: "(" + attr + ")",
- bracketParenAttr: "[(" + attr + ")]",
- onAttr: "on" + capitalAttr,
- bindAttr: "bind" + capitalAttr,
- bindonAttr: "bindon" + capitalAttr
- });
- }
- }
- return attrProps;
- }
- exports.parseFields = parseFields;
- /***/ },
- /* 254 */
- /***/ function(module, exports) {
- function stringify(obj) {
- if (typeof obj == 'function')
- return obj.name || obj.toString();
- return '' + obj;
- }
- exports.stringify = stringify;
- function onError(e) {
- // TODO: (misko): We seem to not have a stack trace here!
- console.log(e, e.stack);
- throw e;
- }
- exports.onError = onError;
- function controllerKey(name) {
- return '$' + name + 'Controller';
- }
- exports.controllerKey = controllerKey;
- /***/ },
- /* 255 */
- /***/ function(module, exports) {
- exports.NG2_APP_VIEW_MANAGER = 'ng2.AppViewManager';
- exports.NG2_COMPILER = 'ng2.Compiler';
- exports.NG2_INJECTOR = 'ng2.Injector';
- exports.NG2_PROTO_VIEW_REF_MAP = 'ng2.ProtoViewRefMap';
- exports.NG2_ZONE = 'ng2.NgZone';
- exports.NG1_CONTROLLER = '$controller';
- exports.NG1_SCOPE = '$scope';
- exports.NG1_ROOT_SCOPE = '$rootScope';
- exports.NG1_COMPILE = '$compile';
- exports.NG1_HTTP_BACKEND = '$httpBackend';
- exports.NG1_INJECTOR = '$injector';
- exports.NG1_PARSE = '$parse';
- exports.NG1_TEMPLATE_CACHE = '$templateCache';
- exports.REQUIRE_INJECTOR = '^' + exports.NG2_INJECTOR;
- /***/ },
- /* 256 */
- /***/ function(module, exports, __webpack_require__) {
- var core_1 = __webpack_require__(2);
- var constants_1 = __webpack_require__(255);
- var INITIAL_VALUE = {
- __UNINITIALIZED__: true
- };
- var DowngradeNg2ComponentAdapter = (function () {
- function DowngradeNg2ComponentAdapter(id, info, element, attrs, scope, parentInjector, parse, viewManager, protoView) {
- this.id = id;
- this.info = info;
- this.element = element;
- this.attrs = attrs;
- this.scope = scope;
- this.parentInjector = parentInjector;
- this.parse = parse;
- this.viewManager = viewManager;
- this.protoView = protoView;
- this.component = null;
- this.inputChangeCount = 0;
- this.inputChanges = null;
- this.hostViewRef = null;
- this.changeDetector = null;
- this.contentInserctionPoint = null;
- this.element[0].id = id;
- this.componentScope = scope.$new();
- this.childNodes = element.contents();
- }
- DowngradeNg2ComponentAdapter.prototype.bootstrapNg2 = function () {
- var childInjector = this.parentInjector.resolveAndCreateChild([core_1.provide(constants_1.NG1_SCOPE, { useValue: this.componentScope })]);
- this.hostViewRef =
- this.viewManager.createRootHostView(this.protoView, '#' + this.id, childInjector);
- var renderer = this.hostViewRef.render;
- var hostElement = this.viewManager.getHostElement(this.hostViewRef);
- this.changeDetector = this.hostViewRef.changeDetectorRef;
- this.component = this.viewManager.getComponent(hostElement);
- this.contentInserctionPoint = renderer.rootContentInsertionPoints[0];
- };
- DowngradeNg2ComponentAdapter.prototype.setupInputs = function () {
- var _this = this;
- var attrs = this.attrs;
- var inputs = this.info.inputs;
- for (var i = 0; i < inputs.length; i++) {
- var input = inputs[i];
- var expr = null;
- if (attrs.hasOwnProperty(input.attr)) {
- var observeFn = (function (prop) {
- var prevValue = INITIAL_VALUE;
- return function (value) {
- if (_this.inputChanges !== null) {
- _this.inputChangeCount++;
- _this.inputChanges[prop] =
- new Ng1Change(value, prevValue === INITIAL_VALUE ? value : prevValue);
- prevValue = value;
- }
- _this.component[prop] = value;
- };
- })(input.prop);
- attrs.$observe(input.attr, observeFn);
- }
- else if (attrs.hasOwnProperty(input.bindAttr)) {
- expr = attrs[input.bindAttr];
- }
- else if (attrs.hasOwnProperty(input.bracketAttr)) {
- expr = attrs[input.bracketAttr];
- }
- else if (attrs.hasOwnProperty(input.bindonAttr)) {
- expr = attrs[input.bindonAttr];
- }
- else if (attrs.hasOwnProperty(input.bracketParenAttr)) {
- expr = attrs[input.bracketParenAttr];
- }
- if (expr != null) {
- var watchFn = (function (prop) { return function (value, prevValue) {
- if (_this.inputChanges != null) {
- _this.inputChangeCount++;
- _this.inputChanges[prop] = new Ng1Change(prevValue, value);
- }
- _this.component[prop] = value;
- }; })(input.prop);
- this.componentScope.$watch(expr, watchFn);
- }
- }
- var prototype = this.info.type.prototype;
- if (prototype && prototype.ngOnChanges) {
- // Detect: OnChanges interface
- this.inputChanges = {};
- this.componentScope.$watch(function () { return _this.inputChangeCount; }, function () {
- var inputChanges = _this.inputChanges;
- _this.inputChanges = {};
- _this.component.ngOnChanges(inputChanges);
- });
- }
- this.componentScope.$watch(function () { return _this.changeDetector && _this.changeDetector.detectChanges(); });
- };
- DowngradeNg2ComponentAdapter.prototype.projectContent = function () {
- var childNodes = this.childNodes;
- if (this.contentInserctionPoint) {
- var parent = this.contentInserctionPoint.parentNode;
- for (var i = 0, ii = childNodes.length; i < ii; i++) {
- parent.insertBefore(childNodes[i], this.contentInserctionPoint);
- }
- }
- };
- DowngradeNg2ComponentAdapter.prototype.setupOutputs = function () {
- var _this = this;
- var attrs = this.attrs;
- var outputs = this.info.outputs;
- for (var j = 0; j < outputs.length; j++) {
- var output = outputs[j];
- var expr = null;
- var assignExpr = false;
- var bindonAttr = output.bindonAttr ? output.bindonAttr.substring(0, output.bindonAttr.length - 6) : null;
- var bracketParenAttr = output.bracketParenAttr ?
- "[(" + output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8) + ")]" :
- null;
- if (attrs.hasOwnProperty(output.onAttr)) {
- expr = attrs[output.onAttr];
- }
- else if (attrs.hasOwnProperty(output.parenAttr)) {
- expr = attrs[output.parenAttr];
- }
- else if (attrs.hasOwnProperty(bindonAttr)) {
- expr = attrs[bindonAttr];
- assignExpr = true;
- }
- else if (attrs.hasOwnProperty(bracketParenAttr)) {
- expr = attrs[bracketParenAttr];
- assignExpr = true;
- }
- if (expr != null && assignExpr != null) {
- var getter = this.parse(expr);
- var setter = getter.assign;
- if (assignExpr && !setter) {
- throw new Error("Expression '" + expr + "' is not assignable!");
- }
- var emitter = this.component[output.prop];
- if (emitter) {
- emitter.subscribe({
- next: assignExpr ? (function (setter) { return function (value) { return setter(_this.scope, value); }; })(setter) :
- (function (getter) { return function (value) { return getter(_this.scope, { $event: value }); }; })(getter)
- });
- }
- else {
- throw new Error("Missing emitter '" + output.prop + "' on component '" + this.info.selector + "'!");
- }
- }
- }
- };
- DowngradeNg2ComponentAdapter.prototype.registerCleanup = function () {
- var _this = this;
- this.element.bind('$remove', function () { return _this.viewManager.destroyRootHostView(_this.hostViewRef); });
- };
- return DowngradeNg2ComponentAdapter;
- })();
- exports.DowngradeNg2ComponentAdapter = DowngradeNg2ComponentAdapter;
- var Ng1Change = (function () {
- function Ng1Change(previousValue, currentValue) {
- this.previousValue = previousValue;
- this.currentValue = currentValue;
- }
- Ng1Change.prototype.isFirstChange = function () { return this.previousValue === this.currentValue; };
- return Ng1Change;
- })();
- /***/ },
- /* 257 */
- /***/ function(module, exports, __webpack_require__) {
- var core_1 = __webpack_require__(2);
- var constants_1 = __webpack_require__(255);
- var util_1 = __webpack_require__(254);
- var angular = __webpack_require__(258);
- var CAMEL_CASE = /([A-Z])/g;
- var INITIAL_VALUE = {
- __UNINITIALIZED__: true
- };
- var NOT_SUPPORTED = 'NOT_SUPPORTED';
- var UpgradeNg1ComponentAdapterBuilder = (function () {
- function UpgradeNg1ComponentAdapterBuilder(name) {
- this.name = name;
- this.inputs = [];
- this.inputsRename = [];
- this.outputs = [];
- this.outputsRename = [];
- this.propertyOutputs = [];
- this.checkProperties = [];
- this.propertyMap = {};
- this.linkFn = null;
- this.directive = null;
- this.$controller = null;
- var selector = name.replace(CAMEL_CASE, function (all, next) { return '-' + next.toLowerCase(); });
- var self = this;
- this.type =
- core_1.Directive({ selector: selector, inputs: this.inputsRename, outputs: this.outputsRename })
- .Class({
- constructor: [
- new core_1.Inject(constants_1.NG1_SCOPE),
- core_1.ElementRef,
- function (scope, elementRef) {
- return new UpgradeNg1ComponentAdapter(self.linkFn, scope, self.directive, elementRef, self.$controller, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap);
- }
- ],
- ngOnChanges: function () { },
- ngDoCheck: function () { }
- });
- }
- UpgradeNg1ComponentAdapterBuilder.prototype.extractDirective = function (injector) {
- var directives = injector.get(this.name + 'Directive');
- if (directives.length > 1) {
- throw new Error('Only support single directive definition for: ' + this.name);
- }
- var directive = directives[0];
- if (directive.replace)
- this.notSupported('replace');
- if (directive.terminal)
- this.notSupported('terminal');
- var link = directive.link;
- if (typeof link == 'object') {
- if (link.post)
- this.notSupported('link.post');
- }
- return directive;
- };
- UpgradeNg1ComponentAdapterBuilder.prototype.notSupported = function (feature) {
- throw new Error("Upgraded directive '" + this.name + "' does not support '" + feature + "'.");
- };
- UpgradeNg1ComponentAdapterBuilder.prototype.extractBindings = function () {
- var scope = this.directive.scope;
- if (typeof scope == 'object') {
- for (var name in scope) {
- if (scope.hasOwnProperty(name)) {
- var localName = scope[name];
- var type = localName.charAt(0);
- localName = localName.substr(1) || name;
- var outputName = 'output_' + name;
- var outputNameRename = outputName + ': ' + name;
- var outputNameRenameChange = outputName + ': ' + name + 'Change';
- var inputName = 'input_' + name;
- var inputNameRename = inputName + ': ' + name;
- switch (type) {
- case '=':
- this.propertyOutputs.push(outputName);
- this.checkProperties.push(localName);
- this.outputs.push(outputName);
- this.outputsRename.push(outputNameRenameChange);
- this.propertyMap[outputName] = localName;
- // don't break; let it fall through to '@'
- case '@':
- this.inputs.push(inputName);
- this.inputsRename.push(inputNameRename);
- this.propertyMap[inputName] = localName;
- break;
- case '&':
- this.outputs.push(outputName);
- this.outputsRename.push(outputNameRename);
- this.propertyMap[outputName] = localName;
- break;
- default:
- var json = JSON.stringify(scope);
- throw new Error("Unexpected mapping '" + type + "' in '" + json + "' in '" + this.name + "' directive.");
- }
- }
- }
- }
- };
- UpgradeNg1ComponentAdapterBuilder.prototype.compileTemplate = function (compile, templateCache, httpBackend) {
- var _this = this;
- if (this.directive.template !== undefined) {
- this.linkFn = compileHtml(this.directive.template);
- }
- else if (this.directive.templateUrl) {
- var url = this.directive.templateUrl;
- var html = templateCache.get(url);
- if (html !== undefined) {
- this.linkFn = compileHtml(html);
- }
- else {
- return new Promise(function (resolve, err) {
- httpBackend('GET', url, null, function (status, response) {
- if (status == 200) {
- resolve(_this.linkFn = compileHtml(templateCache.put(url, response)));
- }
- else {
- err("GET " + url + " returned " + status + ": " + response);
- }
- });
- });
- }
- }
- else {
- throw new Error("Directive '" + this.name + "' is not a component, it is missing template.");
- }
- return null;
- function compileHtml(html) {
- var div = document.createElement('div');
- div.innerHTML = html;
- return compile(div.childNodes);
- }
- };
- UpgradeNg1ComponentAdapterBuilder.resolve = function (exportedComponents, injector) {
- var promises = [];
- var compile = injector.get(constants_1.NG1_COMPILE);
- var templateCache = injector.get(constants_1.NG1_TEMPLATE_CACHE);
- var httpBackend = injector.get(constants_1.NG1_HTTP_BACKEND);
- var $controller = injector.get(constants_1.NG1_CONTROLLER);
- for (var name in exportedComponents) {
- if (exportedComponents.hasOwnProperty(name)) {
- var exportedComponent = exportedComponents[name];
- exportedComponent.directive = exportedComponent.extractDirective(injector);
- exportedComponent.$controller = $controller;
- exportedComponent.extractBindings();
- var promise = exportedComponent.compileTemplate(compile, templateCache, httpBackend);
- if (promise)
- promises.push(promise);
- }
- }
- return Promise.all(promises);
- };
- return UpgradeNg1ComponentAdapterBuilder;
- })();
- exports.UpgradeNg1ComponentAdapterBuilder = UpgradeNg1ComponentAdapterBuilder;
- var UpgradeNg1ComponentAdapter = (function () {
- function UpgradeNg1ComponentAdapter(linkFn, scope, directive, elementRef, $controller, inputs, outputs, propOuts, checkProperties, propertyMap) {
- this.directive = directive;
- this.inputs = inputs;
- this.outputs = outputs;
- this.propOuts = propOuts;
- this.checkProperties = checkProperties;
- this.propertyMap = propertyMap;
- this.destinationObj = null;
- this.checkLastValues = [];
- var element = elementRef.nativeElement;
- var childNodes = [];
- var childNode;
- while (childNode = element.firstChild) {
- element.removeChild(childNode);
- childNodes.push(childNode);
- }
- var componentScope = scope.$new(!!directive.scope);
- var $element = angular.element(element);
- var controllerType = directive.controller;
- var controller = null;
- if (controllerType) {
- var locals = { $scope: componentScope, $element: $element };
- controller = $controller(controllerType, locals, null, directive.controllerAs);
- $element.data(util_1.controllerKey(directive.name), controller);
- }
- var link = directive.link;
- if (typeof link == 'object')
- link = link.pre;
- if (link) {
- var attrs = NOT_SUPPORTED;
- var transcludeFn = NOT_SUPPORTED;
- var linkController = this.resolveRequired($element, directive.require);
- directive.link(componentScope, $element, attrs, linkController, transcludeFn);
- }
- this.destinationObj = directive.bindToController && controller ? controller : componentScope;
- linkFn(componentScope, function (clonedElement, scope) {
- for (var i = 0, ii = clonedElement.length; i < ii; i++) {
- element.appendChild(clonedElement[i]);
- }
- }, { parentBoundTranscludeFn: function (scope, cloneAttach) { cloneAttach(childNodes); } });
- for (var i = 0; i < inputs.length; i++) {
- this[inputs[i]] = null;
- }
- for (var j = 0; j < outputs.length; j++) {
- var emitter = this[outputs[j]] = new core_1.EventEmitter();
- this.setComponentProperty(outputs[j], (function (emitter) { return function (value) { return emitter.emit(value); }; })(emitter));
- }
- for (var k = 0; k < propOuts.length; k++) {
- this[propOuts[k]] = new core_1.EventEmitter();
- this.checkLastValues.push(INITIAL_VALUE);
- }
- }
- UpgradeNg1ComponentAdapter.prototype.ngOnChanges = function (changes) {
- for (var name in changes) {
- if (changes.hasOwnProperty(name)) {
- var change = changes[name];
- this.setComponentProperty(name, change.currentValue);
- }
- }
- };
- UpgradeNg1ComponentAdapter.prototype.ngDoCheck = function () {
- var count = 0;
- var destinationObj = this.destinationObj;
- var lastValues = this.checkLastValues;
- var checkProperties = this.checkProperties;
- for (var i = 0; i < checkProperties.length; i++) {
- var value = destinationObj[checkProperties[i]];
- var last = lastValues[i];
- if (value !== last) {
- if (typeof value == 'number' && isNaN(value) && typeof last == 'number' && isNaN(last)) {
- }
- else {
- var eventEmitter = this[this.propOuts[i]];
- eventEmitter.emit(lastValues[i] = value);
- }
- }
- }
- return count;
- };
- UpgradeNg1ComponentAdapter.prototype.setComponentProperty = function (name, value) {
- this.destinationObj[this.propertyMap[name]] = value;
- };
- UpgradeNg1ComponentAdapter.prototype.resolveRequired = function ($element, require) {
- if (!require) {
- return undefined;
- }
- else if (typeof require == 'string') {
- var name = require;
- var isOptional = false;
- var startParent = false;
- var searchParents = false;
- var ch;
- if (name.charAt(0) == '?') {
- isOptional = true;
- name = name.substr(1);
- }
- if (name.charAt(0) == '^') {
- searchParents = true;
- name = name.substr(1);
- }
- if (name.charAt(0) == '^') {
- startParent = true;
- name = name.substr(1);
- }
- var key = util_1.controllerKey(name);
- if (startParent)
- $element = $element.parent();
- var dep = searchParents ? $element.inheritedData(key) : $element.data(key);
- if (!dep && !isOptional) {
- throw new Error("Can not locate '" + require + "' in '" + this.directive.name + "'.");
- }
- return dep;
- }
- else if (require instanceof Array) {
- var deps = [];
- for (var i = 0; i < require.length; i++) {
- deps.push(this.resolveRequired($element, require[i]));
- }
- return deps;
- }
- throw new Error("Directive '" + this.directive.name + "' require syntax unrecognized: " + this.directive.require);
- };
- return UpgradeNg1ComponentAdapter;
- })();
- /***/ },
- /* 258 */
- /***/ function(module, exports) {
- function noNg() {
- throw new Error('AngularJS v1.x is not loaded!');
- }
- var angular = { bootstrap: noNg, module: noNg, element: noNg, version: noNg };
- try {
- if (window.hasOwnProperty('angular')) {
- angular = window.angular;
- }
- }
- catch (e) {
- }
- exports.bootstrap = angular.bootstrap;
- exports.module = angular.module;
- exports.element = angular.element;
- exports.version = angular.version;
- /***/ }
- /******/ ])
- });
- ;
|