12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = global || self, global.less = factory());
- }(this, (function () { 'use strict';
-
- var defaultOptions = (function () { return ({
-
- javascriptEnabled: false,
-
- depends: false,
-
- compress: false,
-
- lint: false,
-
- paths: [],
-
- color: true,
-
- strictImports: false,
-
- insecure: false,
-
- rootpath: '',
-
- rewriteUrls: false,
-
- math: 0,
-
- strictUnits: false,
-
- globalVars: null,
-
- modifyVars: null,
-
- urlArgs: ''
- }); });
- function extractId(href) {
- return href.replace(/^[a-z-]+:\/+?[^\/]+/, '')
- .replace(/[\?\&]livereload=\w+/, '')
- .replace(/^\//, '')
- .replace(/\.[a-zA-Z]+$/, '')
- .replace(/[^\.\w-]+/g, '-')
- .replace(/\./g, ':');
- }
- function addDataAttr(options, tag) {
- for (var opt in tag.dataset) {
- if (tag.dataset.hasOwnProperty(opt)) {
- if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
- options[opt] = tag.dataset[opt];
- }
- else {
- try {
- options[opt] = JSON.parse(tag.dataset[opt]);
- }
- catch (_) { }
- }
- }
- }
- }
- var browser = {
- createCSS: function (document, styles, sheet) {
-
- var href = sheet.href || '';
-
- var id = "less:" + (sheet.title || extractId(href));
-
- var oldStyleNode = document.getElementById(id);
- var keepOldStyleNode = false;
-
- var styleNode = document.createElement('style');
- styleNode.setAttribute('type', 'text/css');
- if (sheet.media) {
- styleNode.setAttribute('media', sheet.media);
- }
- styleNode.id = id;
- if (!styleNode.styleSheet) {
- styleNode.appendChild(document.createTextNode(styles));
-
- keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
- oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
- }
- var head = document.getElementsByTagName('head')[0];
-
-
- if (oldStyleNode === null || keepOldStyleNode === false) {
- var nextEl = sheet && sheet.nextSibling || null;
- if (nextEl) {
- nextEl.parentNode.insertBefore(styleNode, nextEl);
- }
- else {
- head.appendChild(styleNode);
- }
- }
- if (oldStyleNode && keepOldStyleNode === false) {
- oldStyleNode.parentNode.removeChild(oldStyleNode);
- }
-
-
-
- if (styleNode.styleSheet) {
- try {
- styleNode.styleSheet.cssText = styles;
- }
- catch (e) {
- throw new Error('Couldn\'t reassign styleSheet.cssText.');
- }
- }
- },
- currentScript: function (window) {
- var document = window.document;
- return document.currentScript || (function () {
- var scripts = document.getElementsByTagName('script');
- return scripts[scripts.length - 1];
- })();
- }
- };
- var addDefaultOptions = (function (window, options) {
-
- addDataAttr(options, browser.currentScript(window));
- if (options.isFileProtocol === undefined) {
- options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
- }
-
-
-
-
-
-
- options.async = options.async || false;
- options.fileAsync = options.fileAsync || false;
-
- options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
- options.env = options.env || (window.location.hostname == '127.0.0.1' ||
- window.location.hostname == '0.0.0.0' ||
- window.location.hostname == 'localhost' ||
- (window.location.port &&
- window.location.port.length > 0) ||
- options.isFileProtocol ? 'development'
- : 'production');
- var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
- if (dumpLineNumbers) {
- options.dumpLineNumbers = dumpLineNumbers[1];
- }
- if (options.useFileCache === undefined) {
- options.useFileCache = true;
- }
- if (options.onReady === undefined) {
- options.onReady = true;
- }
- if (options.relativeUrls) {
- options.rewriteUrls = 'all';
- }
- });
-
-
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b)
- if (b.hasOwnProperty(p))
- d[p] = b[p]; };
- return extendStatics(d, b);
- };
- function __extends(d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- function __spreadArrays() {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++)
- s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
- }
- var colors = {
- 'aliceblue': '#f0f8ff',
- 'antiquewhite': '#faebd7',
- 'aqua': '#00ffff',
- 'aquamarine': '#7fffd4',
- 'azure': '#f0ffff',
- 'beige': '#f5f5dc',
- 'bisque': '#ffe4c4',
- 'black': '#000000',
- 'blanchedalmond': '#ffebcd',
- 'blue': '#0000ff',
- 'blueviolet': '#8a2be2',
- 'brown': '#a52a2a',
- 'burlywood': '#deb887',
- 'cadetblue': '#5f9ea0',
- 'chartreuse': '#7fff00',
- 'chocolate': '#d2691e',
- 'coral': '#ff7f50',
- 'cornflowerblue': '#6495ed',
- 'cornsilk': '#fff8dc',
- 'crimson': '#dc143c',
- 'cyan': '#00ffff',
- 'darkblue': '#00008b',
- 'darkcyan': '#008b8b',
- 'darkgoldenrod': '#b8860b',
- 'darkgray': '#a9a9a9',
- 'darkgrey': '#a9a9a9',
- 'darkgreen': '#006400',
- 'darkkhaki': '#bdb76b',
- 'darkmagenta': '#8b008b',
- 'darkolivegreen': '#556b2f',
- 'darkorange': '#ff8c00',
- 'darkorchid': '#9932cc',
- 'darkred': '#8b0000',
- 'darksalmon': '#e9967a',
- 'darkseagreen': '#8fbc8f',
- 'darkslateblue': '#483d8b',
- 'darkslategray': '#2f4f4f',
- 'darkslategrey': '#2f4f4f',
- 'darkturquoise': '#00ced1',
- 'darkviolet': '#9400d3',
- 'deeppink': '#ff1493',
- 'deepskyblue': '#00bfff',
- 'dimgray': '#696969',
- 'dimgrey': '#696969',
- 'dodgerblue': '#1e90ff',
- 'firebrick': '#b22222',
- 'floralwhite': '#fffaf0',
- 'forestgreen': '#228b22',
- 'fuchsia': '#ff00ff',
- 'gainsboro': '#dcdcdc',
- 'ghostwhite': '#f8f8ff',
- 'gold': '#ffd700',
- 'goldenrod': '#daa520',
- 'gray': '#808080',
- 'grey': '#808080',
- 'green': '#008000',
- 'greenyellow': '#adff2f',
- 'honeydew': '#f0fff0',
- 'hotpink': '#ff69b4',
- 'indianred': '#cd5c5c',
- 'indigo': '#4b0082',
- 'ivory': '#fffff0',
- 'khaki': '#f0e68c',
- 'lavender': '#e6e6fa',
- 'lavenderblush': '#fff0f5',
- 'lawngreen': '#7cfc00',
- 'lemonchiffon': '#fffacd',
- 'lightblue': '#add8e6',
- 'lightcoral': '#f08080',
- 'lightcyan': '#e0ffff',
- 'lightgoldenrodyellow': '#fafad2',
- 'lightgray': '#d3d3d3',
- 'lightgrey': '#d3d3d3',
- 'lightgreen': '#90ee90',
- 'lightpink': '#ffb6c1',
- 'lightsalmon': '#ffa07a',
- 'lightseagreen': '#20b2aa',
- 'lightskyblue': '#87cefa',
- 'lightslategray': '#778899',
- 'lightslategrey': '#778899',
- 'lightsteelblue': '#b0c4de',
- 'lightyellow': '#ffffe0',
- 'lime': '#00ff00',
- 'limegreen': '#32cd32',
- 'linen': '#faf0e6',
- 'magenta': '#ff00ff',
- 'maroon': '#800000',
- 'mediumaquamarine': '#66cdaa',
- 'mediumblue': '#0000cd',
- 'mediumorchid': '#ba55d3',
- 'mediumpurple': '#9370d8',
- 'mediumseagreen': '#3cb371',
- 'mediumslateblue': '#7b68ee',
- 'mediumspringgreen': '#00fa9a',
- 'mediumturquoise': '#48d1cc',
- 'mediumvioletred': '#c71585',
- 'midnightblue': '#191970',
- 'mintcream': '#f5fffa',
- 'mistyrose': '#ffe4e1',
- 'moccasin': '#ffe4b5',
- 'navajowhite': '#ffdead',
- 'navy': '#000080',
- 'oldlace': '#fdf5e6',
- 'olive': '#808000',
- 'olivedrab': '#6b8e23',
- 'orange': '#ffa500',
- 'orangered': '#ff4500',
- 'orchid': '#da70d6',
- 'palegoldenrod': '#eee8aa',
- 'palegreen': '#98fb98',
- 'paleturquoise': '#afeeee',
- 'palevioletred': '#d87093',
- 'papayawhip': '#ffefd5',
- 'peachpuff': '#ffdab9',
- 'peru': '#cd853f',
- 'pink': '#ffc0cb',
- 'plum': '#dda0dd',
- 'powderblue': '#b0e0e6',
- 'purple': '#800080',
- 'rebeccapurple': '#663399',
- 'red': '#ff0000',
- 'rosybrown': '#bc8f8f',
- 'royalblue': '#4169e1',
- 'saddlebrown': '#8b4513',
- 'salmon': '#fa8072',
- 'sandybrown': '#f4a460',
- 'seagreen': '#2e8b57',
- 'seashell': '#fff5ee',
- 'sienna': '#a0522d',
- 'silver': '#c0c0c0',
- 'skyblue': '#87ceeb',
- 'slateblue': '#6a5acd',
- 'slategray': '#708090',
- 'slategrey': '#708090',
- 'snow': '#fffafa',
- 'springgreen': '#00ff7f',
- 'steelblue': '#4682b4',
- 'tan': '#d2b48c',
- 'teal': '#008080',
- 'thistle': '#d8bfd8',
- 'tomato': '#ff6347',
- 'turquoise': '#40e0d0',
- 'violet': '#ee82ee',
- 'wheat': '#f5deb3',
- 'white': '#ffffff',
- 'whitesmoke': '#f5f5f5',
- 'yellow': '#ffff00',
- 'yellowgreen': '#9acd32'
- };
- var unitConversions = {
- length: {
- 'm': 1,
- 'cm': 0.01,
- 'mm': 0.001,
- 'in': 0.0254,
- 'px': 0.0254 / 96,
- 'pt': 0.0254 / 72,
- 'pc': 0.0254 / 72 * 12
- },
- duration: {
- 's': 1,
- 'ms': 0.001
- },
- angle: {
- 'rad': 1 / (2 * Math.PI),
- 'deg': 1 / 360,
- 'grad': 1 / 400,
- 'turn': 1
- }
- };
- var data = { colors: colors, unitConversions: unitConversions };
-
- var Node = (function () {
- function Node() {
- this.parent = null;
- this.visibilityBlocks = undefined;
- this.nodeVisible = undefined;
- this.rootNode = null;
- this.parsed = null;
- var self = this;
- Object.defineProperty(this, 'currentFileInfo', {
- get: function () { return self.fileInfo(); }
- });
- Object.defineProperty(this, 'index', {
- get: function () { return self.getIndex(); }
- });
- }
- Node.prototype.setParent = function (nodes, parent) {
- function set(node) {
- if (node && node instanceof Node) {
- node.parent = parent;
- }
- }
- if (Array.isArray(nodes)) {
- nodes.forEach(set);
- }
- else {
- set(nodes);
- }
- };
- Node.prototype.getIndex = function () {
- return this._index || (this.parent && this.parent.getIndex()) || 0;
- };
- Node.prototype.fileInfo = function () {
- return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
- };
- Node.prototype.isRulesetLike = function () {
- return false;
- };
- Node.prototype.toCSS = function (context) {
- var strs = [];
- this.genCSS(context, {
- add: function (chunk, fileInfo, index) {
- strs.push(chunk);
- },
- isEmpty: function () {
- return strs.length === 0;
- }
- });
- return strs.join('');
- };
- Node.prototype.genCSS = function (context, output) {
- output.add(this.value);
- };
- Node.prototype.accept = function (visitor) {
- this.value = visitor.visit(this.value);
- };
- Node.prototype.eval = function () { return this; };
- Node.prototype._operate = function (context, op, a, b) {
- switch (op) {
- case '+': return a + b;
- case '-': return a - b;
- case '*': return a * b;
- case '/': return a / b;
- }
- };
- Node.prototype.fround = function (context, value) {
- var precision = context && context.numPrecision;
-
- return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
- };
-
- Node.prototype.blocksVisibility = function () {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
- return this.visibilityBlocks !== 0;
- };
- Node.prototype.addVisibilityBlock = function () {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
- this.visibilityBlocks = this.visibilityBlocks + 1;
- };
- Node.prototype.removeVisibilityBlock = function () {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
- this.visibilityBlocks = this.visibilityBlocks - 1;
- };
-
-
- Node.prototype.ensureVisibility = function () {
- this.nodeVisible = true;
- };
-
-
- Node.prototype.ensureInvisibility = function () {
- this.nodeVisible = false;
- };
-
-
-
-
- Node.prototype.isVisible = function () {
- return this.nodeVisible;
- };
- Node.prototype.visibilityInfo = function () {
- return {
- visibilityBlocks: this.visibilityBlocks,
- nodeVisible: this.nodeVisible
- };
- };
- Node.prototype.copyVisibilityInfo = function (info) {
- if (!info) {
- return;
- }
- this.visibilityBlocks = info.visibilityBlocks;
- this.nodeVisible = info.nodeVisible;
- };
- return Node;
- }());
- Node.compare = function (a, b) {
-
- if ((a.compare) &&
-
-
- !(b.type === 'Quoted' || b.type === 'Anonymous')) {
- return a.compare(b);
- }
- else if (b.compare) {
- return -b.compare(a);
- }
- else if (a.type !== b.type) {
- return undefined;
- }
- a = a.value;
- b = b.value;
- if (!Array.isArray(a)) {
- return a === b ? 0 : undefined;
- }
- if (a.length !== b.length) {
- return undefined;
- }
- for (var i = 0; i < a.length; i++) {
- if (Node.compare(a[i], b[i]) !== 0) {
- return undefined;
- }
- }
- return 0;
- };
- Node.numericCompare = function (a, b) { return a < b ? -1
- : a === b ? 0
- : a > b ? 1 : undefined; };
-
-
-
- var Color = function (rgb, a, originalForm) {
- var self = this;
-
-
-
-
-
-
- if (Array.isArray(rgb)) {
- this.rgb = rgb;
- }
- else if (rgb.length >= 6) {
- this.rgb = [];
- rgb.match(/.{2}/g).map(function (c, i) {
- if (i < 3) {
- self.rgb.push(parseInt(c, 16));
- }
- else {
- self.alpha = (parseInt(c, 16)) / 255;
- }
- });
- }
- else {
- this.rgb = [];
- rgb.split('').map(function (c, i) {
- if (i < 3) {
- self.rgb.push(parseInt(c + c, 16));
- }
- else {
- self.alpha = (parseInt(c + c, 16)) / 255;
- }
- });
- }
- this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
- if (typeof originalForm !== 'undefined') {
- this.value = originalForm;
- }
- };
- Color.prototype = new Node();
- Color.prototype.luma = function () {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
- g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
- b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
- };
- Color.prototype.genCSS = function (context, output) {
- output.add(this.toCSS(context));
- };
- Color.prototype.toCSS = function (context, doNotCompress) {
- var compress = context && context.compress && !doNotCompress;
- var color;
- var alpha;
- var colorFunction;
- var args = [];
-
-
-
- alpha = this.fround(context, this.alpha);
- if (this.value) {
- if (this.value.indexOf('rgb') === 0) {
- if (alpha < 1) {
- colorFunction = 'rgba';
- }
- }
- else if (this.value.indexOf('hsl') === 0) {
- if (alpha < 1) {
- colorFunction = 'hsla';
- }
- else {
- colorFunction = 'hsl';
- }
- }
- else {
- return this.value;
- }
- }
- else {
- if (alpha < 1) {
- colorFunction = 'rgba';
- }
- }
- switch (colorFunction) {
- case 'rgba':
- args = this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1));
- break;
- case 'hsla':
- args.push(clamp(alpha, 1));
- case 'hsl':
- color = this.toHSL();
- args = [
- this.fround(context, color.h),
- this.fround(context, color.s * 100) + "%",
- this.fround(context, color.l * 100) + "%"
- ].concat(args);
- }
- if (colorFunction) {
-
- return colorFunction + "(" + args.join("," + (compress ? '' : ' ')) + ")";
- }
- color = this.toRGB();
- if (compress) {
- var splitcolor = color.split('');
-
- if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
- color = "#" + splitcolor[1] + splitcolor[3] + splitcolor[5];
- }
- }
- return color;
- };
-
-
-
-
-
-
- Color.prototype.operate = function (context, op, other) {
- var rgb = new Array(3);
- var alpha = this.alpha * (1 - other.alpha) + other.alpha;
- for (var c = 0; c < 3; c++) {
- rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
- }
- return new Color(rgb, alpha);
- };
- Color.prototype.toRGB = function () {
- return toHex(this.rgb);
- };
- Color.prototype.toHSL = function () {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- var a = this.alpha;
- var max = Math.max(r, g, b);
- var min = Math.min(r, g, b);
- var h;
- var s;
- var l = (max + min) / 2;
- var d = max - min;
- if (max === min) {
- h = s = 0;
- }
- else {
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
- case g:
- h = (b - r) / d + 2;
- break;
- case b:
- h = (r - g) / d + 4;
- break;
- }
- h /= 6;
- }
- return { h: h * 360, s: s, l: l, a: a };
- };
-
- Color.prototype.toHSV = function () {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- var a = this.alpha;
- var max = Math.max(r, g, b);
- var min = Math.min(r, g, b);
- var h;
- var s;
- var v = max;
- var d = max - min;
- if (max === 0) {
- s = 0;
- }
- else {
- s = d / max;
- }
- if (max === min) {
- h = 0;
- }
- else {
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
- case g:
- h = (b - r) / d + 2;
- break;
- case b:
- h = (r - g) / d + 4;
- break;
- }
- h /= 6;
- }
- return { h: h * 360, s: s, v: v, a: a };
- };
- Color.prototype.toARGB = function () {
- return toHex([this.alpha * 255].concat(this.rgb));
- };
- Color.prototype.compare = function (x) {
- return (x.rgb &&
- x.rgb[0] === this.rgb[0] &&
- x.rgb[1] === this.rgb[1] &&
- x.rgb[2] === this.rgb[2] &&
- x.alpha === this.alpha) ? 0 : undefined;
- };
- Color.prototype.type = 'Color';
- function clamp(v, max) {
- return Math.min(Math.max(v, 0), max);
- }
- function toHex(v) {
- return "#" + v.map(function (c) {
- c = clamp(Math.round(c), 255);
- return (c < 16 ? '0' : '') + c.toString(16);
- }).join('');
- }
- Color.fromKeyword = function (keyword) {
- var c;
- var key = keyword.toLowerCase();
- if (colors.hasOwnProperty(key)) {
- c = new Color(colors[key].slice(1));
- }
- else if (key === 'transparent') {
- c = new Color([0, 0, 0], 0);
- }
- if (c) {
- c.value = keyword;
- return c;
- }
- };
- var Paren = function (node) {
- this.value = node;
- };
- Paren.prototype = new Node();
- Paren.prototype.genCSS = function (context, output) {
- output.add('(');
- this.value.genCSS(context, output);
- output.add(')');
- };
- Paren.prototype.eval = function (context) {
- return new Paren(this.value.eval(context));
- };
- Paren.prototype.type = 'Paren';
- var _noSpaceCombinators = {
- '': true,
- ' ': true,
- '|': true
- };
- var Combinator = function (value) {
- if (value === ' ') {
- this.value = ' ';
- this.emptyOrWhitespace = true;
- }
- else {
- this.value = value ? value.trim() : '';
- this.emptyOrWhitespace = this.value === '';
- }
- };
- Combinator.prototype = new Node();
- Combinator.prototype.genCSS = function (context, output) {
- var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
- output.add(spaceOrEmpty + this.value + spaceOrEmpty);
- };
- Combinator.prototype.type = 'Combinator';
- var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
- this.combinator = combinator instanceof Combinator ?
- combinator : new Combinator(combinator);
- if (typeof value === 'string') {
- this.value = value.trim();
- }
- else if (value) {
- this.value = value;
- }
- else {
- this.value = '';
- }
- this.isVariable = isVariable;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.copyVisibilityInfo(visibilityInfo);
- this.setParent(this.combinator, this);
- };
- Element.prototype = new Node();
- Element.prototype.accept = function (visitor) {
- var value = this.value;
- this.combinator = visitor.visit(this.combinator);
- if (typeof value === 'object') {
- this.value = visitor.visit(value);
- }
- };
- Element.prototype.eval = function (context) {
- return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- };
- Element.prototype.clone = function () {
- return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- };
- Element.prototype.genCSS = function (context, output) {
- output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
- };
- Element.prototype.toCSS = function (context) {
- if (context === void 0) { context = {}; }
- var value = this.value;
- var firstSelector = context.firstSelector;
- if (value instanceof Paren) {
-
-
- context.firstSelector = true;
- }
- value = value.toCSS ? value.toCSS(context) : value;
- context.firstSelector = firstSelector;
- if (value === '' && this.combinator.value.charAt(0) === '&') {
- return '';
- }
- else {
- return this.combinator.toCSS(context) + value;
- }
- };
- Element.prototype.type = 'Element';
- var Math$1 = {
- ALWAYS: 0,
- PARENS_DIVISION: 1,
- PARENS: 2,
- STRICT_LEGACY: 3
- };
- var RewriteUrls = {
- OFF: 0,
- LOCAL: 1,
- ALL: 2
- };
-
- function getType(payload) {
- return Object.prototype.toString.call(payload).slice(8, -1);
- }
-
- function isPlainObject(payload) {
- if (getType(payload) !== 'Object')
- return false;
- return payload.constructor === Object && Object.getPrototypeOf(payload) === Object.prototype;
- }
-
- function isArray(payload) {
- return getType(payload) === 'Array';
- }
-
- function __spreadArrays$1() {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++)
- s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
- }
- function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
- var propType = {}.propertyIsEnumerable.call(originalObject, key)
- ? 'enumerable'
- : 'nonenumerable';
- if (propType === 'enumerable')
- carry[key] = newVal;
- if (includeNonenumerable && propType === 'nonenumerable') {
- Object.defineProperty(carry, key, {
- value: newVal,
- enumerable: false,
- writable: true,
- configurable: true,
- });
- }
- }
-
- function copy(target, options) {
- if (options === void 0) {
- options = {};
- }
- if (isArray(target))
- return target.map(function (i) { return copy(i, options); });
- if (!isPlainObject(target))
- return target;
- var props = Object.getOwnPropertyNames(target);
- var symbols = Object.getOwnPropertySymbols(target);
- return __spreadArrays$1(props, symbols).reduce(function (carry, key) {
- if (isArray(options.props) && !options.props.includes(key)) {
- return carry;
- }
- var val = target[key];
- var newVal = copy(val, options);
- assignProp(carry, key, newVal, target, options.nonenumerable);
- return carry;
- }, {});
- }
-
- function getLocation(index, inputStream) {
- var n = index + 1;
- var line = null;
- var column = -1;
- while (--n >= 0 && inputStream.charAt(n) !== '\n') {
- column++;
- }
- if (typeof index === 'number') {
- line = (inputStream.slice(0, index).match(/\n/g) || '').length;
- }
- return {
- line: line,
- column: column
- };
- }
- function copyArray(arr) {
- var i;
- var length = arr.length;
- var copy = new Array(length);
- for (i = 0; i < length; i++) {
- copy[i] = arr[i];
- }
- return copy;
- }
- function clone(obj) {
- var cloned = {};
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- cloned[prop] = obj[prop];
- }
- }
- return cloned;
- }
- function defaults(obj1, obj2) {
- var newObj = obj2 || {};
- if (!obj2._defaults) {
- newObj = {};
- var defaults_1 = copy(obj1);
- newObj._defaults = defaults_1;
- var cloned = obj2 ? copy(obj2) : {};
- Object.assign(newObj, defaults_1, cloned);
- }
- return newObj;
- }
- function copyOptions(obj1, obj2) {
- if (obj2 && obj2._defaults) {
- return obj2;
- }
- var opts = defaults(obj1, obj2);
- if (opts.strictMath) {
- opts.math = Math$1.STRICT_LEGACY;
- }
-
- if (opts.relativeUrls) {
- opts.rewriteUrls = RewriteUrls.ALL;
- }
- if (typeof opts.math === 'string') {
- switch (opts.math.toLowerCase()) {
- case 'always':
- opts.math = Math$1.ALWAYS;
- break;
- case 'parens-division':
- opts.math = Math$1.PARENS_DIVISION;
- break;
- case 'strict':
- case 'parens':
- opts.math = Math$1.PARENS;
- break;
- case 'strict-legacy':
- opts.math = Math$1.STRICT_LEGACY;
- }
- }
- if (typeof opts.rewriteUrls === 'string') {
- switch (opts.rewriteUrls.toLowerCase()) {
- case 'off':
- opts.rewriteUrls = RewriteUrls.OFF;
- break;
- case 'local':
- opts.rewriteUrls = RewriteUrls.LOCAL;
- break;
- case 'all':
- opts.rewriteUrls = RewriteUrls.ALL;
- break;
- }
- }
- return opts;
- }
- function merge(obj1, obj2) {
- for (var prop in obj2) {
- if (obj2.hasOwnProperty(prop)) {
- obj1[prop] = obj2[prop];
- }
- }
- return obj1;
- }
- function flattenArray(arr, result) {
- if (result === void 0) { result = []; }
- for (var i = 0, length_1 = arr.length; i < length_1; i++) {
- var value = arr[i];
- if (Array.isArray(value)) {
- flattenArray(value, result);
- }
- else {
- if (value !== undefined) {
- result.push(value);
- }
- }
- }
- return result;
- }
- var utils = Object.freeze({
- __proto__: null,
- getLocation: getLocation,
- copyArray: copyArray,
- clone: clone,
- defaults: defaults,
- copyOptions: copyOptions,
- merge: merge,
- flattenArray: flattenArray
- });
- var anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
-
- var LessError = function LessError(e, fileContentMap, currentFilename) {
- Error.call(this);
- var filename = e.filename || currentFilename;
- this.message = e.message;
- this.stack = e.stack;
- if (fileContentMap && filename) {
- var input = fileContentMap.contents[filename];
- var loc = getLocation(e.index, input);
- var line = loc.line;
- var col = loc.column;
- var callLine = e.call && getLocation(e.call, input).line;
- var lines = input ? input.split('\n') : '';
- this.type = e.type || 'Syntax';
- this.filename = filename;
- this.index = e.index;
- this.line = typeof line === 'number' ? line + 1 : null;
- this.column = col;
- if (!this.line && this.stack) {
- var found = this.stack.match(anonymousFunc);
-
- var func = new Function('a', 'throw new Error()');
- var lineAdjust = 0;
- try {
- func();
- }
- catch (e) {
- var match = e.stack.match(anonymousFunc);
- var line_1 = parseInt(match[2]);
- lineAdjust = 1 - line_1;
- }
- if (found) {
- if (found[2]) {
- this.line = parseInt(found[2]) + lineAdjust;
- }
- if (found[3]) {
- this.column = parseInt(found[3]);
- }
- }
- }
- this.callLine = callLine + 1;
- this.callExtract = lines[callLine];
- this.extract = [
- lines[this.line - 2],
- lines[this.line - 1],
- lines[this.line]
- ];
- }
- };
- if (typeof Object.create === 'undefined') {
- var F = function () { };
- F.prototype = Error.prototype;
- LessError.prototype = new F();
- }
- else {
- LessError.prototype = Object.create(Error.prototype);
- }
- LessError.prototype.constructor = LessError;
-
- LessError.prototype.toString = function (options) {
- if (options === void 0) { options = {}; }
- var message = '';
- var extract = this.extract || [];
- var error = [];
- var stylize = function (str) { return str; };
- if (options.stylize) {
- var type = typeof options.stylize;
- if (type !== 'function') {
- throw Error("options.stylize should be a function, got a " + type + "!");
- }
- stylize = options.stylize;
- }
- if (this.line !== null) {
- if (typeof extract[0] === 'string') {
- error.push(stylize(this.line - 1 + " " + extract[0], 'grey'));
- }
- if (typeof extract[1] === 'string') {
- var errorTxt = this.line + " ";
- if (extract[1]) {
- errorTxt += extract[1].slice(0, this.column) +
- stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
- extract[1].slice(this.column + 1), 'red'), 'inverse');
- }
- error.push(errorTxt);
- }
- if (typeof extract[2] === 'string') {
- error.push(stylize(this.line + 1 + " " + extract[2], 'grey'));
- }
- error = error.join('\n') + stylize('', 'reset') + "\n";
- }
- message += stylize(this.type + "Error: " + this.message, 'red');
- if (this.filename) {
- message += stylize(' in ', 'red') + this.filename;
- }
- if (this.line) {
- message += stylize(" on line " + this.line + ", column " + (this.column + 1) + ":", 'grey');
- }
- message += "\n" + error;
- if (this.callLine) {
- message += stylize('from ', 'red') + (this.filename || '') + "/n";
- message += stylize(this.callLine, 'grey') + " " + this.callExtract + "/n";
- }
- return message;
- };
- var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
- this.extendList = extendList;
- this.condition = condition;
- this.evaldCondition = !condition;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.elements = this.getElements(elements);
- this.mixinElements_ = undefined;
- this.copyVisibilityInfo(visibilityInfo);
- this.setParent(this.elements, this);
- };
- Selector.prototype = new Node();
- Selector.prototype.accept = function (visitor) {
- if (this.elements) {
- this.elements = visitor.visitArray(this.elements);
- }
- if (this.extendList) {
- this.extendList = visitor.visitArray(this.extendList);
- }
- if (this.condition) {
- this.condition = visitor.visit(this.condition);
- }
- };
- Selector.prototype.createDerived = function (elements, extendList, evaldCondition) {
- elements = this.getElements(elements);
- var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
- newSelector.mediaEmpty = this.mediaEmpty;
- return newSelector;
- };
- Selector.prototype.getElements = function (els) {
- if (!els) {
- return [new Element('', '&', false, this._index, this._fileInfo)];
- }
- if (typeof els === 'string') {
- this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
- if (err) {
- throw new LessError({
- index: err.index,
- message: err.message
- }, this.parse.imports, this._fileInfo.filename);
- }
- els = result[0].elements;
- });
- }
- return els;
- };
- Selector.prototype.createEmptySelectors = function () {
- var el = new Element('', '&', false, this._index, this._fileInfo);
- var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
- sels[0].mediaEmpty = true;
- return sels;
- };
- Selector.prototype.match = function (other) {
- var elements = this.elements;
- var len = elements.length;
- var olen;
- var i;
- other = other.mixinElements();
- olen = other.length;
- if (olen === 0 || len < olen) {
- return 0;
- }
- else {
- for (i = 0; i < olen; i++) {
- if (elements[i].value !== other[i]) {
- return 0;
- }
- }
- }
- return olen;
- };
- Selector.prototype.mixinElements = function () {
- if (this.mixinElements_) {
- return this.mixinElements_;
- }
- var elements = this.elements.map(function (v) { return v.combinator.value + (v.value.value || v.value); }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
- if (elements) {
- if (elements[0] === '&') {
- elements.shift();
- }
- }
- else {
- elements = [];
- }
- return (this.mixinElements_ = elements);
- };
- Selector.prototype.isJustParentSelector = function () {
- return !this.mediaEmpty &&
- this.elements.length === 1 &&
- this.elements[0].value === '&' &&
- (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
- };
- Selector.prototype.eval = function (context) {
- var evaldCondition = this.condition && this.condition.eval(context);
- var elements = this.elements;
- var extendList = this.extendList;
- elements = elements && elements.map(function (e) { return e.eval(context); });
- extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
- return this.createDerived(elements, extendList, evaldCondition);
- };
- Selector.prototype.genCSS = function (context, output) {
- var i;
- var element;
- if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
- output.add(' ', this.fileInfo(), this.getIndex());
- }
- for (i = 0; i < this.elements.length; i++) {
- element = this.elements[i];
- element.genCSS(context, output);
- }
- };
- Selector.prototype.getIsOutput = function () {
- return this.evaldCondition;
- };
- Selector.prototype.type = 'Selector';
- var Value = function (value) {
- if (!value) {
- throw new Error('Value requires an array argument');
- }
- if (!Array.isArray(value)) {
- this.value = [value];
- }
- else {
- this.value = value;
- }
- };
- Value.prototype = new Node();
- Value.prototype.accept = function (visitor) {
- if (this.value) {
- this.value = visitor.visitArray(this.value);
- }
- };
- Value.prototype.eval = function (context) {
- if (this.value.length === 1) {
- return this.value[0].eval(context);
- }
- else {
- return new Value(this.value.map(function (v) { return v.eval(context); }));
- }
- };
- Value.prototype.genCSS = function (context, output) {
- var i;
- for (i = 0; i < this.value.length; i++) {
- this.value[i].genCSS(context, output);
- if (i + 1 < this.value.length) {
- output.add((context && context.compress) ? ',' : ', ');
- }
- }
- };
- Value.prototype.type = 'Value';
- var Keyword = function (value) {
- this.value = value;
- };
- Keyword.prototype = new Node();
- Keyword.prototype.genCSS = function (context, output) {
- if (this.value === '%') {
- throw { type: 'Syntax', message: 'Invalid % without number' };
- }
- output.add(this.value);
- };
- Keyword.prototype.type = 'Keyword';
- Keyword.True = new Keyword('true');
- Keyword.False = new Keyword('false');
- var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
- this.value = value;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.mapLines = mapLines;
- this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
- this.allowRoot = true;
- this.copyVisibilityInfo(visibilityInfo);
- };
- Anonymous.prototype = new Node();
- Anonymous.prototype.eval = function () {
- return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
- };
- Anonymous.prototype.compare = function (other) {
- return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
- };
- Anonymous.prototype.isRulesetLike = function () {
- return this.rulesetLike;
- };
- Anonymous.prototype.genCSS = function (context, output) {
- this.nodeVisible = Boolean(this.value);
- if (this.nodeVisible) {
- output.add(this.value, this._fileInfo, this._index, this.mapLines);
- }
- };
- Anonymous.prototype.type = 'Anonymous';
- var MATH = Math$1;
- var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
- this.name = name;
- this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
- this.important = important ? " " + important.trim() : '';
- this.merge = merge;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.inline = inline || false;
- this.variable = (variable !== undefined) ? variable
- : (name.charAt && (name.charAt(0) === '@'));
- this.allowRoot = true;
- this.setParent(this.value, this);
- };
- Declaration.prototype = new Node();
- Declaration.prototype.genCSS = function (context, output) {
- output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
- try {
- this.value.genCSS(context, output);
- }
- catch (e) {
- e.index = this._index;
- e.filename = this._fileInfo.filename;
- throw e;
- }
- output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
- };
- Declaration.prototype.eval = function (context) {
- var mathBypass = false;
- var prevMath;
- var name = this.name;
- var evaldValue;
- var variable = this.variable;
- if (typeof name !== 'string') {
-
-
- name = (name.length === 1) && (name[0] instanceof Keyword) ?
- name[0].value : evalName(context, name);
- variable = false;
- }
-
- if (name === 'font' && context.math === MATH.ALWAYS) {
- mathBypass = true;
- prevMath = context.math;
- context.math = MATH.PARENS_DIVISION;
- }
- try {
- context.importantScope.push({});
- evaldValue = this.value.eval(context);
- if (!this.variable && evaldValue.type === 'DetachedRuleset') {
- throw { message: 'Rulesets cannot be evaluated on a property.',
- index: this.getIndex(), filename: this.fileInfo().filename };
- }
- var important = this.important;
- var importantResult = context.importantScope.pop();
- if (!important && importantResult.important) {
- important = importantResult.important;
- }
- return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
- }
- catch (e) {
- if (typeof e.index !== 'number') {
- e.index = this.getIndex();
- e.filename = this.fileInfo().filename;
- }
- throw e;
- }
- finally {
- if (mathBypass) {
- context.math = prevMath;
- }
- }
- };
- Declaration.prototype.makeImportant = function () {
- return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
- };
- function evalName(context, name) {
- var value = '';
- var i;
- var n = name.length;
- var output = { add: function (s) { value += s; } };
- for (i = 0; i < n; i++) {
- name[i].eval(context).genCSS(context, output);
- }
- return value;
- }
- Declaration.prototype.type = 'Declaration';
- var debugInfo = function (context, ctx, lineSeparator) {
- var result = '';
- if (context.dumpLineNumbers && !context.compress) {
- switch (context.dumpLineNumbers) {
- case 'comments':
- result = debugInfo.asComment(ctx);
- break;
- case 'mediaquery':
- result = debugInfo.asMediaQuery(ctx);
- break;
- case 'all':
- result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
- break;
- }
- }
- return result;
- };
- debugInfo.asComment = function (ctx) { return ctx.debugInfo ? "/* line " + ctx.debugInfo.lineNumber + ", " + ctx.debugInfo.fileName + " */\n" : ''; };
- debugInfo.asMediaQuery = function (ctx) {
- if (!ctx.debugInfo) {
- return '';
- }
- var filenameWithProtocol = ctx.debugInfo.fileName;
- if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
- filenameWithProtocol = "file://" + filenameWithProtocol;
- }
- return "@media -sass-debug-info{filename{font-family:" + filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
- if (a == '\\') {
- a = '\/';
- }
- return "\\" + a;
- }) + "}line{font-family:\\00003" + ctx.debugInfo.lineNumber + "}}\n";
- };
- var Comment = function (value, isLineComment, index, currentFileInfo) {
- this.value = value;
- this.isLineComment = isLineComment;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.allowRoot = true;
- };
- Comment.prototype = new Node();
- Comment.prototype.genCSS = function (context, output) {
- if (this.debugInfo) {
- output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
- }
- output.add(this.value);
- };
- Comment.prototype.isSilent = function (context) {
- var isCompressed = context.compress && this.value[2] !== '!';
- return this.isLineComment || isCompressed;
- };
- Comment.prototype.type = 'Comment';
- var contexts = {};
- var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
- if (!original) {
- return;
- }
- for (var i = 0; i < propertiesToCopy.length; i++) {
- if (original.hasOwnProperty(propertiesToCopy[i])) {
- destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
- }
- }
- };
-
- var parseCopyProperties = [
-
- 'paths',
- 'rewriteUrls',
- 'rootpath',
- 'strictImports',
- 'insecure',
- 'dumpLineNumbers',
- 'compress',
- 'syncImport',
- 'chunkInput',
- 'mime',
- 'useFileCache',
-
- 'processImports',
-
- 'pluginManager'
- ];
- contexts.Parse = function (options) {
- copyFromOriginal(options, this, parseCopyProperties);
- if (typeof this.paths === 'string') {
- this.paths = [this.paths];
- }
- };
- var evalCopyProperties = [
- 'paths',
- 'compress',
- 'math',
- 'strictUnits',
- 'sourceMap',
- 'importMultiple',
- 'urlArgs',
- 'javascriptEnabled',
- 'pluginManager',
- 'importantScope',
- 'rewriteUrls'
- ];
- function isPathRelative(path) {
- return !/^(?:[a-z-]+:|\/|#)/i.test(path);
- }
- function isPathLocalRelative(path) {
- return path.charAt(0) === '.';
- }
- contexts.Eval = (function () {
- function Eval(options, frames) {
- copyFromOriginal(options, this, evalCopyProperties);
- if (typeof this.paths === 'string') {
- this.paths = [this.paths];
- }
- this.frames = frames || [];
- this.importantScope = this.importantScope || [];
- this.inCalc = false;
- this.mathOn = true;
- }
- Eval.prototype.enterCalc = function () {
- if (!this.calcStack) {
- this.calcStack = [];
- }
- this.calcStack.push(true);
- this.inCalc = true;
- };
- Eval.prototype.exitCalc = function () {
- this.calcStack.pop();
- if (!this.calcStack.length) {
- this.inCalc = false;
- }
- };
- Eval.prototype.inParenthesis = function () {
- if (!this.parensStack) {
- this.parensStack = [];
- }
- this.parensStack.push(true);
- };
- Eval.prototype.outOfParenthesis = function () {
- this.parensStack.pop();
- };
- Eval.prototype.isMathOn = function (op) {
- if (!this.mathOn) {
- return false;
- }
- if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
- return false;
- }
- if (this.math > Math$1.PARENS_DIVISION) {
- return this.parensStack && this.parensStack.length;
- }
- return true;
- };
- Eval.prototype.pathRequiresRewrite = function (path) {
- var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
- return isRelative(path);
- };
- Eval.prototype.rewritePath = function (path, rootpath) {
- var newPath;
- rootpath = rootpath || '';
- newPath = this.normalizePath(rootpath + path);
-
-
- if (isPathLocalRelative(path) &&
- isPathRelative(rootpath) &&
- isPathLocalRelative(newPath) === false) {
- newPath = "./" + newPath;
- }
- return newPath;
- };
- Eval.prototype.normalizePath = function (path) {
- var segments = path.split('/').reverse();
- var segment;
- path = [];
- while (segments.length !== 0) {
- segment = segments.pop();
- switch (segment) {
- case '.':
- break;
- case '..':
- if ((path.length === 0) || (path[path.length - 1] === '..')) {
- path.push(segment);
- }
- else {
- path.pop();
- }
- break;
- default:
- path.push(segment);
- break;
- }
- }
- return path.join('/');
- };
- return Eval;
- }());
- function makeRegistry(base) {
- return {
- _data: {},
- add: function (name, func) {
-
-
- name = name.toLowerCase();
- if (this._data.hasOwnProperty(name)) ;
- this._data[name] = func;
- },
- addMultiple: function (functions) {
- var _this = this;
- Object.keys(functions).forEach(function (name) {
- _this.add(name, functions[name]);
- });
- },
- get: function (name) {
- return this._data[name] || (base && base.get(name));
- },
- getLocalFunctions: function () {
- return this._data;
- },
- inherit: function () {
- return makeRegistry(this);
- },
- create: function (base) {
- return makeRegistry(base);
- }
- };
- }
- var functionRegistry = makeRegistry(null);
- var defaultFunc = {
- eval: function () {
- var v = this.value_;
- var e = this.error_;
- if (e) {
- throw e;
- }
- if (v != null) {
- return v ? Keyword.True : Keyword.False;
- }
- },
- value: function (v) {
- this.value_ = v;
- },
- error: function (e) {
- this.error_ = e;
- },
- reset: function () {
- this.value_ = this.error_ = null;
- }
- };
- var Ruleset = function (selectors, rules, strictImports, visibilityInfo) {
- this.selectors = selectors;
- this.rules = rules;
- this._lookups = {};
- this._variables = null;
- this._properties = null;
- this.strictImports = strictImports;
- this.copyVisibilityInfo(visibilityInfo);
- this.allowRoot = true;
- this.setParent(this.selectors, this);
- this.setParent(this.rules, this);
- };
- Ruleset.prototype = new Node();
- Ruleset.prototype.isRulesetLike = function () {
- return true;
- };
- Ruleset.prototype.accept = function (visitor) {
- if (this.paths) {
- this.paths = visitor.visitArray(this.paths, true);
- }
- else if (this.selectors) {
- this.selectors = visitor.visitArray(this.selectors);
- }
- if (this.rules && this.rules.length) {
- this.rules = visitor.visitArray(this.rules);
- }
- };
- Ruleset.prototype.eval = function (context) {
- var selectors;
- var selCnt;
- var selector;
- var i;
- var hasVariable;
- var hasOnePassingSelector = false;
- if (this.selectors && (selCnt = this.selectors.length)) {
- selectors = new Array(selCnt);
- defaultFunc.error({
- type: 'Syntax',
- message: 'it is currently only allowed in parametric mixin guards,'
- });
- for (i = 0; i < selCnt; i++) {
- selector = this.selectors[i].eval(context);
- for (var j = 0; j < selector.elements.length; j++) {
- if (selector.elements[j].isVariable) {
- hasVariable = true;
- break;
- }
- }
- selectors[i] = selector;
- if (selector.evaldCondition) {
- hasOnePassingSelector = true;
- }
- }
- if (hasVariable) {
- var toParseSelectors = new Array(selCnt);
- for (i = 0; i < selCnt; i++) {
- selector = selectors[i];
- toParseSelectors[i] = selector.toCSS(context);
- }
- this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
- if (result) {
- selectors = flattenArray(result);
- }
- });
- }
- defaultFunc.reset();
- }
- else {
- hasOnePassingSelector = true;
- }
- var rules = this.rules ? copyArray(this.rules) : null;
- var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
- var rule;
- var subRule;
- ruleset.originalRuleset = this;
- ruleset.root = this.root;
- ruleset.firstRoot = this.firstRoot;
- ruleset.allowImports = this.allowImports;
- if (this.debugInfo) {
- ruleset.debugInfo = this.debugInfo;
- }
- if (!hasOnePassingSelector) {
- rules.length = 0;
- }
-
-
- ruleset.functionRegistry = (function (frames) {
- var i = 0;
- var n = frames.length;
- var found;
- for (; i !== n; ++i) {
- found = frames[i].functionRegistry;
- if (found) {
- return found;
- }
- }
- return functionRegistry;
- })(context.frames).inherit();
-
- var ctxFrames = context.frames;
- ctxFrames.unshift(ruleset);
-
- var ctxSelectors = context.selectors;
- if (!ctxSelectors) {
- context.selectors = ctxSelectors = [];
- }
- ctxSelectors.unshift(this.selectors);
-
- if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
- ruleset.evalImports(context);
- }
-
-
- var rsRules = ruleset.rules;
- for (i = 0; (rule = rsRules[i]); i++) {
- if (rule.evalFirst) {
- rsRules[i] = rule.eval(context);
- }
- }
- var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
-
- for (i = 0; (rule = rsRules[i]); i++) {
- if (rule.type === 'MixinCall') {
-
- rules = rule.eval(context).filter(function (r) {
- if ((r instanceof Declaration) && r.variable) {
-
-
-
- return !(ruleset.variable(r.name));
- }
- return true;
- });
- rsRules.splice.apply(rsRules, [i, 1].concat(rules));
- i += rules.length - 1;
- ruleset.resetCache();
- }
- else if (rule.type === 'VariableCall') {
-
- rules = rule.eval(context).rules.filter(function (r) {
- if ((r instanceof Declaration) && r.variable) {
-
- return false;
- }
- return true;
- });
- rsRules.splice.apply(rsRules, [i, 1].concat(rules));
- i += rules.length - 1;
- ruleset.resetCache();
- }
- }
-
- for (i = 0; (rule = rsRules[i]); i++) {
- if (!rule.evalFirst) {
- rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
- }
- }
-
- for (i = 0; (rule = rsRules[i]); i++) {
-
- if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
-
- if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
- rsRules.splice(i--, 1);
- for (var j = 0; (subRule = rule.rules[j]); j++) {
- if (subRule instanceof Node) {
- subRule.copyVisibilityInfo(rule.visibilityInfo());
- if (!(subRule instanceof Declaration) || !subRule.variable) {
- rsRules.splice(++i, 0, subRule);
- }
- }
- }
- }
- }
- }
-
- ctxFrames.shift();
- ctxSelectors.shift();
- if (context.mediaBlocks) {
- for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
- context.mediaBlocks[i].bubbleSelectors(selectors);
- }
- }
- return ruleset;
- };
- Ruleset.prototype.evalImports = function (context) {
- var rules = this.rules;
- var i;
- var importRules;
- if (!rules) {
- return;
- }
- for (i = 0; i < rules.length; i++) {
- if (rules[i].type === 'Import') {
- importRules = rules[i].eval(context);
- if (importRules && (importRules.length || importRules.length === 0)) {
- rules.splice.apply(rules, [i, 1].concat(importRules));
- i += importRules.length - 1;
- }
- else {
- rules.splice(i, 1, importRules);
- }
- this.resetCache();
- }
- }
- };
- Ruleset.prototype.makeImportant = function () {
- var result = new Ruleset(this.selectors, this.rules.map(function (r) {
- if (r.makeImportant) {
- return r.makeImportant();
- }
- else {
- return r;
- }
- }), this.strictImports, this.visibilityInfo());
- return result;
- };
- Ruleset.prototype.matchArgs = function (args) {
- return !args || args.length === 0;
- };
-
- Ruleset.prototype.matchCondition = function (args, context) {
- var lastSelector = this.selectors[this.selectors.length - 1];
- if (!lastSelector.evaldCondition) {
- return false;
- }
- if (lastSelector.condition &&
- !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
- return false;
- }
- return true;
- };
- Ruleset.prototype.resetCache = function () {
- this._rulesets = null;
- this._variables = null;
- this._properties = null;
- this._lookups = {};
- };
- Ruleset.prototype.variables = function () {
- if (!this._variables) {
- this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
- if (r instanceof Declaration && r.variable === true) {
- hash[r.name] = r;
- }
-
-
-
- if (r.type === 'Import' && r.root && r.root.variables) {
- var vars = r.root.variables();
- for (var name_1 in vars) {
- if (vars.hasOwnProperty(name_1)) {
- hash[name_1] = r.root.variable(name_1);
- }
- }
- }
- return hash;
- }, {});
- }
- return this._variables;
- };
- Ruleset.prototype.properties = function () {
- if (!this._properties) {
- this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
- if (r instanceof Declaration && r.variable !== true) {
- var name_2 = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
- r.name[0].value : r.name;
-
- if (!hash["$" + name_2]) {
- hash["$" + name_2] = [r];
- }
- else {
- hash["$" + name_2].push(r);
- }
- }
- return hash;
- }, {});
- }
- return this._properties;
- };
- Ruleset.prototype.variable = function (name) {
- var decl = this.variables()[name];
- if (decl) {
- return this.parseValue(decl);
- }
- };
- Ruleset.prototype.property = function (name) {
- var decl = this.properties()[name];
- if (decl) {
- return this.parseValue(decl);
- }
- };
- Ruleset.prototype.lastDeclaration = function () {
- for (var i = this.rules.length; i > 0; i--) {
- var decl = this.rules[i - 1];
- if (decl instanceof Declaration) {
- return this.parseValue(decl);
- }
- }
- };
- Ruleset.prototype.parseValue = function (toParse) {
- var self = this;
- function transformDeclaration(decl) {
- if (decl.value instanceof Anonymous && !decl.parsed) {
- if (typeof decl.value.value === 'string') {
- this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
- if (err) {
- decl.parsed = true;
- }
- if (result) {
- decl.value = result[0];
- decl.important = result[1] || '';
- decl.parsed = true;
- }
- });
- }
- else {
- decl.parsed = true;
- }
- return decl;
- }
- else {
- return decl;
- }
- }
- if (!Array.isArray(toParse)) {
- return transformDeclaration.call(self, toParse);
- }
- else {
- var nodes_1 = [];
- toParse.forEach(function (n) {
- nodes_1.push(transformDeclaration.call(self, n));
- });
- return nodes_1;
- }
- };
- Ruleset.prototype.rulesets = function () {
- if (!this.rules) {
- return [];
- }
- var filtRules = [];
- var rules = this.rules;
- var i;
- var rule;
- for (i = 0; (rule = rules[i]); i++) {
- if (rule.isRuleset) {
- filtRules.push(rule);
- }
- }
- return filtRules;
- };
- Ruleset.prototype.prependRule = function (rule) {
- var rules = this.rules;
- if (rules) {
- rules.unshift(rule);
- }
- else {
- this.rules = [rule];
- }
- this.setParent(rule, this);
- };
- Ruleset.prototype.find = function (selector, self, filter) {
- if (self === void 0) { self = this; }
- var rules = [];
- var match;
- var foundMixins;
- var key = selector.toCSS();
- if (key in this._lookups) {
- return this._lookups[key];
- }
- this.rulesets().forEach(function (rule) {
- if (rule !== self) {
- for (var j = 0; j < rule.selectors.length; j++) {
- match = selector.match(rule.selectors[j]);
- if (match) {
- if (selector.elements.length > match) {
- if (!filter || filter(rule)) {
- foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
- for (var i = 0; i < foundMixins.length; ++i) {
- foundMixins[i].path.push(rule);
- }
- Array.prototype.push.apply(rules, foundMixins);
- }
- }
- else {
- rules.push({ rule: rule, path: [] });
- }
- break;
- }
- }
- }
- });
- this._lookups[key] = rules;
- return rules;
- };
- Ruleset.prototype.genCSS = function (context, output) {
- var i;
- var j;
- var charsetRuleNodes = [];
- var ruleNodes = [];
- var
- debugInfo$1;
- var rule;
- var path;
- context.tabLevel = (context.tabLevel || 0);
- if (!this.root) {
- context.tabLevel++;
- }
- var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
- var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
- var sep;
- var charsetNodeIndex = 0;
- var importNodeIndex = 0;
- for (i = 0; (rule = this.rules[i]); i++) {
- if (rule instanceof Comment) {
- if (importNodeIndex === i) {
- importNodeIndex++;
- }
- ruleNodes.push(rule);
- }
- else if (rule.isCharset && rule.isCharset()) {
- ruleNodes.splice(charsetNodeIndex, 0, rule);
- charsetNodeIndex++;
- importNodeIndex++;
- }
- else if (rule.type === 'Import') {
- ruleNodes.splice(importNodeIndex, 0, rule);
- importNodeIndex++;
- }
- else {
- ruleNodes.push(rule);
- }
- }
- ruleNodes = charsetRuleNodes.concat(ruleNodes);
-
-
- if (!this.root) {
- debugInfo$1 = debugInfo(context, this, tabSetStr);
- if (debugInfo$1) {
- output.add(debugInfo$1);
- output.add(tabSetStr);
- }
- var paths = this.paths;
- var pathCnt = paths.length;
- var pathSubCnt = void 0;
- sep = context.compress ? ',' : (",\n" + tabSetStr);
- for (i = 0; i < pathCnt; i++) {
- path = paths[i];
- if (!(pathSubCnt = path.length)) {
- continue;
- }
- if (i > 0) {
- output.add(sep);
- }
- context.firstSelector = true;
- path[0].genCSS(context, output);
- context.firstSelector = false;
- for (j = 1; j < pathSubCnt; j++) {
- path[j].genCSS(context, output);
- }
- }
- output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
- }
-
- for (i = 0; (rule = ruleNodes[i]); i++) {
- if (i + 1 === ruleNodes.length) {
- context.lastRule = true;
- }
- var currentLastRule = context.lastRule;
- if (rule.isRulesetLike(rule)) {
- context.lastRule = false;
- }
- if (rule.genCSS) {
- rule.genCSS(context, output);
- }
- else if (rule.value) {
- output.add(rule.value.toString());
- }
- context.lastRule = currentLastRule;
- if (!context.lastRule && rule.isVisible()) {
- output.add(context.compress ? '' : ("\n" + tabRuleStr));
- }
- else {
- context.lastRule = false;
- }
- }
- if (!this.root) {
- output.add((context.compress ? '}' : "\n" + tabSetStr + "}"));
- context.tabLevel--;
- }
- if (!output.isEmpty() && !context.compress && this.firstRoot) {
- output.add('\n');
- }
- };
- Ruleset.prototype.joinSelectors = function (paths, context, selectors) {
- for (var s = 0; s < selectors.length; s++) {
- this.joinSelector(paths, context, selectors[s]);
- }
- };
- Ruleset.prototype.joinSelector = function (paths, context, selector) {
- function createParenthesis(elementsToPak, originalElement) {
- var replacementParen;
- var j;
- if (elementsToPak.length === 0) {
- replacementParen = new Paren(elementsToPak[0]);
- }
- else {
- var insideParent = new Array(elementsToPak.length);
- for (j = 0; j < elementsToPak.length; j++) {
- insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
- }
- replacementParen = new Paren(new Selector(insideParent));
- }
- return replacementParen;
- }
- function createSelector(containedElement, originalElement) {
- var element;
- var selector;
- element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
- selector = new Selector([element]);
- return selector;
- }
-
-
-
- function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
- var newSelectorPath;
- var lastSelector;
- var newJoinedSelector;
-
- newSelectorPath = [];
-
-
- if (beginningPath.length > 0) {
- newSelectorPath = copyArray(beginningPath);
- lastSelector = newSelectorPath.pop();
- newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
- }
- else {
- newJoinedSelector = originalSelector.createDerived([]);
- }
- if (addPath.length > 0) {
-
-
-
-
-
- var combinator = replacedElement.combinator;
- var parentEl = addPath[0].elements[0];
- if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
- combinator = parentEl.combinator;
- }
-
- newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
- newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
- }
-
- if (newJoinedSelector.elements.length !== 0) {
- newSelectorPath.push(newJoinedSelector);
- }
-
- if (addPath.length > 1) {
- var restOfPath = addPath.slice(1);
- restOfPath = restOfPath.map(function (selector) { return selector.createDerived(selector.elements, []); });
- newSelectorPath = newSelectorPath.concat(restOfPath);
- }
- return newSelectorPath;
- }
-
-
-
- function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
- var j;
- for (j = 0; j < beginningPath.length; j++) {
- var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
- result.push(newSelectorPath);
- }
- return result;
- }
- function mergeElementsOnToSelectors(elements, selectors) {
- var i;
- var sel;
- if (elements.length === 0) {
- return;
- }
- if (selectors.length === 0) {
- selectors.push([new Selector(elements)]);
- return;
- }
- for (i = 0; (sel = selectors[i]); i++) {
-
- if (sel.length > 0) {
- sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
- }
- else {
- sel.push(new Selector(elements));
- }
- }
- }
-
-
-
- function replaceParentSelector(paths, context, inSelector) {
-
-
-
-
-
-
-
-
-
-
- var i;
- var j;
- var k;
- var currentElements;
- var newSelectors;
- var selectorsMultiplied;
- var sel;
- var el;
- var hadParentSelector = false;
- var length;
- var lastSelector;
- function findNestedSelector(element) {
- var maybeSelector;
- if (!(element.value instanceof Paren)) {
- return null;
- }
- maybeSelector = element.value.value;
- if (!(maybeSelector instanceof Selector)) {
- return null;
- }
- return maybeSelector;
- }
-
- currentElements = [];
-
-
-
- newSelectors = [
- []
- ];
- for (i = 0; (el = inSelector.elements[i]); i++) {
-
- if (el.value !== '&') {
- var nestedSelector = findNestedSelector(el);
- if (nestedSelector != null) {
-
-
- mergeElementsOnToSelectors(currentElements, newSelectors);
- var nestedPaths = [];
- var replaced = void 0;
- var replacedNewSelectors = [];
- replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
- hadParentSelector = hadParentSelector || replaced;
-
- for (k = 0; k < nestedPaths.length; k++) {
- var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
- addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
- }
- newSelectors = replacedNewSelectors;
- currentElements = [];
- }
- else {
- currentElements.push(el);
- }
- }
- else {
- hadParentSelector = true;
-
- selectorsMultiplied = [];
-
-
- mergeElementsOnToSelectors(currentElements, newSelectors);
-
- for (j = 0; j < newSelectors.length; j++) {
- sel = newSelectors[j];
-
-
- if (context.length === 0) {
-
-
- if (sel.length > 0) {
- sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
- }
- selectorsMultiplied.push(sel);
- }
- else {
-
- for (k = 0; k < context.length; k++) {
-
-
- var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
-
- selectorsMultiplied.push(newSelectorPath);
- }
- }
- }
-
- newSelectors = selectorsMultiplied;
- currentElements = [];
- }
- }
-
-
- mergeElementsOnToSelectors(currentElements, newSelectors);
- for (i = 0; i < newSelectors.length; i++) {
- length = newSelectors[i].length;
- if (length > 0) {
- paths.push(newSelectors[i]);
- lastSelector = newSelectors[i][length - 1];
- newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
- }
- }
- return hadParentSelector;
- }
- function deriveSelector(visibilityInfo, deriveFrom) {
- var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
- newSelector.copyVisibilityInfo(visibilityInfo);
- return newSelector;
- }
-
- var i;
- var newPaths;
- var hadParentSelector;
- newPaths = [];
- hadParentSelector = replaceParentSelector(newPaths, context, selector);
- if (!hadParentSelector) {
- if (context.length > 0) {
- newPaths = [];
- for (i = 0; i < context.length; i++) {
- var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
- concatenated.push(selector);
- newPaths.push(concatenated);
- }
- }
- else {
- newPaths = [[selector]];
- }
- }
- for (i = 0; i < newPaths.length; i++) {
- paths.push(newPaths[i]);
- }
- };
- Ruleset.prototype.type = 'Ruleset';
- Ruleset.prototype.isRuleset = true;
- var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
- var i;
- this.name = name;
- this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
- if (rules) {
- if (Array.isArray(rules)) {
- this.rules = rules;
- }
- else {
- this.rules = [rules];
- this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
- }
- for (i = 0; i < this.rules.length; i++) {
- this.rules[i].allowImports = true;
- }
- this.setParent(this.rules, this);
- }
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.debugInfo = debugInfo;
- this.isRooted = isRooted || false;
- this.copyVisibilityInfo(visibilityInfo);
- this.allowRoot = true;
- };
- AtRule.prototype = new Node();
- AtRule.prototype.accept = function (visitor) {
- var value = this.value;
- var rules = this.rules;
- if (rules) {
- this.rules = visitor.visitArray(rules);
- }
- if (value) {
- this.value = visitor.visit(value);
- }
- };
- AtRule.prototype.isRulesetLike = function () {
- return this.rules || !this.isCharset();
- };
- AtRule.prototype.isCharset = function () {
- return '@charset' === this.name;
- };
- AtRule.prototype.genCSS = function (context, output) {
- var value = this.value;
- var rules = this.rules;
- output.add(this.name, this.fileInfo(), this.getIndex());
- if (value) {
- output.add(' ');
- value.genCSS(context, output);
- }
- if (rules) {
- this.outputRuleset(context, output, rules);
- }
- else {
- output.add(';');
- }
- };
- AtRule.prototype.eval = function (context) {
- var mediaPathBackup;
- var mediaBlocksBackup;
- var value = this.value;
- var rules = this.rules;
-
-
- mediaPathBackup = context.mediaPath;
- mediaBlocksBackup = context.mediaBlocks;
-
- context.mediaPath = [];
- context.mediaBlocks = [];
- if (value) {
- value = value.eval(context);
- }
- if (rules) {
-
- rules = [rules[0].eval(context)];
- rules[0].root = true;
- }
-
- context.mediaPath = mediaPathBackup;
- context.mediaBlocks = mediaBlocksBackup;
- return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
- };
- AtRule.prototype.variable = function (name) {
- if (this.rules) {
-
- return Ruleset.prototype.variable.call(this.rules[0], name);
- }
- };
- AtRule.prototype.find = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- if (this.rules) {
-
- return Ruleset.prototype.find.apply(this.rules[0], args);
- }
- };
- AtRule.prototype.rulesets = function () {
- if (this.rules) {
-
- return Ruleset.prototype.rulesets.apply(this.rules[0]);
- }
- };
- AtRule.prototype.outputRuleset = function (context, output, rules) {
- var ruleCnt = rules.length;
- var i;
- context.tabLevel = (context.tabLevel | 0) + 1;
-
- if (context.compress) {
- output.add('{');
- for (i = 0; i < ruleCnt; i++) {
- rules[i].genCSS(context, output);
- }
- output.add('}');
- context.tabLevel--;
- return;
- }
-
- var tabSetStr = "\n" + Array(context.tabLevel).join(' ');
- var tabRuleStr = tabSetStr + " ";
- if (!ruleCnt) {
- output.add(" {" + tabSetStr + "}");
- }
- else {
- output.add(" {" + tabRuleStr);
- rules[0].genCSS(context, output);
- for (i = 1; i < ruleCnt; i++) {
- output.add(tabRuleStr);
- rules[i].genCSS(context, output);
- }
- output.add(tabSetStr + "}");
- }
- context.tabLevel--;
- };
- AtRule.prototype.type = 'AtRule';
- var DetachedRuleset = function (ruleset, frames) {
- this.ruleset = ruleset;
- this.frames = frames;
- this.setParent(this.ruleset, this);
- };
- DetachedRuleset.prototype = new Node();
- DetachedRuleset.prototype.accept = function (visitor) {
- this.ruleset = visitor.visit(this.ruleset);
- };
- DetachedRuleset.prototype.eval = function (context) {
- var frames = this.frames || copyArray(context.frames);
- return new DetachedRuleset(this.ruleset, frames);
- };
- DetachedRuleset.prototype.callEval = function (context) {
- return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
- };
- DetachedRuleset.prototype.type = 'DetachedRuleset';
- DetachedRuleset.prototype.evalFirst = true;
- var Unit = function (numerator, denominator, backupUnit) {
- this.numerator = numerator ? copyArray(numerator).sort() : [];
- this.denominator = denominator ? copyArray(denominator).sort() : [];
- if (backupUnit) {
- this.backupUnit = backupUnit;
- }
- else if (numerator && numerator.length) {
- this.backupUnit = numerator[0];
- }
- };
- Unit.prototype = new Node();
- Unit.prototype.clone = function () {
- return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
- };
- Unit.prototype.genCSS = function (context, output) {
-
- var strictUnits = context && context.strictUnits;
- if (this.numerator.length === 1) {
- output.add(this.numerator[0]);
- }
- else if (!strictUnits && this.backupUnit) {
- output.add(this.backupUnit);
- }
- else if (!strictUnits && this.denominator.length) {
- output.add(this.denominator[0]);
- }
- };
- Unit.prototype.toString = function () {
- var i;
- var returnStr = this.numerator.join('*');
- for (i = 0; i < this.denominator.length; i++) {
- returnStr += "/" + this.denominator[i];
- }
- return returnStr;
- };
- Unit.prototype.compare = function (other) {
- return this.is(other.toString()) ? 0 : undefined;
- };
- Unit.prototype.is = function (unitString) {
- return this.toString().toUpperCase() === unitString.toUpperCase();
- };
- Unit.prototype.isLength = function () {
- return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
- };
- Unit.prototype.isEmpty = function () {
- return this.numerator.length === 0 && this.denominator.length === 0;
- };
- Unit.prototype.isSingular = function () {
- return this.numerator.length <= 1 && this.denominator.length === 0;
- };
- Unit.prototype.map = function (callback) {
- var i;
- for (i = 0; i < this.numerator.length; i++) {
- this.numerator[i] = callback(this.numerator[i], false);
- }
- for (i = 0; i < this.denominator.length; i++) {
- this.denominator[i] = callback(this.denominator[i], true);
- }
- };
- Unit.prototype.usedUnits = function () {
- var group;
- var result = {};
- var mapUnit;
- var groupName;
- mapUnit = function (atomicUnit) {
-
- if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
- result[groupName] = atomicUnit;
- }
- return atomicUnit;
- };
- for (groupName in unitConversions) {
- if (unitConversions.hasOwnProperty(groupName)) {
- group = unitConversions[groupName];
- this.map(mapUnit);
- }
- }
- return result;
- };
- Unit.prototype.cancel = function () {
- var counter = {};
- var atomicUnit;
- var i;
- for (i = 0; i < this.numerator.length; i++) {
- atomicUnit = this.numerator[i];
- counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
- }
- for (i = 0; i < this.denominator.length; i++) {
- atomicUnit = this.denominator[i];
- counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
- }
- this.numerator = [];
- this.denominator = [];
- for (atomicUnit in counter) {
- if (counter.hasOwnProperty(atomicUnit)) {
- var count = counter[atomicUnit];
- if (count > 0) {
- for (i = 0; i < count; i++) {
- this.numerator.push(atomicUnit);
- }
- }
- else if (count < 0) {
- for (i = 0; i < -count; i++) {
- this.denominator.push(atomicUnit);
- }
- }
- }
- }
- this.numerator.sort();
- this.denominator.sort();
- };
- Unit.prototype.type = 'Unit';
-
-
-
- var Dimension = function (value, unit) {
- this.value = parseFloat(value);
- if (isNaN(this.value)) {
- throw new Error('Dimension is not a number.');
- }
- this.unit = (unit && unit instanceof Unit) ? unit :
- new Unit(unit ? [unit] : undefined);
- this.setParent(this.unit, this);
- };
- Dimension.prototype = new Node();
- Dimension.prototype.accept = function (visitor) {
- this.unit = visitor.visit(this.unit);
- };
- Dimension.prototype.eval = function (context) {
- return this;
- };
- Dimension.prototype.toColor = function () {
- return new Color([this.value, this.value, this.value]);
- };
- Dimension.prototype.genCSS = function (context, output) {
- if ((context && context.strictUnits) && !this.unit.isSingular()) {
- throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
- }
- var value = this.fround(context, this.value);
- var strValue = String(value);
- if (value !== 0 && value < 0.000001 && value > -0.000001) {
-
- strValue = value.toFixed(20).replace(/0+$/, '');
- }
- if (context && context.compress) {
-
- if (value === 0 && this.unit.isLength()) {
- output.add(strValue);
- return;
- }
-
- if (value > 0 && value < 1) {
- strValue = (strValue).substr(1);
- }
- }
- output.add(strValue);
- this.unit.genCSS(context, output);
- };
-
-
-
- Dimension.prototype.operate = function (context, op, other) {
-
- var value = this._operate(context, op, this.value, other.value);
- var unit = this.unit.clone();
- if (op === '+' || op === '-') {
- if (unit.numerator.length === 0 && unit.denominator.length === 0) {
- unit = other.unit.clone();
- if (this.unit.backupUnit) {
- unit.backupUnit = this.unit.backupUnit;
- }
- }
- else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ;
- else {
- other = other.convertTo(this.unit.usedUnits());
- if (context.strictUnits && other.unit.toString() !== unit.toString()) {
- throw new Error("Incompatible units. Change the units or use the unit function. " +
- ("Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."));
- }
- value = this._operate(context, op, this.value, other.value);
- }
- }
- else if (op === '*') {
- unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
- unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
- unit.cancel();
- }
- else if (op === '/') {
- unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
- unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
- unit.cancel();
- }
- return new Dimension(value, unit);
- };
- Dimension.prototype.compare = function (other) {
- var a;
- var b;
- if (!(other instanceof Dimension)) {
- return undefined;
- }
- if (this.unit.isEmpty() || other.unit.isEmpty()) {
- a = this;
- b = other;
- }
- else {
- a = this.unify();
- b = other.unify();
- if (a.unit.compare(b.unit) !== 0) {
- return undefined;
- }
- }
- return Node.numericCompare(a.value, b.value);
- };
- Dimension.prototype.unify = function () {
- return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
- };
- Dimension.prototype.convertTo = function (conversions) {
- var value = this.value;
- var unit = this.unit.clone();
- var i;
- var groupName;
- var group;
- var targetUnit;
- var derivedConversions = {};
- var applyUnit;
- if (typeof conversions === 'string') {
- for (i in unitConversions) {
- if (unitConversions[i].hasOwnProperty(conversions)) {
- derivedConversions = {};
- derivedConversions[i] = conversions;
- }
- }
- conversions = derivedConversions;
- }
- applyUnit = function (atomicUnit, denominator) {
-
- if (group.hasOwnProperty(atomicUnit)) {
- if (denominator) {
- value = value / (group[atomicUnit] / group[targetUnit]);
- }
- else {
- value = value * (group[atomicUnit] / group[targetUnit]);
- }
- return targetUnit;
- }
- return atomicUnit;
- };
- for (groupName in conversions) {
- if (conversions.hasOwnProperty(groupName)) {
- targetUnit = conversions[groupName];
- group = unitConversions[groupName];
- unit.map(applyUnit);
- }
- }
- unit.cancel();
- return new Dimension(value, unit);
- };
- Dimension.prototype.type = 'Dimension';
- var MATH$1 = Math$1;
- var Operation = function (op, operands, isSpaced) {
- this.op = op.trim();
- this.operands = operands;
- this.isSpaced = isSpaced;
- };
- Operation.prototype = new Node();
- Operation.prototype.accept = function (visitor) {
- this.operands = visitor.visitArray(this.operands);
- };
- Operation.prototype.eval = function (context) {
- var a = this.operands[0].eval(context);
- var b = this.operands[1].eval(context);
- var op;
- if (context.isMathOn(this.op)) {
- op = this.op === './' ? '/' : this.op;
- if (a instanceof Dimension && b instanceof Color) {
- a = a.toColor();
- }
- if (b instanceof Dimension && a instanceof Color) {
- b = b.toColor();
- }
- if (!a.operate) {
- if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
- return new Operation(this.op, [a, b], this.isSpaced);
- }
- throw { type: 'Operation',
- message: 'Operation on an invalid type' };
- }
- return a.operate(context, op, b);
- }
- else {
- return new Operation(this.op, [a, b], this.isSpaced);
- }
- };
- Operation.prototype.genCSS = function (context, output) {
- this.operands[0].genCSS(context, output);
- if (this.isSpaced) {
- output.add(' ');
- }
- output.add(this.op);
- if (this.isSpaced) {
- output.add(' ');
- }
- this.operands[1].genCSS(context, output);
- };
- Operation.prototype.type = 'Operation';
- var MATH$2 = Math$1;
- var Expression = function (value, noSpacing) {
- this.value = value;
- this.noSpacing = noSpacing;
- if (!value) {
- throw new Error('Expression requires an array parameter');
- }
- };
- Expression.prototype = new Node();
- Expression.prototype.accept = function (visitor) {
- this.value = visitor.visitArray(this.value);
- };
- Expression.prototype.eval = function (context) {
- var returnValue;
- var mathOn = context.isMathOn();
- var inParenthesis = this.parens &&
- (context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
- var doubleParen = false;
- if (inParenthesis) {
- context.inParenthesis();
- }
- if (this.value.length > 1) {
- returnValue = new Expression(this.value.map(function (e) {
- if (!e.eval) {
- return e;
- }
- return e.eval(context);
- }), this.noSpacing);
- }
- else if (this.value.length === 1) {
- if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
- doubleParen = true;
- }
- returnValue = this.value[0].eval(context);
- }
- else {
- returnValue = this;
- }
- if (inParenthesis) {
- context.outOfParenthesis();
- }
- if (this.parens && this.parensInOp && !mathOn && !doubleParen
- && (!(returnValue instanceof Dimension))) {
- returnValue = new Paren(returnValue);
- }
- return returnValue;
- };
- Expression.prototype.genCSS = function (context, output) {
- for (var i = 0; i < this.value.length; i++) {
- this.value[i].genCSS(context, output);
- if (!this.noSpacing && i + 1 < this.value.length) {
- output.add(' ');
- }
- }
- };
- Expression.prototype.throwAwayComments = function () {
- this.value = this.value.filter(function (v) { return !(v instanceof Comment); });
- };
- Expression.prototype.type = 'Expression';
- var functionCaller = (function () {
- function functionCaller(name, context, index, currentFileInfo) {
- this.name = name.toLowerCase();
- this.index = index;
- this.context = context;
- this.currentFileInfo = currentFileInfo;
- this.func = context.frames[0].functionRegistry.get(this.name);
- }
- functionCaller.prototype.isValid = function () {
- return Boolean(this.func);
- };
- functionCaller.prototype.call = function (args) {
- var _this = this;
- var evalArgs = this.func.evalArgs;
- if (evalArgs !== false) {
- args = args.map(function (a) { return a.eval(_this.context); });
- }
-
-
- if (Array.isArray(args)) {
- args = args.filter(function (item) {
- if (item.type === 'Comment') {
- return false;
- }
- return true;
- })
- .map(function (item) {
- if (item.type === 'Expression') {
- var subNodes = item.value.filter(function (item) {
- if (item.type === 'Comment') {
- return false;
- }
- return true;
- });
- if (subNodes.length === 1) {
- return subNodes[0];
- }
- else {
- return new Expression(subNodes);
- }
- }
- return item;
- });
- }
- if (evalArgs === false) {
- return this.func.apply(this, __spreadArrays([this.context], args));
- }
- return this.func.apply(this, args);
- };
- return functionCaller;
- }());
-
-
-
- var Call = function (name, args, index, currentFileInfo) {
- this.name = name;
- this.args = args;
- this.calc = name === 'calc';
- this._index = index;
- this._fileInfo = currentFileInfo;
- };
- Call.prototype = new Node();
- Call.prototype.accept = function (visitor) {
- if (this.args) {
- this.args = visitor.visitArray(this.args);
- }
- };
-
-
-
-
-
-
-
-
-
-
-
- Call.prototype.eval = function (context) {
- var _this = this;
-
- var currentMathContext = context.mathOn;
- context.mathOn = !this.calc;
- if (this.calc || context.inCalc) {
- context.enterCalc();
- }
- var exitCalc = function () {
- if (_this.calc || context.inCalc) {
- context.exitCalc();
- }
- context.mathOn = currentMathContext;
- };
- var result;
- var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
- if (funcCaller.isValid()) {
- try {
- result = funcCaller.call(this.args);
- exitCalc();
- }
- catch (e) {
- if (e.hasOwnProperty('line') && e.hasOwnProperty('column')) {
- throw e;
- }
- throw {
- type: e.type || 'Runtime',
- message: "error evaluating function `" + this.name + "`" + (e.message ? ": " + e.message : ''),
- index: this.getIndex(),
- filename: this.fileInfo().filename,
- line: e.lineNumber,
- column: e.columnNumber
- };
- }
- if (result !== null && result !== undefined) {
-
-
- if (!(result instanceof Node)) {
- if (!result || result === true) {
- result = new Anonymous(null);
- }
- else {
- result = new Anonymous(result.toString());
- }
- }
- result._index = this._index;
- result._fileInfo = this._fileInfo;
- return result;
- }
- }
- var args = this.args.map(function (a) { return a.eval(context); });
- exitCalc();
- return new Call(this.name, args, this.getIndex(), this.fileInfo());
- };
- Call.prototype.genCSS = function (context, output) {
- output.add(this.name + "(", this.fileInfo(), this.getIndex());
- for (var i = 0; i < this.args.length; i++) {
- this.args[i].genCSS(context, output);
- if (i + 1 < this.args.length) {
- output.add(', ');
- }
- }
- output.add(')');
- };
- Call.prototype.type = 'Call';
- var Variable = function (name, index, currentFileInfo) {
- this.name = name;
- this._index = index;
- this._fileInfo = currentFileInfo;
- };
- Variable.prototype = new Node();
- Variable.prototype.eval = function (context) {
- var variable;
- var name = this.name;
- if (name.indexOf('@@') === 0) {
- name = "@" + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
- }
- if (this.evaluating) {
- throw { type: 'Name', message: "Recursive variable definition for " + name, filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- this.evaluating = true;
- variable = this.find(context.frames, function (frame) {
- var v = frame.variable(name);
- if (v) {
- if (v.important) {
- var importantScope = context.importantScope[context.importantScope.length - 1];
- importantScope.important = v.important;
- }
-
- if (context.inCalc) {
- return (new Call('_SELF', [v.value])).eval(context);
- }
- else {
- return v.value.eval(context);
- }
- }
- });
- if (variable) {
- this.evaluating = false;
- return variable;
- }
- else {
- throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- };
- Variable.prototype.find = function (obj, fun) {
- for (var i = 0, r = void 0; i < obj.length; i++) {
- r = fun.call(obj, obj[i]);
- if (r) {
- return r;
- }
- }
- return null;
- };
- Variable.prototype.type = 'Variable';
- var Property = function (name, index, currentFileInfo) {
- this.name = name;
- this._index = index;
- this._fileInfo = currentFileInfo;
- };
- Property.prototype = new Node();
- Property.prototype.eval = function (context) {
- var property;
- var name = this.name;
-
- var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
- if (this.evaluating) {
- throw { type: 'Name', message: "Recursive property reference for " + name, filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- this.evaluating = true;
- property = this.find(context.frames, function (frame) {
- var v;
- var vArr = frame.property(name);
- if (vArr) {
- for (var i = 0; i < vArr.length; i++) {
- v = vArr[i];
- vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
- }
- mergeRules(vArr);
- v = vArr[vArr.length - 1];
- if (v.important) {
- var importantScope = context.importantScope[context.importantScope.length - 1];
- importantScope.important = v.important;
- }
- v = v.value.eval(context);
- return v;
- }
- });
- if (property) {
- this.evaluating = false;
- return property;
- }
- else {
- throw { type: 'Name', message: "Property '" + name + "' is undefined", filename: this.currentFileInfo.filename,
- index: this.index };
- }
- };
- Property.prototype.find = function (obj, fun) {
- for (var i = 0, r = void 0; i < obj.length; i++) {
- r = fun.call(obj, obj[i]);
- if (r) {
- return r;
- }
- }
- return null;
- };
- Property.prototype.type = 'Property';
- var Attribute = function (key, op, value) {
- this.key = key;
- this.op = op;
- this.value = value;
- };
- Attribute.prototype = new Node();
- Attribute.prototype.eval = function (context) {
- return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value);
- };
- Attribute.prototype.genCSS = function (context, output) {
- output.add(this.toCSS(context));
- };
- Attribute.prototype.toCSS = function (context) {
- var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
- if (this.op) {
- value += this.op;
- value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
- }
- return "[" + value + "]";
- };
- Attribute.prototype.type = 'Attribute';
- var Quoted = function (str, content, escaped, index, currentFileInfo) {
- this.escaped = (escaped == null) ? true : escaped;
- this.value = content || '';
- this.quote = str.charAt(0);
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.variableRegex = /@\{([\w-]+)\}/g;
- this.propRegex = /\$\{([\w-]+)\}/g;
- this.allowRoot = escaped;
- };
- Quoted.prototype = new Node();
- Quoted.prototype.genCSS = function (context, output) {
- if (!this.escaped) {
- output.add(this.quote, this.fileInfo(), this.getIndex());
- }
- output.add(this.value);
- if (!this.escaped) {
- output.add(this.quote);
- }
- };
- Quoted.prototype.containsVariables = function () {
- return this.value.match(this.variableRegex);
- };
- Quoted.prototype.eval = function (context) {
- var that = this;
- var value = this.value;
- var variableReplacement = function (_, name) {
- var v = new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context, true);
- return (v instanceof Quoted) ? v.value : v.toCSS();
- };
- var propertyReplacement = function (_, name) {
- var v = new Property("$" + name, that.getIndex(), that.fileInfo()).eval(context, true);
- return (v instanceof Quoted) ? v.value : v.toCSS();
- };
- function iterativeReplace(value, regexp, replacementFnc) {
- var evaluatedValue = value;
- do {
- value = evaluatedValue.toString();
- evaluatedValue = value.replace(regexp, replacementFnc);
- } while (value !== evaluatedValue);
- return evaluatedValue;
- }
- value = iterativeReplace(value, this.variableRegex, variableReplacement);
- value = iterativeReplace(value, this.propRegex, propertyReplacement);
- return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
- };
- Quoted.prototype.compare = function (other) {
-
- if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
- return Node.numericCompare(this.value, other.value);
- }
- else {
- return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
- }
- };
- Quoted.prototype.type = 'Quoted';
- var URL = function (val, index, currentFileInfo, isEvald) {
- this.value = val;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.isEvald = isEvald;
- };
- URL.prototype = new Node();
- URL.prototype.accept = function (visitor) {
- this.value = visitor.visit(this.value);
- };
- URL.prototype.genCSS = function (context, output) {
- output.add('url(');
- this.value.genCSS(context, output);
- output.add(')');
- };
- URL.prototype.eval = function (context) {
- var val = this.value.eval(context);
- var rootpath;
- if (!this.isEvald) {
-
- rootpath = this.fileInfo() && this.fileInfo().rootpath;
- if (typeof rootpath === 'string' &&
- typeof val.value === 'string' &&
- context.pathRequiresRewrite(val.value)) {
- if (!val.quote) {
- rootpath = escapePath(rootpath);
- }
- val.value = context.rewritePath(val.value, rootpath);
- }
- else {
- val.value = context.normalizePath(val.value);
- }
-
- if (context.urlArgs) {
- if (!val.value.match(/^\s*data:/)) {
- var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
- var urlArgs = delimiter + context.urlArgs;
- if (val.value.indexOf('#') !== -1) {
- val.value = val.value.replace('#', urlArgs + "#");
- }
- else {
- val.value += urlArgs;
- }
- }
- }
- }
- return new URL(val, this.getIndex(), this.fileInfo(), true);
- };
- URL.prototype.type = 'Url';
- function escapePath(path) {
- return path.replace(/[\(\)'"\s]/g, function (match) { return "\\" + match; });
- }
- var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
- this._index = index;
- this._fileInfo = currentFileInfo;
- var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
- this.features = new Value(features);
- this.rules = [new Ruleset(selectors, value)];
- this.rules[0].allowImports = true;
- this.copyVisibilityInfo(visibilityInfo);
- this.allowRoot = true;
- this.setParent(selectors, this);
- this.setParent(this.features, this);
- this.setParent(this.rules, this);
- };
- Media.prototype = new AtRule();
- Media.prototype.isRulesetLike = function () {
- return true;
- };
- Media.prototype.accept = function (visitor) {
- if (this.features) {
- this.features = visitor.visit(this.features);
- }
- if (this.rules) {
- this.rules = visitor.visitArray(this.rules);
- }
- };
- Media.prototype.genCSS = function (context, output) {
- output.add('@media ', this._fileInfo, this._index);
- this.features.genCSS(context, output);
- this.outputRuleset(context, output, this.rules);
- };
- Media.prototype.eval = function (context) {
- if (!context.mediaBlocks) {
- context.mediaBlocks = [];
- context.mediaPath = [];
- }
- var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
- if (this.debugInfo) {
- this.rules[0].debugInfo = this.debugInfo;
- media.debugInfo = this.debugInfo;
- }
- media.features = this.features.eval(context);
- context.mediaPath.push(media);
- context.mediaBlocks.push(media);
- this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
- context.frames.unshift(this.rules[0]);
- media.rules = [this.rules[0].eval(context)];
- context.frames.shift();
- context.mediaPath.pop();
- return context.mediaPath.length === 0 ? media.evalTop(context) :
- media.evalNested(context);
- };
- Media.prototype.evalTop = function (context) {
- var result = this;
-
- if (context.mediaBlocks.length > 1) {
- var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
- result = new Ruleset(selectors, context.mediaBlocks);
- result.multiMedia = true;
- result.copyVisibilityInfo(this.visibilityInfo());
- this.setParent(result, this);
- }
- delete context.mediaBlocks;
- delete context.mediaPath;
- return result;
- };
- Media.prototype.evalNested = function (context) {
- var i;
- var value;
- var path = context.mediaPath.concat([this]);
-
- for (i = 0; i < path.length; i++) {
- value = path[i].features instanceof Value ?
- path[i].features.value : path[i].features;
- path[i] = Array.isArray(value) ? value : [value];
- }
-
-
-
-
-
-
-
- this.features = new Value(this.permute(path).map(function (path) {
- path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); });
- for (i = path.length - 1; i > 0; i--) {
- path.splice(i, 0, new Anonymous('and'));
- }
- return new Expression(path);
- }));
- this.setParent(this.features, this);
-
- return new Ruleset([], []);
- };
- Media.prototype.permute = function (arr) {
- if (arr.length === 0) {
- return [];
- }
- else if (arr.length === 1) {
- return arr[0];
- }
- else {
- var result = [];
- var rest = this.permute(arr.slice(1));
- for (var i = 0; i < rest.length; i++) {
- for (var j = 0; j < arr[0].length; j++) {
- result.push([arr[0][j]].concat(rest[i]));
- }
- }
- return result;
- }
- };
- Media.prototype.bubbleSelectors = function (selectors) {
- if (!selectors) {
- return;
- }
- this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
- this.setParent(this.rules, this);
- };
- Media.prototype.type = 'Media';
-
-
-
-
-
-
-
-
-
-
-
-
- var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
- this.options = options;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.path = path;
- this.features = features;
- this.allowRoot = true;
- if (this.options.less !== undefined || this.options.inline) {
- this.css = !this.options.less || this.options.inline;
- }
- else {
- var pathValue = this.getPath();
- if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
- this.css = true;
- }
- }
- this.copyVisibilityInfo(visibilityInfo);
- this.setParent(this.features, this);
- this.setParent(this.path, this);
- };
- Import.prototype = new Node();
- Import.prototype.accept = function (visitor) {
- if (this.features) {
- this.features = visitor.visit(this.features);
- }
- this.path = visitor.visit(this.path);
- if (!this.options.isPlugin && !this.options.inline && this.root) {
- this.root = visitor.visit(this.root);
- }
- };
- Import.prototype.genCSS = function (context, output) {
- if (this.css && this.path._fileInfo.reference === undefined) {
- output.add('@import ', this._fileInfo, this._index);
- this.path.genCSS(context, output);
- if (this.features) {
- output.add(' ');
- this.features.genCSS(context, output);
- }
- output.add(';');
- }
- };
- Import.prototype.getPath = function () {
- return (this.path instanceof URL) ?
- this.path.value.value : this.path.value;
- };
- Import.prototype.isVariableImport = function () {
- var path = this.path;
- if (path instanceof URL) {
- path = path.value;
- }
- if (path instanceof Quoted) {
- return path.containsVariables();
- }
- return true;
- };
- Import.prototype.evalForImport = function (context) {
- var path = this.path;
- if (path instanceof URL) {
- path = path.value;
- }
- return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
- };
- Import.prototype.evalPath = function (context) {
- var path = this.path.eval(context);
- var fileInfo = this._fileInfo;
- if (!(path instanceof URL)) {
-
- var pathValue = path.value;
- if (fileInfo &&
- pathValue &&
- context.pathRequiresRewrite(pathValue)) {
- path.value = context.rewritePath(pathValue, fileInfo.rootpath);
- }
- else {
- path.value = context.normalizePath(path.value);
- }
- }
- return path;
- };
- Import.prototype.eval = function (context) {
- var result = this.doEval(context);
- if (this.options.reference || this.blocksVisibility()) {
- if (result.length || result.length === 0) {
- result.forEach(function (node) {
- node.addVisibilityBlock();
- });
- }
- else {
- result.addVisibilityBlock();
- }
- }
- return result;
- };
- Import.prototype.doEval = function (context) {
- var ruleset;
- var registry;
- var features = this.features && this.features.eval(context);
- if (this.options.isPlugin) {
- if (this.root && this.root.eval) {
- try {
- this.root.eval(context);
- }
- catch (e) {
- e.message = 'Plugin error during evaluation';
- throw new LessError(e, this.root.imports, this.root.filename);
- }
- }
- registry = context.frames[0] && context.frames[0].functionRegistry;
- if (registry && this.root && this.root.functions) {
- registry.addMultiple(this.root.functions);
- }
- return [];
- }
- if (this.skip) {
- if (typeof this.skip === 'function') {
- this.skip = this.skip();
- }
- if (this.skip) {
- return [];
- }
- }
- if (this.options.inline) {
- var contents = new Anonymous(this.root, 0, {
- filename: this.importedFilename,
- reference: this.path._fileInfo && this.path._fileInfo.reference
- }, true, true);
- return this.features ? new Media([contents], this.features.value) : [contents];
- }
- else if (this.css) {
- var newImport = new Import(this.evalPath(context), features, this.options, this._index);
- if (!newImport.css && this.error) {
- throw this.error;
- }
- return newImport;
- }
- else if (this.root) {
- ruleset = new Ruleset(null, copyArray(this.root.rules));
- ruleset.evalImports(context);
- return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
- }
- else {
- return [];
- }
- };
- Import.prototype.type = 'Import';
- var JsEvalNode = function () { };
- JsEvalNode.prototype = new Node();
- JsEvalNode.prototype.evaluateJavaScript = function (expression, context) {
- var result;
- var that = this;
- var evalContext = {};
- if (!context.javascriptEnabled) {
- throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
- filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return that.jsify(new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context)); });
- try {
- expression = new Function("return (" + expression + ")");
- }
- catch (e) {
- throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`", filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- var variables = context.frames[0].variables();
- for (var k in variables) {
- if (variables.hasOwnProperty(k)) {
-
- evalContext[k.slice(1)] = {
- value: variables[k].value,
- toJS: function () {
- return this.value.eval(context).toCSS();
- }
- };
- }
- }
- try {
- result = expression.call(evalContext);
- }
- catch (e) {
- throw { message: "JavaScript evaluation error: '" + e.name + ": " + e.message.replace(/["]/g, '\'') + "'", filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- return result;
- };
- JsEvalNode.prototype.jsify = function (obj) {
- if (Array.isArray(obj.value) && (obj.value.length > 1)) {
- return "[" + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + "]";
- }
- else {
- return obj.toCSS();
- }
- };
- var JavaScript = function (string, escaped, index, currentFileInfo) {
- this.escaped = escaped;
- this.expression = string;
- this._index = index;
- this._fileInfo = currentFileInfo;
- };
- JavaScript.prototype = new JsEvalNode();
- JavaScript.prototype.eval = function (context) {
- var result = this.evaluateJavaScript(this.expression, context);
- var type = typeof result;
- if (type === 'number' && !isNaN(result)) {
- return new Dimension(result);
- }
- else if (type === 'string') {
- return new Quoted("\"" + result + "\"", result, this.escaped, this._index);
- }
- else if (Array.isArray(result)) {
- return new Anonymous(result.join(', '));
- }
- else {
- return new Anonymous(result);
- }
- };
- JavaScript.prototype.type = 'JavaScript';
- var Assignment = function (key, val) {
- this.key = key;
- this.value = val;
- };
- Assignment.prototype = new Node();
- Assignment.prototype.accept = function (visitor) {
- this.value = visitor.visit(this.value);
- };
- Assignment.prototype.eval = function (context) {
- if (this.value.eval) {
- return new Assignment(this.key, this.value.eval(context));
- }
- return this;
- };
- Assignment.prototype.genCSS = function (context, output) {
- output.add(this.key + "=");
- if (this.value.genCSS) {
- this.value.genCSS(context, output);
- }
- else {
- output.add(this.value);
- }
- };
- Assignment.prototype.type = 'Assignment';
- var Condition = function (op, l, r, i, negate) {
- this.op = op.trim();
- this.lvalue = l;
- this.rvalue = r;
- this._index = i;
- this.negate = negate;
- };
- Condition.prototype = new Node();
- Condition.prototype.accept = function (visitor) {
- this.lvalue = visitor.visit(this.lvalue);
- this.rvalue = visitor.visit(this.rvalue);
- };
- Condition.prototype.eval = function (context) {
- var result = (function (op, a, b) {
- switch (op) {
- case 'and': return a && b;
- case 'or': return a || b;
- default:
- switch (Node.compare(a, b)) {
- case -1:
- return op === '<' || op === '=<' || op === '<=';
- case 0:
- return op === '=' || op === '>=' || op === '=<' || op === '<=';
- case 1:
- return op === '>' || op === '>=';
- default:
- return false;
- }
- }
- })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
- return this.negate ? !result : result;
- };
- Condition.prototype.type = 'Condition';
- var UnicodeDescriptor = function (value) {
- this.value = value;
- };
- UnicodeDescriptor.prototype = new Node();
- UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
- var Negative = function (node) {
- this.value = node;
- };
- Negative.prototype = new Node();
- Negative.prototype.genCSS = function (context, output) {
- output.add('-');
- this.value.genCSS(context, output);
- };
- Negative.prototype.eval = function (context) {
- if (context.isMathOn()) {
- return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
- }
- return new Negative(this.value.eval(context));
- };
- Negative.prototype.type = 'Negative';
- var Extend = function (selector, option, index, currentFileInfo, visibilityInfo) {
- this.selector = selector;
- this.option = option;
- this.object_id = Extend.next_id++;
- this.parent_ids = [this.object_id];
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.copyVisibilityInfo(visibilityInfo);
- this.allowRoot = true;
- switch (option) {
- case 'all':
- this.allowBefore = true;
- this.allowAfter = true;
- break;
- default:
- this.allowBefore = false;
- this.allowAfter = false;
- break;
- }
- this.setParent(this.selector, this);
- };
- Extend.prototype = new Node();
- Extend.prototype.accept = function (visitor) {
- this.selector = visitor.visit(this.selector);
- };
- Extend.prototype.eval = function (context) {
- return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- };
- Extend.prototype.clone = function (context) {
- return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- };
-
- Extend.prototype.findSelfSelectors = function (selectors) {
- var selfElements = [];
- var i;
- var selectorElements;
- for (i = 0; i < selectors.length; i++) {
- selectorElements = selectors[i].elements;
-
-
- if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
- selectorElements[0].combinator.value = ' ';
- }
- selfElements = selfElements.concat(selectors[i].elements);
- }
- this.selfSelectors = [new Selector(selfElements)];
- this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
- };
-
- Extend.next_id = 0;
- Extend.prototype.type = 'Extend';
- var VariableCall = function (variable, index, currentFileInfo) {
- this.variable = variable;
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.allowRoot = true;
- };
- VariableCall.prototype = new Node();
- VariableCall.prototype.eval = function (context) {
- var rules;
- var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
- var error = new LessError({ message: "Could not evaluate variable call " + this.variable });
- if (!detachedRuleset.ruleset) {
- if (detachedRuleset.rules) {
- rules = detachedRuleset;
- }
- else if (Array.isArray(detachedRuleset)) {
- rules = new Ruleset('', detachedRuleset);
- }
- else if (Array.isArray(detachedRuleset.value)) {
- rules = new Ruleset('', detachedRuleset.value);
- }
- else {
- throw error;
- }
- detachedRuleset = new DetachedRuleset(rules);
- }
- if (detachedRuleset.ruleset) {
- return detachedRuleset.callEval(context);
- }
- throw error;
- };
- VariableCall.prototype.type = 'VariableCall';
- var NamespaceValue = function (ruleCall, lookups, index, fileInfo) {
- this.value = ruleCall;
- this.lookups = lookups;
- this._index = index;
- this._fileInfo = fileInfo;
- };
- NamespaceValue.prototype = new Node();
- NamespaceValue.prototype.eval = function (context) {
- var i;
- var name;
- var rules = this.value.eval(context);
- for (i = 0; i < this.lookups.length; i++) {
- name = this.lookups[i];
-
- if (Array.isArray(rules)) {
- rules = new Ruleset([new Selector()], rules);
- }
- if (name === '') {
- rules = rules.lastDeclaration();
- }
- else if (name.charAt(0) === '@') {
- if (name.charAt(1) === '@') {
- name = "@" + new Variable(name.substr(1)).eval(context).value;
- }
- if (rules.variables) {
- rules = rules.variable(name);
- }
- if (!rules) {
- throw { type: 'Name', message: "variable " + name + " not found", filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
- }
- else {
- if (name.substring(0, 2) === '$@') {
- name = "$" + new Variable(name.substr(1)).eval(context).value;
- }
- else {
- name = name.charAt(0) === '$' ? name : "$" + name;
- }
- if (rules.properties) {
- rules = rules.property(name);
- }
- if (!rules) {
- throw { type: 'Name', message: "property \"" + name.substr(1) + "\" not found", filename: this.fileInfo().filename,
- index: this.getIndex() };
- }
-
-
- rules = rules[rules.length - 1];
- }
- if (rules.value) {
- rules = rules.eval(context).value;
- }
- if (rules.ruleset) {
- rules = rules.ruleset.eval(context);
- }
- }
- return rules;
- };
- NamespaceValue.prototype.type = 'NamespaceValue';
- var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
- this.name = name || 'anonymous mixin';
- this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
- this.params = params;
- this.condition = condition;
- this.variadic = variadic;
- this.arity = params.length;
- this.rules = rules;
- this._lookups = {};
- var optionalParameters = [];
- this.required = params.reduce(function (count, p) {
- if (!p.name || (p.name && !p.value)) {
- return count + 1;
- }
- else {
- optionalParameters.push(p.name);
- return count;
- }
- }, 0);
- this.optionalParameters = optionalParameters;
- this.frames = frames;
- this.copyVisibilityInfo(visibilityInfo);
- this.allowRoot = true;
- };
- Definition.prototype = new Ruleset();
- Definition.prototype.accept = function (visitor) {
- if (this.params && this.params.length) {
- this.params = visitor.visitArray(this.params);
- }
- this.rules = visitor.visitArray(this.rules);
- if (this.condition) {
- this.condition = visitor.visit(this.condition);
- }
- };
- Definition.prototype.evalParams = function (context, mixinEnv, args, evaldArguments) {
-
- var frame = new Ruleset(null, null);
- var varargs;
- var arg;
- var params = copyArray(this.params);
- var i;
- var j;
- var val;
- var name;
- var isNamedFound;
- var argIndex;
- var argsLength = 0;
- if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
- frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
- }
- mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
- if (args) {
- args = copyArray(args);
- argsLength = args.length;
- for (i = 0; i < argsLength; i++) {
- arg = args[i];
- if (name = (arg && arg.name)) {
- isNamedFound = false;
- for (j = 0; j < params.length; j++) {
- if (!evaldArguments[j] && name === params[j].name) {
- evaldArguments[j] = arg.value.eval(context);
- frame.prependRule(new Declaration(name, arg.value.eval(context)));
- isNamedFound = true;
- break;
- }
- }
- if (isNamedFound) {
- args.splice(i, 1);
- i--;
- continue;
- }
- else {
- throw { type: 'Runtime', message: "Named argument for " + this.name + " " + args[i].name + " not found" };
- }
- }
- }
- }
- argIndex = 0;
- for (i = 0; i < params.length; i++) {
- if (evaldArguments[i]) {
- continue;
- }
- arg = args && args[argIndex];
- if (name = params[i].name) {
- if (params[i].variadic) {
- varargs = [];
- for (j = argIndex; j < argsLength; j++) {
- varargs.push(args[j].value.eval(context));
- }
- frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
- }
- else {
- val = arg && arg.value;
- if (val) {
-
- if (Array.isArray(val)) {
- val = new DetachedRuleset(new Ruleset('', val));
- }
- else {
- val = val.eval(context);
- }
- }
- else if (params[i].value) {
- val = params[i].value.eval(mixinEnv);
- frame.resetCache();
- }
- else {
- throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + " (" + argsLength + " for " + this.arity + ")" };
- }
- frame.prependRule(new Declaration(name, val));
- evaldArguments[i] = val;
- }
- }
- if (params[i].variadic && args) {
- for (j = argIndex; j < argsLength; j++) {
- evaldArguments[j] = args[j].value.eval(context);
- }
- }
- argIndex++;
- }
- return frame;
- };
- Definition.prototype.makeImportant = function () {
- var rules = !this.rules ? this.rules : this.rules.map(function (r) {
- if (r.makeImportant) {
- return r.makeImportant(true);
- }
- else {
- return r;
- }
- });
- var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
- return result;
- };
- Definition.prototype.eval = function (context) {
- return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
- };
- Definition.prototype.evalCall = function (context, args, important) {
- var _arguments = [];
- var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
- var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
- var rules;
- var ruleset;
- frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
- rules = copyArray(this.rules);
- ruleset = new Ruleset(null, rules);
- ruleset.originalRuleset = this;
- ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
- if (important) {
- ruleset = ruleset.makeImportant();
- }
- return ruleset;
- };
- Definition.prototype.matchCondition = function (args, context) {
- if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context, new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
- .concat(this.frames || [])
- .concat(context.frames)))) {
- return false;
- }
- return true;
- };
- Definition.prototype.matchArgs = function (args, context) {
- var allArgsCnt = (args && args.length) || 0;
- var len;
- var optionalParameters = this.optionalParameters;
- var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
- if (optionalParameters.indexOf(p.name) < 0) {
- return count + 1;
- }
- else {
- return count;
- }
- }, 0);
- if (!this.variadic) {
- if (requiredArgsCnt < this.required) {
- return false;
- }
- if (allArgsCnt > this.params.length) {
- return false;
- }
- }
- else {
- if (requiredArgsCnt < (this.required - 1)) {
- return false;
- }
- }
-
- len = Math.min(requiredArgsCnt, this.arity);
- for (var i = 0; i < len; i++) {
- if (!this.params[i].name && !this.params[i].variadic) {
- if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
- return false;
- }
- }
- }
- return true;
- };
- Definition.prototype.type = 'MixinDefinition';
- Definition.prototype.evalFirst = true;
- var MixinCall = function (elements, args, index, currentFileInfo, important) {
- this.selector = new Selector(elements);
- this.arguments = args || [];
- this._index = index;
- this._fileInfo = currentFileInfo;
- this.important = important;
- this.allowRoot = true;
- this.setParent(this.selector, this);
- };
- MixinCall.prototype = new Node();
- MixinCall.prototype.accept = function (visitor) {
- if (this.selector) {
- this.selector = visitor.visit(this.selector);
- }
- if (this.arguments.length) {
- this.arguments = visitor.visitArray(this.arguments);
- }
- };
- MixinCall.prototype.eval = function (context) {
- var mixins;
- var mixin;
- var mixinPath;
- var args = [];
- var arg;
- var argValue;
- var rules = [];
- var match = false;
- var i;
- var m;
- var f;
- var isRecursive;
- var isOneFound;
- var candidates = [];
- var candidate;
- var conditionResult = [];
- var defaultResult;
- var defFalseEitherCase = -1;
- var defNone = 0;
- var defTrue = 1;
- var defFalse = 2;
- var count;
- var originalRuleset;
- var noArgumentsFilter;
- this.selector = this.selector.eval(context);
- function calcDefGroup(mixin, mixinPath) {
- var f;
- var p;
- var namespace;
- for (f = 0; f < 2; f++) {
- conditionResult[f] = true;
- defaultFunc.value(f);
- for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
- namespace = mixinPath[p];
- if (namespace.matchCondition) {
- conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
- }
- }
- if (mixin.matchCondition) {
- conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
- }
- }
- if (conditionResult[0] || conditionResult[1]) {
- if (conditionResult[0] != conditionResult[1]) {
- return conditionResult[1] ?
- defTrue : defFalse;
- }
- return defNone;
- }
- return defFalseEitherCase;
- }
- for (i = 0; i < this.arguments.length; i++) {
- arg = this.arguments[i];
- argValue = arg.value.eval(context);
- if (arg.expand && Array.isArray(argValue.value)) {
- argValue = argValue.value;
- for (m = 0; m < argValue.length; m++) {
- args.push({ value: argValue[m] });
- }
- }
- else {
- args.push({ name: arg.name, value: argValue });
- }
- }
- noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
- for (i = 0; i < context.frames.length; i++) {
- if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
- isOneFound = true;
-
-
-
-
- for (m = 0; m < mixins.length; m++) {
- mixin = mixins[m].rule;
- mixinPath = mixins[m].path;
- isRecursive = false;
- for (f = 0; f < context.frames.length; f++) {
- if ((!(mixin instanceof Definition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
- isRecursive = true;
- break;
- }
- }
- if (isRecursive) {
- continue;
- }
- if (mixin.matchArgs(args, context)) {
- candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
- if (candidate.group !== defFalseEitherCase) {
- candidates.push(candidate);
- }
- match = true;
- }
- }
- defaultFunc.reset();
- count = [0, 0, 0];
- for (m = 0; m < candidates.length; m++) {
- count[candidates[m].group]++;
- }
- if (count[defNone] > 0) {
- defaultResult = defFalse;
- }
- else {
- defaultResult = defTrue;
- if ((count[defTrue] + count[defFalse]) > 1) {
- throw { type: 'Runtime', message: "Ambiguous use of `default()` found when matching for `" + this.format(args) + "`", index: this.getIndex(), filename: this.fileInfo().filename };
- }
- }
- for (m = 0; m < candidates.length; m++) {
- candidate = candidates[m].group;
- if ((candidate === defNone) || (candidate === defaultResult)) {
- try {
- mixin = candidates[m].mixin;
- if (!(mixin instanceof Definition)) {
- originalRuleset = mixin.originalRuleset || mixin;
- mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
- mixin.originalRuleset = originalRuleset;
- }
- var newRules = mixin.evalCall(context, args, this.important).rules;
- this._setVisibilityToReplacement(newRules);
- Array.prototype.push.apply(rules, newRules);
- }
- catch (e) {
- throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
- }
- }
- }
- if (match) {
- return rules;
- }
- }
- }
- if (isOneFound) {
- throw { type: 'Runtime', message: "No matching definition was found for `" + this.format(args) + "`", index: this.getIndex(), filename: this.fileInfo().filename };
- }
- else {
- throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.getIndex(), filename: this.fileInfo().filename };
- }
- };
- MixinCall.prototype._setVisibilityToReplacement = function (replacement) {
- var i;
- var rule;
- if (this.blocksVisibility()) {
- for (i = 0; i < replacement.length; i++) {
- rule = replacement[i];
- rule.addVisibilityBlock();
- }
- }
- };
- MixinCall.prototype.format = function (args) {
- return this.selector.toCSS().trim() + "(" + (args ? args.map(function (a) {
- var argValue = '';
- if (a.name) {
- argValue += a.name + ":";
- }
- if (a.value.toCSS) {
- argValue += a.value.toCSS();
- }
- else {
- argValue += '???';
- }
- return argValue;
- }).join(', ') : '') + ")";
- };
- MixinCall.prototype.type = 'MixinCall';
- var tree = {
- Node: Node, Color: Color, AtRule: AtRule, DetachedRuleset: DetachedRuleset, Operation: Operation,
- Dimension: Dimension, Unit: Unit, Keyword: Keyword, Variable: Variable, Property: Property,
- Ruleset: Ruleset, Element: Element, Attribute: Attribute, Combinator: Combinator, Selector: Selector,
- Quoted: Quoted, Expression: Expression, Declaration: Declaration, Call: Call, URL: URL, Import: Import,
- Comment: Comment, Anonymous: Anonymous, Value: Value, JavaScript: JavaScript, Assignment: Assignment,
- Condition: Condition, Paren: Paren, Media: Media, UnicodeDescriptor: UnicodeDescriptor, Negative: Negative,
- Extend: Extend, VariableCall: VariableCall, NamespaceValue: NamespaceValue,
- mixin: {
- Call: MixinCall,
- Definition: Definition
- }
- };
- var logger = {
- error: function (msg) {
- this._fireEvent('error', msg);
- },
- warn: function (msg) {
- this._fireEvent('warn', msg);
- },
- info: function (msg) {
- this._fireEvent('info', msg);
- },
- debug: function (msg) {
- this._fireEvent('debug', msg);
- },
- addListener: function (listener) {
- this._listeners.push(listener);
- },
- removeListener: function (listener) {
- for (var i = 0; i < this._listeners.length; i++) {
- if (this._listeners[i] === listener) {
- this._listeners.splice(i, 1);
- return;
- }
- }
- },
- _fireEvent: function (type, msg) {
- for (var i = 0; i < this._listeners.length; i++) {
- var logFunction = this._listeners[i][type];
- if (logFunction) {
- logFunction(msg);
- }
- }
- },
- _listeners: []
- };
-
- var environment = (function () {
- function environment(externalEnvironment, fileManagers) {
- this.fileManagers = fileManagers || [];
- externalEnvironment = externalEnvironment || {};
- var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
- var requiredFunctions = [];
- var functions = requiredFunctions.concat(optionalFunctions);
- for (var i = 0; i < functions.length; i++) {
- var propName = functions[i];
- var environmentFunc = externalEnvironment[propName];
- if (environmentFunc) {
- this[propName] = environmentFunc.bind(externalEnvironment);
- }
- else if (i < requiredFunctions.length) {
- this.warn("missing required function in environment - " + propName);
- }
- }
- }
- environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
- if (!filename) {
- logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
- }
- if (currentDirectory == null) {
- logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
- }
- var fileManagers = this.fileManagers;
- if (options.pluginManager) {
- fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
- }
- for (var i = fileManagers.length - 1; i >= 0; i--) {
- var fileManager = fileManagers[i];
- if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
- return fileManager;
- }
- }
- return null;
- };
- environment.prototype.addFileManager = function (fileManager) {
- this.fileManagers.push(fileManager);
- };
- environment.prototype.clearFileManagers = function () {
- this.fileManagers = [];
- };
- return environment;
- }());
- var AbstractFileManager = (function () {
- function AbstractFileManager() {
- }
- AbstractFileManager.prototype.getPath = function (filename) {
- var j = filename.lastIndexOf('?');
- if (j > 0) {
- filename = filename.slice(0, j);
- }
- j = filename.lastIndexOf('/');
- if (j < 0) {
- j = filename.lastIndexOf('\\');
- }
- if (j < 0) {
- return '';
- }
- return filename.slice(0, j + 1);
- };
- AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
- return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
- };
- AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
- return this.tryAppendExtension(path, '.less');
- };
- AbstractFileManager.prototype.supportsSync = function () { return false; };
- AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () { return false; };
- AbstractFileManager.prototype.isPathAbsolute = function (filename) {
- return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
- };
-
- AbstractFileManager.prototype.join = function (basePath, laterPath) {
- if (!basePath) {
- return laterPath;
- }
- return basePath + laterPath;
- };
- AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
-
- var urlParts = this.extractUrlParts(url);
- var baseUrlParts = this.extractUrlParts(baseUrl);
- var i;
- var max;
- var urlDirectories;
- var baseUrlDirectories;
- var diff = '';
- if (urlParts.hostPart !== baseUrlParts.hostPart) {
- return '';
- }
- max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
- for (i = 0; i < max; i++) {
- if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
- break;
- }
- }
- baseUrlDirectories = baseUrlParts.directories.slice(i);
- urlDirectories = urlParts.directories.slice(i);
- for (i = 0; i < baseUrlDirectories.length - 1; i++) {
- diff += '../';
- }
- for (i = 0; i < urlDirectories.length - 1; i++) {
- diff += urlDirectories[i] + "/";
- }
- return diff;
- };
-
- AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
-
-
-
-
-
- var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
- var urlParts = url.match(urlPartsRegex);
- var returner = {};
- var rawDirectories = [];
- var directories = [];
- var i;
- var baseUrlParts;
- if (!urlParts) {
- throw new Error("Could not parse sheet href - '" + url + "'");
- }
-
- if (baseUrl && (!urlParts[1] || urlParts[2])) {
- baseUrlParts = baseUrl.match(urlPartsRegex);
- if (!baseUrlParts) {
- throw new Error("Could not parse page url - '" + baseUrl + "'");
- }
- urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
- if (!urlParts[2]) {
- urlParts[3] = baseUrlParts[3] + urlParts[3];
- }
- }
- if (urlParts[3]) {
- rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
-
- for (i = 0; i < rawDirectories.length; i++) {
- if (rawDirectories[i] === '..') {
- directories.pop();
- }
- else if (rawDirectories[i] !== '.') {
- directories.push(rawDirectories[i]);
- }
- }
- }
- returner.hostPart = urlParts[1];
- returner.directories = directories;
- returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
- returner.path = (urlParts[1] || '') + directories.join('/');
- returner.filename = urlParts[4];
- returner.fileUrl = returner.path + (urlParts[4] || '');
- returner.url = returner.fileUrl + (urlParts[5] || '');
- return returner;
- };
- return AbstractFileManager;
- }());
- var AbstractPluginLoader = (function () {
- function AbstractPluginLoader() {
-
- this.require = function () { return null; };
- }
- AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
- var loader;
- var registry;
- var pluginObj;
- var localModule;
- var pluginManager;
- var filename;
- var result;
- pluginManager = context.pluginManager;
- if (fileInfo) {
- if (typeof fileInfo === 'string') {
- filename = fileInfo;
- }
- else {
- filename = fileInfo.filename;
- }
- }
- var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
- if (filename) {
- pluginObj = pluginManager.get(filename);
- if (pluginObj) {
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
- if (result) {
- return result;
- }
- try {
- if (pluginObj.use) {
- pluginObj.use.call(this.context, pluginObj);
- }
- }
- catch (e) {
- e.message = e.message || 'Error during @plugin call';
- return new LessError(e, imports, filename);
- }
- return pluginObj;
- }
- }
- localModule = {
- exports: {},
- pluginManager: pluginManager,
- fileInfo: fileInfo
- };
- registry = functionRegistry.create();
- var registerPlugin = function (obj) {
- pluginObj = obj;
- };
- try {
- loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
- loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
- }
- catch (e) {
- return new LessError(e, imports, filename);
- }
- if (!pluginObj) {
- pluginObj = localModule.exports;
- }
- pluginObj = this.validatePlugin(pluginObj, filename, shortname);
- if (pluginObj instanceof LessError) {
- return pluginObj;
- }
- if (pluginObj) {
- pluginObj.imports = imports;
- pluginObj.filename = filename;
-
- if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
- if (result) {
- return result;
- }
- }
-
- pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
- pluginObj.functions = registry.getLocalFunctions();
-
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
- if (result) {
- return result;
- }
-
- try {
- if (pluginObj.use) {
- pluginObj.use.call(this.context, pluginObj);
- }
- }
- catch (e) {
- e.message = e.message || 'Error during @plugin call';
- return new LessError(e, imports, filename);
- }
- }
- else {
- return new LessError({ message: 'Not a valid plugin' }, imports, filename);
- }
- return pluginObj;
- };
- AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
- if (options && !plugin.setOptions) {
- return new LessError({
- message: "Options have been provided but the plugin " + name + " does not support any options."
- });
- }
- try {
- plugin.setOptions && plugin.setOptions(options);
- }
- catch (e) {
- return new LessError(e);
- }
- };
- AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
- if (plugin) {
-
-
- if (typeof plugin === 'function') {
- plugin = new plugin();
- }
- if (plugin.minVersion) {
- if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
- return new LessError({
- message: "Plugin " + name + " requires version " + this.versionToString(plugin.minVersion)
- });
- }
- }
- return plugin;
- }
- return null;
- };
- AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
- if (typeof aVersion === 'string') {
- aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
- aVersion.shift();
- }
- for (var i = 0; i < aVersion.length; i++) {
- if (aVersion[i] !== bVersion[i]) {
- return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
- }
- }
- return 0;
- };
- AbstractPluginLoader.prototype.versionToString = function (version) {
- var versionString = '';
- for (var i = 0; i < version.length; i++) {
- versionString += (versionString ? '.' : '') + version[i];
- }
- return versionString;
- };
- AbstractPluginLoader.prototype.printUsage = function (plugins) {
- for (var i = 0; i < plugins.length; i++) {
- var plugin = plugins[i];
- if (plugin.printUsage) {
- plugin.printUsage();
- }
- }
- };
- return AbstractPluginLoader;
- }());
- var _visitArgs = { visitDeeper: true };
- var _hasIndexed = false;
- function _noop(node) {
- return node;
- }
- function indexNodeTypes(parent, ticker) {
-
- var key;
- var child;
- for (key in parent) {
-
- child = parent[key];
- switch (typeof child) {
- case 'function':
-
-
- if (child.prototype && child.prototype.type) {
- child.prototype.typeIndex = ticker++;
- }
- break;
- case 'object':
- ticker = indexNodeTypes(child, ticker);
- break;
- }
- }
- return ticker;
- }
- var Visitor = (function () {
- function Visitor(implementation) {
- this._implementation = implementation;
- this._visitInCache = {};
- this._visitOutCache = {};
- if (!_hasIndexed) {
- indexNodeTypes(tree, 1);
- _hasIndexed = true;
- }
- }
- Visitor.prototype.visit = function (node) {
- if (!node) {
- return node;
- }
- var nodeTypeIndex = node.typeIndex;
- if (!nodeTypeIndex) {
-
- if (node.value && node.value.typeIndex) {
- this.visit(node.value);
- }
- return node;
- }
- var impl = this._implementation;
- var func = this._visitInCache[nodeTypeIndex];
- var funcOut = this._visitOutCache[nodeTypeIndex];
- var visitArgs = _visitArgs;
- var fnName;
- visitArgs.visitDeeper = true;
- if (!func) {
- fnName = "visit" + node.type;
- func = impl[fnName] || _noop;
- funcOut = impl[fnName + "Out"] || _noop;
- this._visitInCache[nodeTypeIndex] = func;
- this._visitOutCache[nodeTypeIndex] = funcOut;
- }
- if (func !== _noop) {
- var newNode = func.call(impl, node, visitArgs);
- if (node && impl.isReplacing) {
- node = newNode;
- }
- }
- if (visitArgs.visitDeeper && node) {
- if (node.length) {
- for (var i = 0, cnt = node.length; i < cnt; i++) {
- if (node[i].accept) {
- node[i].accept(this);
- }
- }
- }
- else if (node.accept) {
- node.accept(this);
- }
- }
- if (funcOut != _noop) {
- funcOut.call(impl, node);
- }
- return node;
- };
- Visitor.prototype.visitArray = function (nodes, nonReplacing) {
- if (!nodes) {
- return nodes;
- }
- var cnt = nodes.length;
- var i;
-
- if (nonReplacing || !this._implementation.isReplacing) {
- for (i = 0; i < cnt; i++) {
- this.visit(nodes[i]);
- }
- return nodes;
- }
-
- var out = [];
- for (i = 0; i < cnt; i++) {
- var evald = this.visit(nodes[i]);
- if (evald === undefined) {
- continue;
- }
- if (!evald.splice) {
- out.push(evald);
- }
- else if (evald.length) {
- this.flatten(evald, out);
- }
- }
- return out;
- };
- Visitor.prototype.flatten = function (arr, out) {
- if (!out) {
- out = [];
- }
- var cnt;
- var i;
- var item;
- var nestedCnt;
- var j;
- var nestedItem;
- for (i = 0, cnt = arr.length; i < cnt; i++) {
- item = arr[i];
- if (item === undefined) {
- continue;
- }
- if (!item.splice) {
- out.push(item);
- continue;
- }
- for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
- nestedItem = item[j];
- if (nestedItem === undefined) {
- continue;
- }
- if (!nestedItem.splice) {
- out.push(nestedItem);
- }
- else if (nestedItem.length) {
- this.flatten(nestedItem, out);
- }
- }
- }
- return out;
- };
- return Visitor;
- }());
- var ImportSequencer = (function () {
- function ImportSequencer(onSequencerEmpty) {
- this.imports = [];
- this.variableImports = [];
- this._onSequencerEmpty = onSequencerEmpty;
- this._currentDepth = 0;
- }
- ImportSequencer.prototype.addImport = function (callback) {
- var importSequencer = this;
- var importItem = {
- callback: callback,
- args: null,
- isReady: false
- };
- this.imports.push(importItem);
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- importItem.args = Array.prototype.slice.call(args, 0);
- importItem.isReady = true;
- importSequencer.tryRun();
- };
- };
- ImportSequencer.prototype.addVariableImport = function (callback) {
- this.variableImports.push(callback);
- };
- ImportSequencer.prototype.tryRun = function () {
- this._currentDepth++;
- try {
- while (true) {
- while (this.imports.length > 0) {
- var importItem = this.imports[0];
- if (!importItem.isReady) {
- return;
- }
- this.imports = this.imports.slice(1);
- importItem.callback.apply(null, importItem.args);
- }
- if (this.variableImports.length === 0) {
- break;
- }
- var variableImport = this.variableImports[0];
- this.variableImports = this.variableImports.slice(1);
- variableImport();
- }
- }
- finally {
- this._currentDepth--;
- }
- if (this._currentDepth === 0 && this._onSequencerEmpty) {
- this._onSequencerEmpty();
- }
- };
- return ImportSequencer;
- }());
- var ImportVisitor = function (importer, finish) {
- this._visitor = new Visitor(this);
- this._importer = importer;
- this._finish = finish;
- this.context = new contexts.Eval();
- this.importCount = 0;
- this.onceFileDetectionMap = {};
- this.recursionDetector = {};
- this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
- };
- ImportVisitor.prototype = {
- isReplacing: false,
- run: function (root) {
- try {
-
- this._visitor.visit(root);
- }
- catch (e) {
- this.error = e;
- }
- this.isFinished = true;
- this._sequencer.tryRun();
- },
- _onSequencerEmpty: function () {
- if (!this.isFinished) {
- return;
- }
- this._finish(this.error);
- },
- visitImport: function (importNode, visitArgs) {
- var inlineCSS = importNode.options.inline;
- if (!importNode.css || inlineCSS) {
- var context = new contexts.Eval(this.context, copyArray(this.context.frames));
- var importParent = context.frames[0];
- this.importCount++;
- if (importNode.isVariableImport()) {
- this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
- }
- else {
- this.processImportNode(importNode, context, importParent);
- }
- }
- visitArgs.visitDeeper = false;
- },
- processImportNode: function (importNode, context, importParent) {
- var evaldImportNode;
- var inlineCSS = importNode.options.inline;
- try {
- evaldImportNode = importNode.evalForImport(context);
- }
- catch (e) {
- if (!e.filename) {
- e.index = importNode.getIndex();
- e.filename = importNode.fileInfo().filename;
- }
-
- importNode.css = true;
-
- importNode.error = e;
- }
- if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
- if (evaldImportNode.options.multiple) {
- context.importMultiple = true;
- }
-
- var tryAppendLessExtension = evaldImportNode.css === undefined;
- for (var i = 0; i < importParent.rules.length; i++) {
- if (importParent.rules[i] === importNode) {
- importParent.rules[i] = evaldImportNode;
- break;
- }
- }
- var onImported = this.onImported.bind(this, evaldImportNode, context);
- var sequencedOnImported = this._sequencer.addImport(onImported);
- this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
- }
- else {
- this.importCount--;
- if (this.isFinished) {
- this._sequencer.tryRun();
- }
- }
- },
- onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
- if (e) {
- if (!e.filename) {
- e.index = importNode.getIndex();
- e.filename = importNode.fileInfo().filename;
- }
- this.error = e;
- }
- var importVisitor = this;
- var inlineCSS = importNode.options.inline;
- var isPlugin = importNode.options.isPlugin;
- var isOptional = importNode.options.optional;
- var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
- if (!context.importMultiple) {
- if (duplicateImport) {
- importNode.skip = true;
- }
- else {
- importNode.skip = function () {
- if (fullPath in importVisitor.onceFileDetectionMap) {
- return true;
- }
- importVisitor.onceFileDetectionMap[fullPath] = true;
- return false;
- };
- }
- }
- if (!fullPath && isOptional) {
- importNode.skip = true;
- }
- if (root) {
- importNode.root = root;
- importNode.importedFilename = fullPath;
- if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
- importVisitor.recursionDetector[fullPath] = true;
- var oldContext = this.context;
- this.context = context;
- try {
- this._visitor.visit(root);
- }
- catch (e) {
- this.error = e;
- }
- this.context = oldContext;
- }
- }
- importVisitor.importCount--;
- if (importVisitor.isFinished) {
- importVisitor._sequencer.tryRun();
- }
- },
- visitDeclaration: function (declNode, visitArgs) {
- if (declNode.value.type === 'DetachedRuleset') {
- this.context.frames.unshift(declNode);
- }
- else {
- visitArgs.visitDeeper = false;
- }
- },
- visitDeclarationOut: function (declNode) {
- if (declNode.value.type === 'DetachedRuleset') {
- this.context.frames.shift();
- }
- },
- visitAtRule: function (atRuleNode, visitArgs) {
- this.context.frames.unshift(atRuleNode);
- },
- visitAtRuleOut: function (atRuleNode) {
- this.context.frames.shift();
- },
- visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
- this.context.frames.unshift(mixinDefinitionNode);
- },
- visitMixinDefinitionOut: function (mixinDefinitionNode) {
- this.context.frames.shift();
- },
- visitRuleset: function (rulesetNode, visitArgs) {
- this.context.frames.unshift(rulesetNode);
- },
- visitRulesetOut: function (rulesetNode) {
- this.context.frames.shift();
- },
- visitMedia: function (mediaNode, visitArgs) {
- this.context.frames.unshift(mediaNode.rules[0]);
- },
- visitMediaOut: function (mediaNode) {
- this.context.frames.shift();
- }
- };
- var SetTreeVisibilityVisitor = (function () {
- function SetTreeVisibilityVisitor(visible) {
- this.visible = visible;
- }
- SetTreeVisibilityVisitor.prototype.run = function (root) {
- this.visit(root);
- };
- SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
- if (!nodes) {
- return nodes;
- }
- var cnt = nodes.length;
- var i;
- for (i = 0; i < cnt; i++) {
- this.visit(nodes[i]);
- }
- return nodes;
- };
- SetTreeVisibilityVisitor.prototype.visit = function (node) {
- if (!node) {
- return node;
- }
- if (node.constructor === Array) {
- return this.visitArray(node);
- }
- if (!node.blocksVisibility || node.blocksVisibility()) {
- return node;
- }
- if (this.visible) {
- node.ensureVisibility();
- }
- else {
- node.ensureInvisibility();
- }
- node.accept(this);
- return node;
- };
- return SetTreeVisibilityVisitor;
- }());
-
- var ExtendFinderVisitor = (function () {
- function ExtendFinderVisitor() {
- this._visitor = new Visitor(this);
- this.contexts = [];
- this.allExtendsStack = [[]];
- }
- ExtendFinderVisitor.prototype.run = function (root) {
- root = this._visitor.visit(root);
- root.allExtends = this.allExtendsStack[0];
- return root;
- };
- ExtendFinderVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- ExtendFinderVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- ExtendFinderVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
- if (rulesetNode.root) {
- return;
- }
- var i;
- var j;
- var extend;
- var allSelectorsExtendList = [];
- var extendList;
-
- var rules = rulesetNode.rules;
- var ruleCnt = rules ? rules.length : 0;
- for (i = 0; i < ruleCnt; i++) {
- if (rulesetNode.rules[i] instanceof tree.Extend) {
- allSelectorsExtendList.push(rules[i]);
- rulesetNode.extendOnEveryPath = true;
- }
- }
-
-
- var paths = rulesetNode.paths;
- for (i = 0; i < paths.length; i++) {
- var selectorPath = paths[i];
- var selector = selectorPath[selectorPath.length - 1];
- var selExtendList = selector.extendList;
- extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
- : allSelectorsExtendList;
- if (extendList) {
- extendList = extendList.map(function (allSelectorsExtend) { return allSelectorsExtend.clone(); });
- }
- for (j = 0; j < extendList.length; j++) {
- this.foundExtends = true;
- extend = extendList[j];
- extend.findSelfSelectors(selectorPath);
- extend.ruleset = rulesetNode;
- if (j === 0) {
- extend.firstExtendOnThisSelectorPath = true;
- }
- this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
- }
- }
- this.contexts.push(rulesetNode.selectors);
- };
- ExtendFinderVisitor.prototype.visitRulesetOut = function (rulesetNode) {
- if (!rulesetNode.root) {
- this.contexts.length = this.contexts.length - 1;
- }
- };
- ExtendFinderVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
- mediaNode.allExtends = [];
- this.allExtendsStack.push(mediaNode.allExtends);
- };
- ExtendFinderVisitor.prototype.visitMediaOut = function (mediaNode) {
- this.allExtendsStack.length = this.allExtendsStack.length - 1;
- };
- ExtendFinderVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
- atRuleNode.allExtends = [];
- this.allExtendsStack.push(atRuleNode.allExtends);
- };
- ExtendFinderVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
- this.allExtendsStack.length = this.allExtendsStack.length - 1;
- };
- return ExtendFinderVisitor;
- }());
- var ProcessExtendsVisitor = (function () {
- function ProcessExtendsVisitor() {
- this._visitor = new Visitor(this);
- }
- ProcessExtendsVisitor.prototype.run = function (root) {
- var extendFinder = new ExtendFinderVisitor();
- this.extendIndices = {};
- extendFinder.run(root);
- if (!extendFinder.foundExtends) {
- return root;
- }
- root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
- this.allExtendsStack = [root.allExtends];
- var newRoot = this._visitor.visit(root);
- this.checkExtendsForNonMatched(root.allExtends);
- return newRoot;
- };
- ProcessExtendsVisitor.prototype.checkExtendsForNonMatched = function (extendList) {
- var indices = this.extendIndices;
- extendList.filter(function (extend) { return !extend.hasFoundMatches && extend.parent_ids.length == 1; }).forEach(function (extend) {
- var selector = '_unknown_';
- try {
- selector = extend.selector.toCSS({});
- }
- catch (_) { }
- if (!indices[extend.index + " " + selector]) {
- indices[extend.index + " " + selector] = true;
- logger.warn("extend '" + selector + "' has no matches");
- }
- });
- };
- ProcessExtendsVisitor.prototype.doExtendChaining = function (extendsList, extendsListTarget, iterationCount) {
-
-
-
-
-
-
-
-
- var extendIndex;
- var targetExtendIndex;
- var matches;
- var extendsToAdd = [];
- var newSelector;
- var extendVisitor = this;
- var selectorPath;
- var extend;
- var targetExtend;
- var newExtend;
- iterationCount = iterationCount || 0;
-
-
-
-
-
-
- for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
- for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
- extend = extendsList[extendIndex];
- targetExtend = extendsListTarget[targetExtendIndex];
-
- if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
- continue;
- }
-
- selectorPath = [targetExtend.selfSelectors[0]];
- matches = extendVisitor.findMatch(extend, selectorPath);
- if (matches.length) {
- extend.hasFoundMatches = true;
-
- extend.selfSelectors.forEach(function (selfSelector) {
- var info = targetExtend.visibilityInfo();
-
- newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
-
- newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
- newExtend.selfSelectors = newSelector;
-
- newSelector[newSelector.length - 1].extendList = [newExtend];
-
- extendsToAdd.push(newExtend);
- newExtend.ruleset = targetExtend.ruleset;
-
- newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
-
-
-
- if (targetExtend.firstExtendOnThisSelectorPath) {
- newExtend.firstExtendOnThisSelectorPath = true;
- targetExtend.ruleset.paths.push(newSelector);
- }
- });
- }
- }
- }
- if (extendsToAdd.length) {
-
-
- this.extendChainCount++;
- if (iterationCount > 100) {
- var selectorOne = '{unable to calculate}';
- var selectorTwo = '{unable to calculate}';
- try {
- selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
- selectorTwo = extendsToAdd[0].selector.toCSS();
- }
- catch (e) { }
- throw { message: "extend circular reference detected. One of the circular extends is currently:" + selectorOne + ":extend(" + selectorTwo + ")" };
- }
-
-
- return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
- }
- else {
- return extendsToAdd;
- }
- };
- ProcessExtendsVisitor.prototype.visitDeclaration = function (ruleNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- ProcessExtendsVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- ProcessExtendsVisitor.prototype.visitSelector = function (selectorNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- ProcessExtendsVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
- if (rulesetNode.root) {
- return;
- }
- var matches;
- var pathIndex;
- var extendIndex;
- var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
- var selectorsToAdd = [];
- var extendVisitor = this;
- var selectorPath;
-
- for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
- for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
- selectorPath = rulesetNode.paths[pathIndex];
-
- if (rulesetNode.extendOnEveryPath) {
- continue;
- }
- var extendList = selectorPath[selectorPath.length - 1].extendList;
- if (extendList && extendList.length) {
- continue;
- }
- matches = this.findMatch(allExtends[extendIndex], selectorPath);
- if (matches.length) {
- allExtends[extendIndex].hasFoundMatches = true;
- allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
- var extendedSelectors;
- extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
- selectorsToAdd.push(extendedSelectors);
- });
- }
- }
- }
- rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
- };
- ProcessExtendsVisitor.prototype.findMatch = function (extend, haystackSelectorPath) {
-
-
-
-
- var haystackSelectorIndex;
- var hackstackSelector;
- var hackstackElementIndex;
- var haystackElement;
- var targetCombinator;
- var i;
- var extendVisitor = this;
- var needleElements = extend.selector.elements;
- var potentialMatches = [];
- var potentialMatch;
- var matches = [];
-
- for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
- hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
- for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
- haystackElement = hackstackSelector.elements[hackstackElementIndex];
-
- if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
- potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
- initialCombinator: haystackElement.combinator });
- }
- for (i = 0; i < potentialMatches.length; i++) {
- potentialMatch = potentialMatches[i];
-
-
-
- targetCombinator = haystackElement.combinator.value;
- if (targetCombinator === '' && hackstackElementIndex === 0) {
- targetCombinator = ' ';
- }
-
- if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
- (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
- potentialMatch = null;
- }
- else {
- potentialMatch.matched++;
- }
-
- if (potentialMatch) {
- potentialMatch.finished = potentialMatch.matched === needleElements.length;
- if (potentialMatch.finished &&
- (!extend.allowAfter &&
- (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
- potentialMatch = null;
- }
- }
-
- if (potentialMatch) {
- if (potentialMatch.finished) {
- potentialMatch.length = needleElements.length;
- potentialMatch.endPathIndex = haystackSelectorIndex;
- potentialMatch.endPathElementIndex = hackstackElementIndex + 1;
- potentialMatches.length = 0;
- matches.push(potentialMatch);
- }
- }
- else {
- potentialMatches.splice(i, 1);
- i--;
- }
- }
- }
- }
- return matches;
- };
- ProcessExtendsVisitor.prototype.isElementValuesEqual = function (elementValue1, elementValue2) {
- if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
- return elementValue1 === elementValue2;
- }
- if (elementValue1 instanceof tree.Attribute) {
- if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
- return false;
- }
- if (!elementValue1.value || !elementValue2.value) {
- if (elementValue1.value || elementValue2.value) {
- return false;
- }
- return true;
- }
- elementValue1 = elementValue1.value.value || elementValue1.value;
- elementValue2 = elementValue2.value.value || elementValue2.value;
- return elementValue1 === elementValue2;
- }
- elementValue1 = elementValue1.value;
- elementValue2 = elementValue2.value;
- if (elementValue1 instanceof tree.Selector) {
- if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
- return false;
- }
- for (var i = 0; i < elementValue1.elements.length; i++) {
- if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
- if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
- return false;
- }
- }
- if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
- return false;
- }
- }
- return true;
- }
- return false;
- };
- ProcessExtendsVisitor.prototype.extendSelector = function (matches, selectorPath, replacementSelector, isVisible) {
-
- var currentSelectorPathIndex = 0;
- var currentSelectorPathElementIndex = 0;
- var path = [];
- var matchIndex;
- var selector;
- var firstElement;
- var match;
- var newElements;
- for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
- match = matches[matchIndex];
- selector = selectorPath[match.pathIndex];
- firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
- if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1]
- .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
- currentSelectorPathElementIndex = 0;
- currentSelectorPathIndex++;
- }
- newElements = selector.elements
- .slice(currentSelectorPathElementIndex, match.index)
- .concat([firstElement])
- .concat(replacementSelector.elements.slice(1));
- if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
- path[path.length - 1].elements =
- path[path.length - 1].elements.concat(newElements);
- }
- else {
- path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
- path.push(new tree.Selector(newElements));
- }
- currentSelectorPathIndex = match.endPathIndex;
- currentSelectorPathElementIndex = match.endPathElementIndex;
- if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
- currentSelectorPathElementIndex = 0;
- currentSelectorPathIndex++;
- }
- }
- if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1]
- .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
- currentSelectorPathIndex++;
- }
- path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
- path = path.map(function (currentValue) {
-
- var derived = currentValue.createDerived(currentValue.elements);
- if (isVisible) {
- derived.ensureVisibility();
- }
- else {
- derived.ensureInvisibility();
- }
- return derived;
- });
- return path;
- };
- ProcessExtendsVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
- var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
- newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
- this.allExtendsStack.push(newAllExtends);
- };
- ProcessExtendsVisitor.prototype.visitMediaOut = function (mediaNode) {
- var lastIndex = this.allExtendsStack.length - 1;
- this.allExtendsStack.length = lastIndex;
- };
- ProcessExtendsVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
- var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
- newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
- this.allExtendsStack.push(newAllExtends);
- };
- ProcessExtendsVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
- var lastIndex = this.allExtendsStack.length - 1;
- this.allExtendsStack.length = lastIndex;
- };
- return ProcessExtendsVisitor;
- }());
- var JoinSelectorVisitor = (function () {
- function JoinSelectorVisitor() {
- this.contexts = [[]];
- this._visitor = new Visitor(this);
- }
- JoinSelectorVisitor.prototype.run = function (root) {
- return this._visitor.visit(root);
- };
- JoinSelectorVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- JoinSelectorVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- };
- JoinSelectorVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- var paths = [];
- var selectors;
- this.contexts.push(paths);
- if (!rulesetNode.root) {
- selectors = rulesetNode.selectors;
- if (selectors) {
- selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
- rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
- if (selectors) {
- rulesetNode.joinSelectors(paths, context, selectors);
- }
- }
- if (!selectors) {
- rulesetNode.rules = null;
- }
- rulesetNode.paths = paths;
- }
- };
- JoinSelectorVisitor.prototype.visitRulesetOut = function (rulesetNode) {
- this.contexts.length = this.contexts.length - 1;
- };
- JoinSelectorVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
- };
- JoinSelectorVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- if (atRuleNode.rules && atRuleNode.rules.length) {
- atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
- }
- };
- return JoinSelectorVisitor;
- }());
- var CSSVisitorUtils = (function () {
- function CSSVisitorUtils(context) {
- this._visitor = new Visitor(this);
- this._context = context;
- }
- CSSVisitorUtils.prototype.containsSilentNonBlockedChild = function (bodyRules) {
- var rule;
- if (!bodyRules) {
- return false;
- }
- for (var r = 0; r < bodyRules.length; r++) {
- rule = bodyRules[r];
- if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
-
-
- return true;
- }
- }
- return false;
- };
- CSSVisitorUtils.prototype.keepOnlyVisibleChilds = function (owner) {
- if (owner && owner.rules) {
- owner.rules = owner.rules.filter(function (thing) { return thing.isVisible(); });
- }
- };
- CSSVisitorUtils.prototype.isEmpty = function (owner) {
- return (owner && owner.rules)
- ? (owner.rules.length === 0) : true;
- };
- CSSVisitorUtils.prototype.hasVisibleSelector = function (rulesetNode) {
- return (rulesetNode && rulesetNode.paths)
- ? (rulesetNode.paths.length > 0) : false;
- };
- CSSVisitorUtils.prototype.resolveVisibility = function (node, originalRules) {
- if (!node.blocksVisibility()) {
- if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
- return;
- }
- return node;
- }
- var compiledRulesBody = node.rules[0];
- this.keepOnlyVisibleChilds(compiledRulesBody);
- if (this.isEmpty(compiledRulesBody)) {
- return;
- }
- node.ensureVisibility();
- node.removeVisibilityBlock();
- return node;
- };
- CSSVisitorUtils.prototype.isVisibleRuleset = function (rulesetNode) {
- if (rulesetNode.firstRoot) {
- return true;
- }
- if (this.isEmpty(rulesetNode)) {
- return false;
- }
- if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
- return false;
- }
- return true;
- };
- return CSSVisitorUtils;
- }());
- var ToCSSVisitor = function (context) {
- this._visitor = new Visitor(this);
- this._context = context;
- this.utils = new CSSVisitorUtils(context);
- };
- ToCSSVisitor.prototype = {
- isReplacing: true,
- run: function (root) {
- return this._visitor.visit(root);
- },
- visitDeclaration: function (declNode, visitArgs) {
- if (declNode.blocksVisibility() || declNode.variable) {
- return;
- }
- return declNode;
- },
- visitMixinDefinition: function (mixinNode, visitArgs) {
-
-
- mixinNode.frames = [];
- },
- visitExtend: function (extendNode, visitArgs) {
- },
- visitComment: function (commentNode, visitArgs) {
- if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
- return;
- }
- return commentNode;
- },
- visitMedia: function (mediaNode, visitArgs) {
- var originalRules = mediaNode.rules[0].rules;
- mediaNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- return this.utils.resolveVisibility(mediaNode, originalRules);
- },
- visitImport: function (importNode, visitArgs) {
- if (importNode.blocksVisibility()) {
- return;
- }
- return importNode;
- },
- visitAtRule: function (atRuleNode, visitArgs) {
- if (atRuleNode.rules && atRuleNode.rules.length) {
- return this.visitAtRuleWithBody(atRuleNode, visitArgs);
- }
- else {
- return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
- }
- },
- visitAnonymous: function (anonymousNode, visitArgs) {
- if (!anonymousNode.blocksVisibility()) {
- anonymousNode.accept(this._visitor);
- return anonymousNode;
- }
- },
- visitAtRuleWithBody: function (atRuleNode, visitArgs) {
-
-
- function hasFakeRuleset(atRuleNode) {
- var bodyRules = atRuleNode.rules;
- return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
- }
- function getBodyRules(atRuleNode) {
- var nodeRules = atRuleNode.rules;
- if (hasFakeRuleset(atRuleNode)) {
- return nodeRules[0].rules;
- }
- return nodeRules;
- }
-
-
-
- var originalRules = getBodyRules(atRuleNode);
- atRuleNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- if (!this.utils.isEmpty(atRuleNode)) {
- this._mergeRules(atRuleNode.rules[0].rules);
- }
- return this.utils.resolveVisibility(atRuleNode, originalRules);
- },
- visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
- if (atRuleNode.blocksVisibility()) {
- return;
- }
- if (atRuleNode.name === '@charset') {
-
-
-
- if (this.charset) {
- if (atRuleNode.debugInfo) {
- var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, '') + " */\n");
- comment.debugInfo = atRuleNode.debugInfo;
- return this._visitor.visit(comment);
- }
- return;
- }
- this.charset = true;
- }
- return atRuleNode;
- },
- checkValidNodes: function (rules, isRoot) {
- if (!rules) {
- return;
- }
- for (var i = 0; i < rules.length; i++) {
- var ruleNode = rules[i];
- if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
- throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
- index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
- }
- if (ruleNode instanceof tree.Call) {
- throw { message: "Function '" + ruleNode.name + "' is undefined", index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
- }
- if (ruleNode.type && !ruleNode.allowRoot) {
- throw { message: ruleNode.type + " node returned by a function is not valid here", index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
- }
- }
- },
- visitRuleset: function (rulesetNode, visitArgs) {
-
- var rule;
- var rulesets = [];
- this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
- if (!rulesetNode.root) {
-
- this._compileRulesetPaths(rulesetNode);
-
- var nodeRules = rulesetNode.rules;
- var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
- for (var i = 0; i < nodeRuleCnt;) {
- rule = nodeRules[i];
- if (rule && rule.rules) {
-
- rulesets.push(this._visitor.visit(rule));
- nodeRules.splice(i, 1);
- nodeRuleCnt--;
- continue;
- }
- i++;
- }
-
-
-
- if (nodeRuleCnt > 0) {
- rulesetNode.accept(this._visitor);
- }
- else {
- rulesetNode.rules = null;
- }
- visitArgs.visitDeeper = false;
- }
- else {
- rulesetNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- }
- if (rulesetNode.rules) {
- this._mergeRules(rulesetNode.rules);
- this._removeDuplicateRules(rulesetNode.rules);
- }
-
- if (this.utils.isVisibleRuleset(rulesetNode)) {
- rulesetNode.ensureVisibility();
- rulesets.splice(0, 0, rulesetNode);
- }
- if (rulesets.length === 1) {
- return rulesets[0];
- }
- return rulesets;
- },
- _compileRulesetPaths: function (rulesetNode) {
- if (rulesetNode.paths) {
- rulesetNode.paths = rulesetNode.paths
- .filter(function (p) {
- var i;
- if (p[0].elements[0].combinator.value === ' ') {
- p[0].elements[0].combinator = new (tree.Combinator)('');
- }
- for (i = 0; i < p.length; i++) {
- if (p[i].isVisible() && p[i].getIsOutput()) {
- return true;
- }
- }
- return false;
- });
- }
- },
- _removeDuplicateRules: function (rules) {
- if (!rules) {
- return;
- }
-
- var ruleCache = {};
- var ruleList;
- var rule;
- var i;
- for (i = rules.length - 1; i >= 0; i--) {
- rule = rules[i];
- if (rule instanceof tree.Declaration) {
- if (!ruleCache[rule.name]) {
- ruleCache[rule.name] = rule;
- }
- else {
- ruleList = ruleCache[rule.name];
- if (ruleList instanceof tree.Declaration) {
- ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
- }
- var ruleCSS = rule.toCSS(this._context);
- if (ruleList.indexOf(ruleCSS) !== -1) {
- rules.splice(i, 1);
- }
- else {
- ruleList.push(ruleCSS);
- }
- }
- }
- }
- },
- _mergeRules: function (rules) {
- if (!rules) {
- return;
- }
- var groups = {};
- var groupsArr = [];
- for (var i = 0; i < rules.length; i++) {
- var rule = rules[i];
- if (rule.merge) {
- var key = rule.name;
- groups[key] ? rules.splice(i--, 1) :
- groupsArr.push(groups[key] = []);
- groups[key].push(rule);
- }
- }
- groupsArr.forEach(function (group) {
- if (group.length > 0) {
- var result_1 = group[0];
- var space_1 = [];
- var comma_1 = [new tree.Expression(space_1)];
- group.forEach(function (rule) {
- if ((rule.merge === '+') && (space_1.length > 0)) {
- comma_1.push(new tree.Expression(space_1 = []));
- }
- space_1.push(rule.value);
- result_1.important = result_1.important || rule.important;
- });
- result_1.value = new tree.Value(comma_1);
- }
- });
- }
- };
- var visitors = {
- Visitor: Visitor,
- ImportVisitor: ImportVisitor,
- MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
- ExtendVisitor: ProcessExtendsVisitor,
- JoinSelectorVisitor: JoinSelectorVisitor,
- ToCSSVisitor: ToCSSVisitor
- };
-
- var chunker = (function (input, fail) {
- var len = input.length;
- var level = 0;
- var parenLevel = 0;
- var lastOpening;
- var lastOpeningParen;
- var lastMultiComment;
- var lastMultiCommentEndBrace;
- var chunks = [];
- var emitFrom = 0;
- var chunkerCurrentIndex;
- var currentChunkStartIndex;
- var cc;
- var cc2;
- var matched;
- function emitChunk(force) {
- var len = chunkerCurrentIndex - emitFrom;
- if (((len < 512) && !force) || !len) {
- return;
- }
- chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
- emitFrom = chunkerCurrentIndex + 1;
- }
- for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc = input.charCodeAt(chunkerCurrentIndex);
- if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
-
- continue;
- }
- switch (cc) {
- case 40:
- parenLevel++;
- lastOpeningParen = chunkerCurrentIndex;
- continue;
- case 41:
- if (--parenLevel < 0) {
- return fail('missing opening `(`', chunkerCurrentIndex);
- }
- continue;
- case 59:
- if (!parenLevel) {
- emitChunk();
- }
- continue;
- case 123:
- level++;
- lastOpening = chunkerCurrentIndex;
- continue;
- case 125:
- if (--level < 0) {
- return fail('missing opening `{`', chunkerCurrentIndex);
- }
- if (!level && !parenLevel) {
- emitChunk();
- }
- continue;
- case 92:
- if (chunkerCurrentIndex < len - 1) {
- chunkerCurrentIndex++;
- continue;
- }
- return fail('unescaped `\\`', chunkerCurrentIndex);
- case 34:
- case 39:
- case 96:
- matched = 0;
- currentChunkStartIndex = chunkerCurrentIndex;
- for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
- if (cc2 > 96) {
- continue;
- }
- if (cc2 == cc) {
- matched = 1;
- break;
- }
- if (cc2 == 92) {
- if (chunkerCurrentIndex == len - 1) {
- return fail('unescaped `\\`', chunkerCurrentIndex);
- }
- chunkerCurrentIndex++;
- }
- }
- if (matched) {
- continue;
- }
- return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
- case 47:
- if (parenLevel || (chunkerCurrentIndex == len - 1)) {
- continue;
- }
- cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
- if (cc2 == 47) {
-
- for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
- if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
- break;
- }
- }
- }
- else if (cc2 == 42) {
-
- lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
- for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
- if (cc2 == 125) {
- lastMultiCommentEndBrace = chunkerCurrentIndex;
- }
- if (cc2 != 42) {
- continue;
- }
- if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
- break;
- }
- }
- if (chunkerCurrentIndex == len - 1) {
- return fail('missing closing `*/`', currentChunkStartIndex);
- }
- chunkerCurrentIndex++;
- }
- continue;
- case 42:
- if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
- return fail('unmatched `/*`', chunkerCurrentIndex);
- }
- continue;
- }
- }
- if (level !== 0) {
- if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
- return fail('missing closing `}` or `*/`', lastOpening);
- }
- else {
- return fail('missing closing `}`', lastOpening);
- }
- }
- else if (parenLevel !== 0) {
- return fail('missing closing `)`', lastOpeningParen);
- }
- emitChunk(true);
- return chunks;
- });
- var getParserInput = (function () {
- var
- input;
- var
- j;
- var
- saveStack = [];
- var
- furthest;
- var
- furthestPossibleErrorMessage;
- var
- chunks;
- var
- current;
- var
- currentPos;
- var parserInput = {};
- var CHARCODE_SPACE = 32;
- var CHARCODE_TAB = 9;
- var CHARCODE_LF = 10;
- var CHARCODE_CR = 13;
- var CHARCODE_PLUS = 43;
- var CHARCODE_COMMA = 44;
- var CHARCODE_FORWARD_SLASH = 47;
- var CHARCODE_9 = 57;
- function skipWhitespace(length) {
- var oldi = parserInput.i;
- var oldj = j;
- var curr = parserInput.i - currentPos;
- var endIndex = parserInput.i + current.length - curr;
- var mem = (parserInput.i += length);
- var inp = input;
- var c;
- var nextChar;
- var comment;
- for (; parserInput.i < endIndex; parserInput.i++) {
- c = inp.charCodeAt(parserInput.i);
- if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
- nextChar = inp.charAt(parserInput.i + 1);
- if (nextChar === '/') {
- comment = { index: parserInput.i, isLineComment: true };
- var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
- if (nextNewLine < 0) {
- nextNewLine = endIndex;
- }
- parserInput.i = nextNewLine;
- comment.text = inp.substr(comment.index, parserInput.i - comment.index);
- parserInput.commentStore.push(comment);
- continue;
- }
- else if (nextChar === '*') {
- var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
- if (nextStarSlash >= 0) {
- comment = {
- index: parserInput.i,
- text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
- isLineComment: false
- };
- parserInput.i += comment.text.length - 1;
- parserInput.commentStore.push(comment);
- continue;
- }
- }
- break;
- }
- if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
- break;
- }
- }
- current = current.slice(length + parserInput.i - mem + curr);
- currentPos = parserInput.i;
- if (!current.length) {
- if (j < chunks.length - 1) {
- current = chunks[++j];
- skipWhitespace(0);
- return true;
- }
- parserInput.finished = true;
- }
- return oldi !== parserInput.i || oldj !== j;
- }
- parserInput.save = function () {
- currentPos = parserInput.i;
- saveStack.push({ current: current, i: parserInput.i, j: j });
- };
- parserInput.restore = function (possibleErrorMessage) {
- if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
- furthest = parserInput.i;
- furthestPossibleErrorMessage = possibleErrorMessage;
- }
- var state = saveStack.pop();
- current = state.current;
- currentPos = parserInput.i = state.i;
- j = state.j;
- };
- parserInput.forget = function () {
- saveStack.pop();
- };
- parserInput.isWhitespace = function (offset) {
- var pos = parserInput.i + (offset || 0);
- var code = input.charCodeAt(pos);
- return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
- };
-
- parserInput.$re = function (tok) {
- if (parserInput.i > currentPos) {
- current = current.slice(parserInput.i - currentPos);
- currentPos = parserInput.i;
- }
- var m = tok.exec(current);
- if (!m) {
- return null;
- }
- skipWhitespace(m[0].length);
- if (typeof m === 'string') {
- return m;
- }
- return m.length === 1 ? m[0] : m;
- };
- parserInput.$char = function (tok) {
- if (input.charAt(parserInput.i) !== tok) {
- return null;
- }
- skipWhitespace(1);
- return tok;
- };
- parserInput.$str = function (tok) {
- var tokLength = tok.length;
-
- for (var i = 0; i < tokLength; i++) {
- if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
- return null;
- }
- }
- skipWhitespace(tokLength);
- return tok;
- };
- parserInput.$quoted = function (loc) {
- var pos = loc || parserInput.i;
- var startChar = input.charAt(pos);
- if (startChar !== '\'' && startChar !== '"') {
- return;
- }
- var length = input.length;
- var currentPosition = pos;
- for (var i = 1; i + currentPosition < length; i++) {
- var nextChar = input.charAt(i + currentPosition);
- switch (nextChar) {
- case '\\':
- i++;
- continue;
- case '\r':
- case '\n':
- break;
- case startChar:
- var str = input.substr(currentPosition, i + 1);
- if (!loc && loc !== 0) {
- skipWhitespace(i + 1);
- return str;
- }
- return [startChar, str];
- }
- }
- return null;
- };
-
- parserInput.$parseUntil = function (tok) {
- var quote = '';
- var returnVal = null;
- var inComment = false;
- var blockDepth = 0;
- var blockStack = [];
- var parseGroups = [];
- var length = input.length;
- var startPos = parserInput.i;
- var lastPos = parserInput.i;
- var i = parserInput.i;
- var loop = true;
- var testChar;
- if (typeof tok === 'string') {
- testChar = function (char) { return char === tok; };
- }
- else {
- testChar = function (char) { return tok.test(char); };
- }
- do {
- var nextChar = input.charAt(i);
- if (blockDepth === 0 && testChar(nextChar)) {
- returnVal = input.substr(lastPos, i - lastPos);
- if (returnVal) {
- parseGroups.push(returnVal);
- }
- else {
- parseGroups.push(' ');
- }
- returnVal = parseGroups;
- skipWhitespace(i - startPos);
- loop = false;
- }
- else {
- if (inComment) {
- if (nextChar === '*' &&
- input.charAt(i + 1) === '/') {
- i++;
- blockDepth--;
- inComment = false;
- }
- i++;
- continue;
- }
- switch (nextChar) {
- case '\\':
- i++;
- nextChar = input.charAt(i);
- parseGroups.push(input.substr(lastPos, i - lastPos + 1));
- lastPos = i + 1;
- break;
- case '/':
- if (input.charAt(i + 1) === '*') {
- i++;
- inComment = true;
- blockDepth++;
- }
- break;
- case '\'':
- case '"':
- quote = parserInput.$quoted(i);
- if (quote) {
- parseGroups.push(input.substr(lastPos, i - lastPos), quote);
- i += quote[1].length - 1;
- lastPos = i + 1;
- }
- else {
- skipWhitespace(i - startPos);
- returnVal = nextChar;
- loop = false;
- }
- break;
- case '{':
- blockStack.push('}');
- blockDepth++;
- break;
- case '(':
- blockStack.push(')');
- blockDepth++;
- break;
- case '[':
- blockStack.push(']');
- blockDepth++;
- break;
- case '}':
- case ')':
- case ']':
- var expected = blockStack.pop();
- if (nextChar === expected) {
- blockDepth--;
- }
- else {
-
- skipWhitespace(i - startPos);
- returnVal = expected;
- loop = false;
- }
- }
- i++;
- if (i > length) {
- loop = false;
- }
- }
- } while (loop);
- return returnVal ? returnVal : null;
- };
- parserInput.autoCommentAbsorb = true;
- parserInput.commentStore = [];
- parserInput.finished = false;
-
-
- parserInput.peek = function (tok) {
- if (typeof tok === 'string') {
-
- for (var i = 0; i < tok.length; i++) {
- if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
- return false;
- }
- }
- return true;
- }
- else {
- return tok.test(current);
- }
- };
-
-
- parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
- parserInput.currentChar = function () { return input.charAt(parserInput.i); };
- parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
- parserInput.getInput = function () { return input; };
- parserInput.peekNotNumeric = function () {
- var c = input.charCodeAt(parserInput.i);
-
- return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
- };
- parserInput.start = function (str, chunkInput, failFunction) {
- input = str;
- parserInput.i = j = currentPos = furthest = 0;
-
-
-
-
-
-
-
-
-
-
- if (chunkInput) {
- chunks = chunker(str, failFunction);
- }
- else {
- chunks = [str];
- }
- current = chunks[0];
- skipWhitespace(0);
- };
- parserInput.end = function () {
- var message;
- var isFinished = parserInput.i >= input.length;
- if (parserInput.i < furthest) {
- message = furthestPossibleErrorMessage;
- parserInput.i = furthest;
- }
- return {
- isFinished: isFinished,
- furthest: parserInput.i,
- furthestPossibleErrorMessage: message,
- furthestReachedEnd: parserInput.i >= input.length - 1,
- furthestChar: input[parserInput.i]
- };
- };
- return parserInput;
- });
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var Parser = function Parser(context, imports, fileInfo) {
- var parsers;
- var parserInput = getParserInput();
- function error(msg, type) {
- throw new LessError({
- index: parserInput.i,
- filename: fileInfo.filename,
- type: type || 'Syntax',
- message: msg
- }, imports);
- }
- function expect(arg, msg) {
-
- var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
- if (result) {
- return result;
- }
- error(msg || (typeof arg === 'string'
- ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
- : 'unexpected token'));
- }
-
- function expectChar(arg, msg) {
- if (parserInput.$char(arg)) {
- return arg;
- }
- error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
- }
- function getDebugInfo(index) {
- var filename = fileInfo.filename;
- return {
- lineNumber: getLocation(index, parserInput.getInput()).line + 1,
- fileName: filename
- };
- }
-
- function parseNode(str, parseList, currentIndex, fileInfo, callback) {
- var result;
- var returnNodes = [];
- var parser = parserInput;
- try {
- parser.start(str, false, function fail(msg, index) {
- callback({
- message: msg,
- index: index + currentIndex
- });
- });
- for (var x = 0, p = void 0, i = void 0; (p = parseList[x]); x++) {
- i = parser.i;
- result = parsers[p]();
- if (result) {
- try {
- result._index = i + currentIndex;
- result._fileInfo = fileInfo;
- }
- catch (e) { }
- returnNodes.push(result);
- }
- else {
- returnNodes.push(null);
- }
- }
- var endInfo = parser.end();
- if (endInfo.isFinished) {
- callback(null, returnNodes);
- }
- else {
- callback(true, null);
- }
- }
- catch (e) {
- throw new LessError({
- index: e.index + currentIndex,
- message: e.message
- }, imports, fileInfo.filename);
- }
- }
-
-
-
- return {
- parserInput: parserInput,
- imports: imports,
- fileInfo: fileInfo,
- parseNode: parseNode,
-
-
-
-
-
-
- parse: function (str, callback, additionalData) {
- var root;
- var error = null;
- var globalVars;
- var modifyVars;
- var ignored;
- var preText = '';
- globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + "\n" : '';
- modifyVars = (additionalData && additionalData.modifyVars) ? "\n" + Parser.serializeVars(additionalData.modifyVars) : '';
- if (context.pluginManager) {
- var preProcessors = context.pluginManager.getPreProcessors();
- for (var i = 0; i < preProcessors.length; i++) {
- str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo });
- }
- }
- if (globalVars || (additionalData && additionalData.banner)) {
- preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
- ignored = imports.contentsIgnoredChars;
- ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
- ignored[fileInfo.filename] += preText.length;
- }
- str = str.replace(/\r\n?/g, '\n');
-
- str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
- imports.contents[fileInfo.filename] = str;
-
-
-
-
- try {
- parserInput.start(str, context.chunkInput, function fail(msg, index) {
- throw new LessError({
- index: index,
- type: 'Parse',
- message: msg,
- filename: fileInfo.filename
- }, imports);
- });
- tree.Node.prototype.parse = this;
- root = new tree.Ruleset(null, this.parsers.primary());
- tree.Node.prototype.rootNode = root;
- root.root = true;
- root.firstRoot = true;
- root.functionRegistry = functionRegistry.inherit();
- }
- catch (e) {
- return callback(new LessError(e, imports, fileInfo.filename));
- }
-
-
-
-
-
-
-
-
- var endInfo = parserInput.end();
- if (!endInfo.isFinished) {
- var message = endInfo.furthestPossibleErrorMessage;
- if (!message) {
- message = 'Unrecognised input';
- if (endInfo.furthestChar === '}') {
- message += '. Possibly missing opening \'{\'';
- }
- else if (endInfo.furthestChar === ')') {
- message += '. Possibly missing opening \'(\'';
- }
- else if (endInfo.furthestReachedEnd) {
- message += '. Possibly missing something';
- }
- }
- error = new LessError({
- type: 'Parse',
- message: message,
- index: endInfo.furthest,
- filename: fileInfo.filename
- }, imports);
- }
- var finish = function (e) {
- e = error || e || imports.error;
- if (e) {
- if (!(e instanceof LessError)) {
- e = new LessError(e, imports, fileInfo.filename);
- }
- return callback(e);
- }
- else {
- return callback(null, root);
- }
- };
- if (context.processImports !== false) {
- new visitors.ImportVisitor(imports, finish)
- .run(root);
- }
- else {
- return finish();
- }
- },
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- parsers: parsers = {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- primary: function () {
- var mixin = this.mixin;
- var root = [];
- var node;
- while (true) {
- while (true) {
- node = this.comment();
- if (!node) {
- break;
- }
- root.push(node);
- }
-
- if (parserInput.finished) {
- break;
- }
- if (parserInput.peek('}')) {
- break;
- }
- node = this.extendRule();
- if (node) {
- root = root.concat(node);
- continue;
- }
- node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
- this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
- if (node) {
- root.push(node);
- }
- else {
- var foundSemiColon = false;
- while (parserInput.$char(';')) {
- foundSemiColon = true;
- }
- if (!foundSemiColon) {
- break;
- }
- }
- }
- return root;
- },
-
-
- comment: function () {
- if (parserInput.commentStore.length) {
- var comment = parserInput.commentStore.shift();
- return new (tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
- }
- },
-
-
-
- entities: {
- mixinLookup: function () {
- return parsers.mixin.call(true, true);
- },
-
-
-
-
-
- quoted: function (forceEscaped) {
- var str;
- var index = parserInput.i;
- var isEscaped = false;
- parserInput.save();
- if (parserInput.$char('~')) {
- isEscaped = true;
- }
- else if (forceEscaped) {
- parserInput.restore();
- return;
- }
- str = parserInput.$quoted();
- if (!str) {
- parserInput.restore();
- return;
- }
- parserInput.forget();
- return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
- },
-
-
-
-
-
- keyword: function () {
- var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
- if (k) {
- return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
- }
- },
-
-
-
-
-
-
-
- call: function () {
- var name;
- var args;
- var func;
- var index = parserInput.i;
-
- if (parserInput.peek(/^url\(/i)) {
- return;
- }
- parserInput.save();
- name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
- if (!name) {
- parserInput.forget();
- return;
- }
- name = name[1];
- func = this.customFuncCall(name);
- if (func) {
- args = func.parse();
- if (args && func.stop) {
- parserInput.forget();
- return args;
- }
- }
- args = this.arguments(args);
- if (!parserInput.$char(')')) {
- parserInput.restore('Could not parse call arguments or missing \')\'');
- return;
- }
- parserInput.forget();
- return new (tree.Call)(name, args, index, fileInfo);
- },
-
-
-
-
-
-
-
-
- customFuncCall: function (name) {
-
- return {
- alpha: f(parsers.ieAlpha, true),
- boolean: f(condition),
- 'if': f(condition)
- }[name.toLowerCase()];
- function f(parse, stop) {
- return {
- parse: parse,
- stop: stop
-
- };
- }
- function condition() {
- return [expect(parsers.condition, 'expected condition')];
- }
- },
- arguments: function (prevArgs) {
- var argsComma = prevArgs || [];
- var argsSemiColon = [];
- var isSemiColonSeparated;
- var value;
- parserInput.save();
- while (true) {
- if (prevArgs) {
- prevArgs = false;
- }
- else {
- value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
- if (!value) {
- break;
- }
- if (value.value && value.value.length == 1) {
- value = value.value[0];
- }
- argsComma.push(value);
- }
- if (parserInput.$char(',')) {
- continue;
- }
- if (parserInput.$char(';') || isSemiColonSeparated) {
- isSemiColonSeparated = true;
- value = (argsComma.length < 1) ? argsComma[0]
- : new tree.Value(argsComma);
- argsSemiColon.push(value);
- argsComma = [];
- }
- }
- parserInput.forget();
- return isSemiColonSeparated ? argsSemiColon : argsComma;
- },
- literal: function () {
- return this.dimension() ||
- this.color() ||
- this.quoted() ||
- this.unicodeDescriptor();
- },
-
-
-
-
-
- assignment: function () {
- var key;
- var value;
- parserInput.save();
- key = parserInput.$re(/^\w+(?=\s?=)/i);
- if (!key) {
- parserInput.restore();
- return;
- }
- if (!parserInput.$char('=')) {
- parserInput.restore();
- return;
- }
- value = parsers.entity();
- if (value) {
- parserInput.forget();
- return new (tree.Assignment)(key, value);
- }
- else {
- parserInput.restore();
- }
- },
-
-
-
-
-
-
-
- url: function () {
- var value;
- var index = parserInput.i;
- parserInput.autoCommentAbsorb = false;
- if (!parserInput.$str('url(')) {
- parserInput.autoCommentAbsorb = true;
- return;
- }
- value = this.quoted() || this.variable() || this.property() ||
- parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
- parserInput.autoCommentAbsorb = true;
- expectChar(')');
- return new (tree.URL)((value.value != null ||
- value instanceof tree.Variable ||
- value instanceof tree.Property) ?
- value : new (tree.Anonymous)(value, index), index, fileInfo);
- },
-
-
-
-
-
-
-
-
- variable: function () {
- var ch;
- var name;
- var index = parserInput.i;
- parserInput.save();
- if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
- ch = parserInput.currentChar();
- if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
-
- var result = parsers.variableCall(name);
- if (result) {
- parserInput.forget();
- return result;
- }
- }
- parserInput.forget();
- return new (tree.Variable)(name, index, fileInfo);
- }
- parserInput.restore();
- },
-
- variableCurly: function () {
- var curly;
- var index = parserInput.i;
- if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
- return new (tree.Variable)("@" + curly[1], index, fileInfo);
- }
- },
-
-
-
-
-
- property: function () {
- var name;
- var index = parserInput.i;
- if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
- return new (tree.Property)(name, index, fileInfo);
- }
- },
-
- propertyCurly: function () {
- var curly;
- var index = parserInput.i;
- if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
- return new (tree.Property)("$" + curly[1], index, fileInfo);
- }
- },
-
-
-
-
-
-
-
- color: function () {
- var rgb;
- parserInput.save();
- if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
- if (!rgb[2]) {
- parserInput.forget();
- return new (tree.Color)(rgb[1], undefined, rgb[0]);
- }
- }
- parserInput.restore();
- },
- colorKeyword: function () {
- parserInput.save();
- var autoCommentAbsorb = parserInput.autoCommentAbsorb;
- parserInput.autoCommentAbsorb = false;
- var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
- parserInput.autoCommentAbsorb = autoCommentAbsorb;
- if (!k) {
- parserInput.forget();
- return;
- }
- parserInput.restore();
- var color = tree.Color.fromKeyword(k);
- if (color) {
- parserInput.$str(k);
- return color;
- }
- },
-
-
-
-
-
- dimension: function () {
- if (parserInput.peekNotNumeric()) {
- return;
- }
- var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
- if (value) {
- return new (tree.Dimension)(value[1], value[2]);
- }
- },
-
-
-
-
-
- unicodeDescriptor: function () {
- var ud;
- ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
- if (ud) {
- return new (tree.UnicodeDescriptor)(ud[0]);
- }
- },
-
-
-
-
-
- javascript: function () {
- var js;
- var index = parserInput.i;
- parserInput.save();
- var escape = parserInput.$char('~');
- var jsQuote = parserInput.$char('`');
- if (!jsQuote) {
- parserInput.restore();
- return;
- }
- js = parserInput.$re(/^[^`]*`/);
- if (js) {
- parserInput.forget();
- return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
- }
- parserInput.restore('invalid javascript definition');
- }
- },
-
-
-
-
-
- variable: function () {
- var name;
- if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
- return name[1];
- }
- },
-
-
-
-
-
-
-
-
- variableCall: function (parsedName) {
- var lookups;
- var i = parserInput.i;
- var inValue = !!parsedName;
- var name = parsedName;
- parserInput.save();
- if (name || (parserInput.currentChar() === '@'
- && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
- lookups = this.mixin.ruleLookups();
- if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
- parserInput.restore('Missing \'[...]\' lookup in variable call');
- return;
- }
- if (!inValue) {
- name = name[1];
- }
- var call = new tree.VariableCall(name, i, fileInfo);
- if (!inValue && parsers.end()) {
- parserInput.forget();
- return call;
- }
- else {
- parserInput.forget();
- return new tree.NamespaceValue(call, lookups, i, fileInfo);
- }
- }
- parserInput.restore();
- },
-
-
-
- extend: function (isRule) {
- var elements;
- var e;
- var index = parserInput.i;
- var option;
- var extendList;
- var extend;
- if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
- return;
- }
- do {
- option = null;
- elements = null;
- while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
- e = this.element();
- if (!e) {
- break;
- }
- if (elements) {
- elements.push(e);
- }
- else {
- elements = [e];
- }
- }
- option = option && option[1];
- if (!elements) {
- error('Missing target selector for :extend().');
- }
- extend = new (tree.Extend)(new (tree.Selector)(elements), option, index, fileInfo);
- if (extendList) {
- extendList.push(extend);
- }
- else {
- extendList = [extend];
- }
- } while (parserInput.$char(','));
- expect(/^\)/);
- if (isRule) {
- expect(/^;/);
- }
- return extendList;
- },
-
-
-
- extendRule: function () {
- return this.extend(true);
- },
-
-
-
- mixin: {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- call: function (inValue, getLookup) {
- var s = parserInput.currentChar();
- var important = false;
- var lookups;
- var index = parserInput.i;
- var elements;
- var args;
- var hasParens;
- if (s !== '.' && s !== '#') {
- return;
- }
- parserInput.save();
- elements = this.elements();
- if (elements) {
- if (parserInput.$char('(')) {
- args = this.args(true).args;
- expectChar(')');
- hasParens = true;
- }
- if (getLookup !== false) {
- lookups = this.ruleLookups();
- }
- if (getLookup === true && !lookups) {
- parserInput.restore();
- return;
- }
- if (inValue && !lookups && !hasParens) {
-
- parserInput.restore();
- return;
- }
- if (!inValue && parsers.important()) {
- important = true;
- }
- if (inValue || parsers.end()) {
- parserInput.forget();
- var mixin = new (tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important);
- if (lookups) {
- return new tree.NamespaceValue(mixin, lookups);
- }
- else {
- return mixin;
- }
- }
- }
- parserInput.restore();
- },
-
- elements: function () {
- var elements;
- var e;
- var c;
- var elem;
- var elemIndex;
- var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
- while (true) {
- elemIndex = parserInput.i;
- e = parserInput.$re(re);
- if (!e) {
- break;
- }
- elem = new (tree.Element)(c, e, false, elemIndex, fileInfo);
- if (elements) {
- elements.push(elem);
- }
- else {
- elements = [elem];
- }
- c = parserInput.$char('>');
- }
- return elements;
- },
- args: function (isCall) {
- var entities = parsers.entities;
- var returner = { args: null, variadic: false };
- var expressions = [];
- var argsSemiColon = [];
- var argsComma = [];
- var isSemiColonSeparated;
- var expressionContainsNamed;
- var name;
- var nameLoop;
- var value;
- var arg;
- var expand;
- var hasSep = true;
- parserInput.save();
- while (true) {
- if (isCall) {
- arg = parsers.detachedRuleset() || parsers.expression();
- }
- else {
- parserInput.commentStore.length = 0;
- if (parserInput.$str('...')) {
- returner.variadic = true;
- if (parserInput.$char(';') && !isSemiColonSeparated) {
- isSemiColonSeparated = true;
- }
- (isSemiColonSeparated ? argsSemiColon : argsComma)
- .push({ variadic: true });
- break;
- }
- arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
- }
- if (!arg || !hasSep) {
- break;
- }
- nameLoop = null;
- if (arg.throwAwayComments) {
- arg.throwAwayComments();
- }
- value = arg;
- var val = null;
- if (isCall) {
-
- if (arg.value && arg.value.length == 1) {
- val = arg.value[0];
- }
- }
- else {
- val = arg;
- }
- if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
- if (parserInput.$char(':')) {
- if (expressions.length > 0) {
- if (isSemiColonSeparated) {
- error('Cannot mix ; and , as delimiter types');
- }
- expressionContainsNamed = true;
- }
- value = parsers.detachedRuleset() || parsers.expression();
- if (!value) {
- if (isCall) {
- error('could not understand value for named argument');
- }
- else {
- parserInput.restore();
- returner.args = [];
- return returner;
- }
- }
- nameLoop = (name = val.name);
- }
- else if (parserInput.$str('...')) {
- if (!isCall) {
- returner.variadic = true;
- if (parserInput.$char(';') && !isSemiColonSeparated) {
- isSemiColonSeparated = true;
- }
- (isSemiColonSeparated ? argsSemiColon : argsComma)
- .push({ name: arg.name, variadic: true });
- break;
- }
- else {
- expand = true;
- }
- }
- else if (!isCall) {
- name = nameLoop = val.name;
- value = null;
- }
- }
- if (value) {
- expressions.push(value);
- }
- argsComma.push({ name: nameLoop, value: value, expand: expand });
- if (parserInput.$char(',')) {
- hasSep = true;
- continue;
- }
- hasSep = parserInput.$char(';') === ';';
- if (hasSep || isSemiColonSeparated) {
- if (expressionContainsNamed) {
- error('Cannot mix ; and , as delimiter types');
- }
- isSemiColonSeparated = true;
- if (expressions.length > 1) {
- value = new (tree.Value)(expressions);
- }
- argsSemiColon.push({ name: name, value: value, expand: expand });
- name = null;
- expressions = [];
- expressionContainsNamed = false;
- }
- }
- parserInput.forget();
- returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
- return returner;
- },
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- definition: function () {
- var name;
- var params = [];
- var match;
- var ruleset;
- var cond;
- var variadic = false;
- if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
- parserInput.peek(/^[^{]*\}/)) {
- return;
- }
- parserInput.save();
- match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
- if (match) {
- name = match[1];
- var argInfo = this.args(false);
- params = argInfo.args;
- variadic = argInfo.variadic;
-
-
-
-
-
- if (!parserInput.$char(')')) {
- parserInput.restore('Missing closing \')\'');
- return;
- }
- parserInput.commentStore.length = 0;
- if (parserInput.$str('when')) {
- cond = expect(parsers.conditions, 'expected condition');
- }
- ruleset = parsers.block();
- if (ruleset) {
- parserInput.forget();
- return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
- }
- else {
- parserInput.restore();
- }
- }
- else {
- parserInput.restore();
- }
- },
- ruleLookups: function () {
- var rule;
- var lookups = [];
- if (parserInput.currentChar() !== '[') {
- return;
- }
- while (true) {
- parserInput.save();
- rule = this.lookupValue();
- if (!rule && rule !== '') {
- parserInput.restore();
- break;
- }
- lookups.push(rule);
- parserInput.forget();
- }
- if (lookups.length > 0) {
- return lookups;
- }
- },
- lookupValue: function () {
- parserInput.save();
- if (!parserInput.$char('[')) {
- parserInput.restore();
- return;
- }
- var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
- if (!parserInput.$char(']')) {
- parserInput.restore();
- return;
- }
- if (name || name === '') {
- parserInput.forget();
- return name;
- }
- parserInput.restore();
- }
- },
-
-
-
-
- entity: function () {
- var entities = this.entities;
- return this.comment() || entities.literal() || entities.variable() || entities.url() ||
- entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
- entities.javascript();
- },
-
-
-
-
-
- end: function () {
- return parserInput.$char(';') || parserInput.peek('}');
- },
-
-
-
-
-
- ieAlpha: function () {
- var value;
-
- if (!parserInput.$re(/^opacity=/i)) {
- return;
- }
- value = parserInput.$re(/^\d+/);
- if (!value) {
- value = expect(parsers.entities.variable, 'Could not parse alpha');
- value = "@{" + value.name.slice(1) + "}";
- }
- expectChar(')');
- return new tree.Quoted('', "alpha(opacity=" + value + ")");
- },
-
-
-
-
-
-
-
-
-
-
-
-
- element: function () {
- var e;
- var c;
- var v;
- var index = parserInput.i;
- c = this.combinator();
- e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
- parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
- parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
- parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
- this.entities.variableCurly();
- if (!e) {
- parserInput.save();
- if (parserInput.$char('(')) {
- if ((v = this.selector(false)) && parserInput.$char(')')) {
- e = new (tree.Paren)(v);
- parserInput.forget();
- }
- else {
- parserInput.restore('Missing closing \')\'');
- }
- }
- else {
- parserInput.forget();
- }
- }
- if (e) {
- return new (tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo);
- }
- },
-
-
-
-
-
-
-
-
-
- combinator: function () {
- var c = parserInput.currentChar();
- if (c === '/') {
- parserInput.save();
- var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
- if (slashedCombinator) {
- parserInput.forget();
- return new (tree.Combinator)(slashedCombinator);
- }
- parserInput.restore();
- }
- if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
- parserInput.i++;
- if (c === '^' && parserInput.currentChar() === '^') {
- c = '^^';
- parserInput.i++;
- }
- while (parserInput.isWhitespace()) {
- parserInput.i++;
- }
- return new (tree.Combinator)(c);
- }
- else if (parserInput.isWhitespace(-1)) {
- return new (tree.Combinator)(' ');
- }
- else {
- return new (tree.Combinator)(null);
- }
- },
-
-
-
-
-
-
-
-
-
- selector: function (isLess) {
- var index = parserInput.i;
- var elements;
- var extendList;
- var c;
- var e;
- var allExtends;
- var when;
- var condition;
- isLess = isLess !== false;
- while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
- if (when) {
- condition = expect(this.conditions, 'expected condition');
- }
- else if (condition) {
- error('CSS guard can only be used at the end of selector');
- }
- else if (extendList) {
- if (allExtends) {
- allExtends = allExtends.concat(extendList);
- }
- else {
- allExtends = extendList;
- }
- }
- else {
- if (allExtends) {
- error('Extend can only be used at the end of selector');
- }
- c = parserInput.currentChar();
- if (elements) {
- elements.push(e);
- }
- else {
- elements = [e];
- }
- e = null;
- }
- if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
- break;
- }
- }
- if (elements) {
- return new (tree.Selector)(elements, allExtends, condition, index, fileInfo);
- }
- if (allExtends) {
- error('Extend must be used to extend a selector, it cannot be used on its own');
- }
- },
- selectors: function () {
- var s;
- var selectors;
- while (true) {
- s = this.selector();
- if (!s) {
- break;
- }
- if (selectors) {
- selectors.push(s);
- }
- else {
- selectors = [s];
- }
- parserInput.commentStore.length = 0;
- if (s.condition && selectors.length > 1) {
- error("Guards are only currently allowed on a single selector.");
- }
- if (!parserInput.$char(',')) {
- break;
- }
- if (s.condition) {
- error("Guards are only currently allowed on a single selector.");
- }
- parserInput.commentStore.length = 0;
- }
- return selectors;
- },
- attribute: function () {
- if (!parserInput.$char('[')) {
- return;
- }
- var entities = this.entities;
- var key;
- var val;
- var op;
- if (!(key = entities.variableCurly())) {
- key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
- }
- op = parserInput.$re(/^[|~*$^]?=/);
- if (op) {
- val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
- }
- expectChar(']');
- return new (tree.Attribute)(key, op, val);
- },
-
-
-
-
- block: function () {
- var content;
- if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
- return content;
- }
- },
- blockRuleset: function () {
- var block = this.block();
- if (block) {
- block = new tree.Ruleset(null, block);
- }
- return block;
- },
- detachedRuleset: function () {
- var argInfo;
- var params;
- var variadic;
- parserInput.save();
- if (parserInput.$re(/^[.#]\(/)) {
-
- argInfo = this.mixin.args(false);
- params = argInfo.args;
- variadic = argInfo.variadic;
- if (!parserInput.$char(')')) {
- parserInput.restore();
- return;
- }
- }
- var blockRuleset = this.blockRuleset();
- if (blockRuleset) {
- parserInput.forget();
- if (params) {
- return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
- }
- return new tree.DetachedRuleset(blockRuleset);
- }
- parserInput.restore();
- },
-
-
-
- ruleset: function () {
- var selectors;
- var rules;
- var debugInfo;
- parserInput.save();
- if (context.dumpLineNumbers) {
- debugInfo = getDebugInfo(parserInput.i);
- }
- selectors = this.selectors();
- if (selectors && (rules = this.block())) {
- parserInput.forget();
- var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
- if (context.dumpLineNumbers) {
- ruleset.debugInfo = debugInfo;
- }
- return ruleset;
- }
- else {
- parserInput.restore();
- }
- },
- declaration: function () {
- var name;
- var value;
- var index = parserInput.i;
- var hasDR;
- var c = parserInput.currentChar();
- var important;
- var merge;
- var isVariable;
- if (c === '.' || c === '#' || c === '&' || c === ':') {
- return;
- }
- parserInput.save();
- name = this.variable() || this.ruleProperty();
- if (name) {
- isVariable = typeof name === 'string';
- if (isVariable) {
- value = this.detachedRuleset();
- if (value) {
- hasDR = true;
- }
- }
- parserInput.commentStore.length = 0;
- if (!value) {
-
-
-
- merge = !isVariable && name.length > 1 && name.pop().value;
-
- if (name[0].value && name[0].value.slice(0, 2) === '--') {
- value = this.permissiveValue();
- }
-
-
- else {
- value = this.anonymousValue();
- }
- if (value) {
- parserInput.forget();
-
- return new (tree.Declaration)(name, value, false, merge, index, fileInfo);
- }
- if (!value) {
- value = this.value();
- }
- if (value) {
- important = this.important();
- }
- else if (isVariable) {
-
- value = this.permissiveValue();
- }
- }
- if (value && (this.end() || hasDR)) {
- parserInput.forget();
- return new (tree.Declaration)(name, value, important, merge, index, fileInfo);
- }
- else {
- parserInput.restore();
- }
- }
- else {
- parserInput.restore();
- }
- },
- anonymousValue: function () {
- var index = parserInput.i;
- var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
- if (match) {
- return new (tree.Anonymous)(match[1], index);
- }
- },
-
- permissiveValue: function (untilTokens) {
- var i;
- var e;
- var done;
- var value;
- var tok = untilTokens || ';';
- var index = parserInput.i;
- var result = [];
- function testCurrentChar() {
- var char = parserInput.currentChar();
- if (typeof tok === 'string') {
- return char === tok;
- }
- else {
- return tok.test(char);
- }
- }
- if (testCurrentChar()) {
- return;
- }
- value = [];
- do {
- e = this.comment();
- if (e) {
- value.push(e);
- continue;
- }
- e = this.entity();
- if (e) {
- value.push(e);
- }
- } while (e);
- done = testCurrentChar();
- if (value.length > 0) {
- value = new (tree.Expression)(value);
- if (done) {
- return value;
- }
- else {
- result.push(value);
- }
-
- if (parserInput.prevChar() === ' ') {
- result.push(new tree.Anonymous(' ', index));
- }
- }
- parserInput.save();
- value = parserInput.$parseUntil(tok);
- if (value) {
- if (typeof value === 'string') {
- error("Expected '" + value + "'", 'Parse');
- }
- if (value.length === 1 && value[0] === ' ') {
- parserInput.forget();
- return new tree.Anonymous('', index);
- }
- var item = void 0;
- for (i = 0; i < value.length; i++) {
- item = value[i];
- if (Array.isArray(item)) {
-
- result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
- }
- else {
- if (i === value.length - 1) {
- item = item.trim();
- }
-
- var quote = new tree.Quoted('\'', item, true, index, fileInfo);
- quote.variableRegex = /@([\w-]+)/g;
- quote.propRegex = /\$([\w-]+)/g;
- result.push(quote);
- }
- }
- parserInput.forget();
- return new tree.Expression(result, true);
- }
- parserInput.restore();
- },
-
-
-
-
-
-
-
-
-
-
- 'import': function () {
- var path;
- var features;
- var index = parserInput.i;
- var dir = parserInput.$re(/^@import?\s+/);
- if (dir) {
- var options = (dir ? this.importOptions() : null) || {};
- if ((path = this.entities.quoted() || this.entities.url())) {
- features = this.mediaFeatures();
- if (!parserInput.$char(';')) {
- parserInput.i = index;
- error('missing semi-colon or unrecognised media features on import');
- }
- features = features && new (tree.Value)(features);
- return new (tree.Import)(path, features, options, index, fileInfo);
- }
- else {
- parserInput.i = index;
- error('malformed import statement');
- }
- }
- },
- importOptions: function () {
- var o;
- var options = {};
- var optionName;
- var value;
-
- if (!parserInput.$char('(')) {
- return null;
- }
- do {
- o = this.importOption();
- if (o) {
- optionName = o;
- value = true;
- switch (optionName) {
- case 'css':
- optionName = 'less';
- value = false;
- break;
- case 'once':
- optionName = 'multiple';
- value = false;
- break;
- }
- options[optionName] = value;
- if (!parserInput.$char(',')) {
- break;
- }
- }
- } while (o);
- expectChar(')');
- return options;
- },
- importOption: function () {
- var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
- if (opt) {
- return opt[1];
- }
- },
- mediaFeature: function () {
- var entities = this.entities;
- var nodes = [];
- var e;
- var p;
- parserInput.save();
- do {
- e = entities.keyword() || entities.variable() || entities.mixinLookup();
- if (e) {
- nodes.push(e);
- }
- else if (parserInput.$char('(')) {
- p = this.property();
- e = this.value();
- if (parserInput.$char(')')) {
- if (p && e) {
- nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
- }
- else if (e) {
- nodes.push(new (tree.Paren)(e));
- }
- else {
- error('badly formed media feature definition');
- }
- }
- else {
- error('Missing closing \')\'', 'Parse');
- }
- }
- } while (e);
- parserInput.forget();
- if (nodes.length > 0) {
- return new (tree.Expression)(nodes);
- }
- },
- mediaFeatures: function () {
- var entities = this.entities;
- var features = [];
- var e;
- do {
- e = this.mediaFeature();
- if (e) {
- features.push(e);
- if (!parserInput.$char(',')) {
- break;
- }
- }
- else {
- e = entities.variable() || entities.mixinLookup();
- if (e) {
- features.push(e);
- if (!parserInput.$char(',')) {
- break;
- }
- }
- }
- } while (e);
- return features.length > 0 ? features : null;
- },
- media: function () {
- var features;
- var rules;
- var media;
- var debugInfo;
- var index = parserInput.i;
- if (context.dumpLineNumbers) {
- debugInfo = getDebugInfo(index);
- }
- parserInput.save();
- if (parserInput.$str('@media')) {
- features = this.mediaFeatures();
- rules = this.block();
- if (!rules) {
- error('media definitions require block statements after any features');
- }
- parserInput.forget();
- media = new (tree.Media)(rules, features, index, fileInfo);
- if (context.dumpLineNumbers) {
- media.debugInfo = debugInfo;
- }
- return media;
- }
- parserInput.restore();
- },
-
-
-
-
-
- plugin: function () {
- var path;
- var args;
- var options;
- var index = parserInput.i;
- var dir = parserInput.$re(/^@plugin?\s+/);
- if (dir) {
- args = this.pluginArgs();
- if (args) {
- options = {
- pluginArgs: args,
- isPlugin: true
- };
- }
- else {
- options = { isPlugin: true };
- }
- if ((path = this.entities.quoted() || this.entities.url())) {
- if (!parserInput.$char(';')) {
- parserInput.i = index;
- error('missing semi-colon on @plugin');
- }
- return new (tree.Import)(path, null, options, index, fileInfo);
- }
- else {
- parserInput.i = index;
- error('malformed @plugin statement');
- }
- }
- },
- pluginArgs: function () {
-
- parserInput.save();
- if (!parserInput.$char('(')) {
- parserInput.restore();
- return null;
- }
- var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
- if (args[1]) {
- parserInput.forget();
- return args[1].trim();
- }
- else {
- parserInput.restore();
- return null;
- }
- },
-
-
-
-
-
- atrule: function () {
- var index = parserInput.i;
- var name;
- var value;
- var rules;
- var nonVendorSpecificName;
- var hasIdentifier;
- var hasExpression;
- var hasUnknown;
- var hasBlock = true;
- var isRooted = true;
- if (parserInput.currentChar() !== '@') {
- return;
- }
- value = this['import']() || this.plugin() || this.media();
- if (value) {
- return value;
- }
- parserInput.save();
- name = parserInput.$re(/^@[a-z-]+/);
- if (!name) {
- return;
- }
- nonVendorSpecificName = name;
- if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
- nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
- }
- switch (nonVendorSpecificName) {
- case '@charset':
- hasIdentifier = true;
- hasBlock = false;
- break;
- case '@namespace':
- hasExpression = true;
- hasBlock = false;
- break;
- case '@keyframes':
- case '@counter-style':
- hasIdentifier = true;
- break;
- case '@document':
- case '@supports':
- hasUnknown = true;
- isRooted = false;
- break;
- default:
- hasUnknown = true;
- break;
- }
- parserInput.commentStore.length = 0;
- if (hasIdentifier) {
- value = this.entity();
- if (!value) {
- error("expected " + name + " identifier");
- }
- }
- else if (hasExpression) {
- value = this.expression();
- if (!value) {
- error("expected " + name + " expression");
- }
- }
- else if (hasUnknown) {
- value = this.permissiveValue(/^[{;]/);
- hasBlock = (parserInput.currentChar() === '{');
- if (!value) {
- if (!hasBlock && parserInput.currentChar() !== ';') {
- error(name + " rule is missing block or ending semi-colon");
- }
- }
- else if (!value.value) {
- value = null;
- }
- }
- if (hasBlock) {
- rules = this.blockRuleset();
- }
- if (rules || (!hasBlock && value && parserInput.$char(';'))) {
- parserInput.forget();
- return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
- }
- parserInput.restore('at-rule options not recognised');
- },
-
-
-
-
-
-
-
-
- value: function () {
- var e;
- var expressions = [];
- var index = parserInput.i;
- do {
- e = this.expression();
- if (e) {
- expressions.push(e);
- if (!parserInput.$char(',')) {
- break;
- }
- }
- } while (e);
- if (expressions.length > 0) {
- return new (tree.Value)(expressions, index);
- }
- },
- important: function () {
- if (parserInput.currentChar() === '!') {
- return parserInput.$re(/^! *important/);
- }
- },
- sub: function () {
- var a;
- var e;
- parserInput.save();
- if (parserInput.$char('(')) {
- a = this.addition();
- if (a && parserInput.$char(')')) {
- parserInput.forget();
- e = new (tree.Expression)([a]);
- e.parens = true;
- return e;
- }
- parserInput.restore('Expected \')\'');
- return;
- }
- parserInput.restore();
- },
- multiplication: function () {
- var m;
- var a;
- var op;
- var operation;
- var isSpaced;
- m = this.operand();
- if (m) {
- isSpaced = parserInput.isWhitespace(-1);
- while (true) {
- if (parserInput.peek(/^\/[*\/]/)) {
- break;
- }
- parserInput.save();
- op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
- if (!op) {
- parserInput.forget();
- break;
- }
- a = this.operand();
- if (!a) {
- parserInput.restore();
- break;
- }
- parserInput.forget();
- m.parensInOp = true;
- a.parensInOp = true;
- operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
- isSpaced = parserInput.isWhitespace(-1);
- }
- return operation || m;
- }
- },
- addition: function () {
- var m;
- var a;
- var op;
- var operation;
- var isSpaced;
- m = this.multiplication();
- if (m) {
- isSpaced = parserInput.isWhitespace(-1);
- while (true) {
- op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
- if (!op) {
- break;
- }
- a = this.multiplication();
- if (!a) {
- break;
- }
- m.parensInOp = true;
- a.parensInOp = true;
- operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
- isSpaced = parserInput.isWhitespace(-1);
- }
- return operation || m;
- }
- },
- conditions: function () {
- var a;
- var b;
- var index = parserInput.i;
- var condition;
- a = this.condition(true);
- if (a) {
- while (true) {
- if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
- break;
- }
- b = this.condition(true);
- if (!b) {
- break;
- }
- condition = new (tree.Condition)('or', condition || a, b, index);
- }
- return condition || a;
- }
- },
- condition: function (needsParens) {
- var result;
- var logical;
- var next;
- function or() {
- return parserInput.$str('or');
- }
- result = this.conditionAnd(needsParens);
- if (!result) {
- return;
- }
- logical = or();
- if (logical) {
- next = this.condition(needsParens);
- if (next) {
- result = new (tree.Condition)(logical, result, next);
- }
- else {
- return;
- }
- }
- return result;
- },
- conditionAnd: function (needsParens) {
- var result;
- var logical;
- var next;
- var self = this;
- function insideCondition() {
- var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
- if (!cond && !needsParens) {
- return self.atomicCondition(needsParens);
- }
- return cond;
- }
- function and() {
- return parserInput.$str('and');
- }
- result = insideCondition();
- if (!result) {
- return;
- }
- logical = and();
- if (logical) {
- next = this.conditionAnd(needsParens);
- if (next) {
- result = new (tree.Condition)(logical, result, next);
- }
- else {
- return;
- }
- }
- return result;
- },
- negatedCondition: function (needsParens) {
- if (parserInput.$str('not')) {
- var result = this.parenthesisCondition(needsParens);
- if (result) {
- result.negate = !result.negate;
- }
- return result;
- }
- },
- parenthesisCondition: function (needsParens) {
- function tryConditionFollowedByParenthesis(me) {
- var body;
- parserInput.save();
- body = me.condition(needsParens);
- if (!body) {
- parserInput.restore();
- return;
- }
- if (!parserInput.$char(')')) {
- parserInput.restore();
- return;
- }
- parserInput.forget();
- return body;
- }
- var body;
- parserInput.save();
- if (!parserInput.$str('(')) {
- parserInput.restore();
- return;
- }
- body = tryConditionFollowedByParenthesis(this);
- if (body) {
- parserInput.forget();
- return body;
- }
- body = this.atomicCondition(needsParens);
- if (!body) {
- parserInput.restore();
- return;
- }
- if (!parserInput.$char(')')) {
- parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
- return;
- }
- parserInput.forget();
- return body;
- },
- atomicCondition: function (needsParens) {
- var entities = this.entities;
- var index = parserInput.i;
- var a;
- var b;
- var c;
- var op;
- function cond() {
- return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
- }
- cond = cond.bind(this);
- a = cond();
- if (a) {
- if (parserInput.$char('>')) {
- if (parserInput.$char('=')) {
- op = '>=';
- }
- else {
- op = '>';
- }
- }
- else if (parserInput.$char('<')) {
- if (parserInput.$char('=')) {
- op = '<=';
- }
- else {
- op = '<';
- }
- }
- else if (parserInput.$char('=')) {
- if (parserInput.$char('>')) {
- op = '=>';
- }
- else if (parserInput.$char('<')) {
- op = '=<';
- }
- else {
- op = '=';
- }
- }
- if (op) {
- b = cond();
- if (b) {
- c = new (tree.Condition)(op, a, b, index, false);
- }
- else {
- error('expected expression');
- }
- }
- else {
- c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index, false);
- }
- return c;
- }
- },
-
-
-
-
- operand: function () {
- var entities = this.entities;
- var negate;
- if (parserInput.peek(/^-[@\$\(]/)) {
- negate = parserInput.$char('-');
- }
- var o = this.sub() || entities.dimension() ||
- entities.color() || entities.variable() ||
- entities.property() || entities.call() ||
- entities.quoted(true) || entities.colorKeyword() ||
- entities.mixinLookup();
- if (negate) {
- o.parensInOp = true;
- o = new (tree.Negative)(o);
- }
- return o;
- },
-
-
-
-
-
-
-
- expression: function () {
- var entities = [];
- var e;
- var delim;
- var index = parserInput.i;
- do {
- e = this.comment();
- if (e) {
- entities.push(e);
- continue;
- }
- e = this.addition() || this.entity();
- if (e instanceof tree.Comment) {
- e = null;
- }
- if (e) {
- entities.push(e);
-
- if (!parserInput.peek(/^\/[\/*]/)) {
- delim = parserInput.$char('/');
- if (delim) {
- entities.push(new (tree.Anonymous)(delim, index));
- }
- }
- }
- } while (e);
- if (entities.length > 0) {
- return new (tree.Expression)(entities);
- }
- },
- property: function () {
- var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
- if (name) {
- return name[1];
- }
- },
- ruleProperty: function () {
- var name = [];
- var index = [];
- var s;
- var k;
- parserInput.save();
- var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
- if (simpleProperty) {
- name = [new (tree.Keyword)(simpleProperty[1])];
- parserInput.forget();
- return name;
- }
- function match(re) {
- var i = parserInput.i;
- var chunk = parserInput.$re(re);
- if (chunk) {
- index.push(i);
- return name.push(chunk[1]);
- }
- }
- match(/^(\*?)/);
- while (true) {
- if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
- break;
- }
- }
- if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
- parserInput.forget();
-
-
- if (name[0] === '') {
- name.shift();
- index.shift();
- }
- for (k = 0; k < name.length; k++) {
- s = name[k];
- name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
- new (tree.Keyword)(s) :
- (s.charAt(0) === '@' ?
- new (tree.Variable)("@" + s.slice(2, -1), index[k], fileInfo) :
- new (tree.Property)("$" + s.slice(2, -1), index[k], fileInfo));
- }
- return name;
- }
- parserInput.restore();
- }
- }
- };
- };
- Parser.serializeVars = function (vars) {
- var s = '';
- for (var name_1 in vars) {
- if (Object.hasOwnProperty.call(vars, name_1)) {
- var value = vars[name_1];
- s += ((name_1[0] === '@') ? '' : '@') + name_1 + ": " + value + ((String(value).slice(-1) === ';') ? '' : ';');
- }
- }
- return s;
- };
- function boolean(condition) {
- return condition ? Keyword.True : Keyword.False;
- }
-
- function If(context, condition, trueValue, falseValue) {
- return condition.eval(context) ? trueValue.eval(context)
- : (falseValue ? falseValue.eval(context) : new Anonymous);
- }
- If.evalArgs = false;
- var boolean$1 = { boolean: boolean, 'if': If };
- var colorFunctions;
- function clamp$1(val) {
- return Math.min(1, Math.max(0, val));
- }
- function hsla(origColor, hsl) {
- var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
- if (color) {
- if (origColor.value &&
- /^(rgb|hsl)/.test(origColor.value)) {
- color.value = origColor.value;
- }
- else {
- color.value = 'rgb';
- }
- return color;
- }
- }
- function toHSL(color) {
- if (color.toHSL) {
- return color.toHSL();
- }
- else {
- throw new Error('Argument cannot be evaluated to a color');
- }
- }
- function toHSV(color) {
- if (color.toHSV) {
- return color.toHSV();
- }
- else {
- throw new Error('Argument cannot be evaluated to a color');
- }
- }
- function number(n) {
- if (n instanceof Dimension) {
- return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
- }
- else if (typeof n === 'number') {
- return n;
- }
- else {
- throw {
- type: 'Argument',
- message: 'color functions take numbers as parameters'
- };
- }
- }
- function scaled(n, size) {
- if (n instanceof Dimension && n.unit.is('%')) {
- return parseFloat(n.value * size / 100);
- }
- else {
- return number(n);
- }
- }
- colorFunctions = {
- rgb: function (r, g, b) {
- var color = colorFunctions.rgba(r, g, b, 1.0);
- if (color) {
- color.value = 'rgb';
- return color;
- }
- },
- rgba: function (r, g, b, a) {
- try {
- if (r instanceof Color) {
- if (g) {
- a = number(g);
- }
- else {
- a = r.alpha;
- }
- return new Color(r.rgb, a, 'rgba');
- }
- var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
- a = number(a);
- return new Color(rgb, a, 'rgba');
- }
- catch (e) { }
- },
- hsl: function (h, s, l) {
- var color = colorFunctions.hsla(h, s, l, 1.0);
- if (color) {
- color.value = 'hsl';
- return color;
- }
- },
- hsla: function (h, s, l, a) {
- try {
- if (h instanceof Color) {
- if (s) {
- a = number(s);
- }
- else {
- a = h.alpha;
- }
- return new Color(h.rgb, a, 'hsla');
- }
- var m1_1;
- var m2_1;
- function hue(h) {
- h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
- if (h * 6 < 1) {
- return m1_1 + (m2_1 - m1_1) * h * 6;
- }
- else if (h * 2 < 1) {
- return m2_1;
- }
- else if (h * 3 < 2) {
- return m1_1 + (m2_1 - m1_1) * (2 / 3 - h) * 6;
- }
- else {
- return m1_1;
- }
- }
- h = (number(h) % 360) / 360;
- s = clamp$1(number(s));
- l = clamp$1(number(l));
- a = clamp$1(number(a));
- m2_1 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
- m1_1 = l * 2 - m2_1;
- var rgb = [
- hue(h + 1 / 3) * 255,
- hue(h) * 255,
- hue(h - 1 / 3) * 255
- ];
- a = number(a);
- return new Color(rgb, a, 'hsla');
- }
- catch (e) { }
- },
- hsv: function (h, s, v) {
- return colorFunctions.hsva(h, s, v, 1.0);
- },
- hsva: function (h, s, v, a) {
- h = ((number(h) % 360) / 360) * 360;
- s = number(s);
- v = number(v);
- a = number(a);
- var i;
- var f;
- i = Math.floor((h / 60) % 6);
- f = (h / 60) - i;
- var vs = [v,
- v * (1 - s),
- v * (1 - f * s),
- v * (1 - (1 - f) * s)];
- var perm = [[0, 3, 1],
- [2, 0, 1],
- [1, 0, 3],
- [1, 2, 0],
- [3, 1, 0],
- [0, 1, 2]];
- return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
- },
- hue: function (color) {
- return new Dimension(toHSL(color).h);
- },
- saturation: function (color) {
- return new Dimension(toHSL(color).s * 100, '%');
- },
- lightness: function (color) {
- return new Dimension(toHSL(color).l * 100, '%');
- },
- hsvhue: function (color) {
- return new Dimension(toHSV(color).h);
- },
- hsvsaturation: function (color) {
- return new Dimension(toHSV(color).s * 100, '%');
- },
- hsvvalue: function (color) {
- return new Dimension(toHSV(color).v * 100, '%');
- },
- red: function (color) {
- return new Dimension(color.rgb[0]);
- },
- green: function (color) {
- return new Dimension(color.rgb[1]);
- },
- blue: function (color) {
- return new Dimension(color.rgb[2]);
- },
- alpha: function (color) {
- return new Dimension(toHSL(color).a);
- },
- luma: function (color) {
- return new Dimension(color.luma() * color.alpha * 100, '%');
- },
- luminance: function (color) {
- var luminance = (0.2126 * color.rgb[0] / 255) +
- (0.7152 * color.rgb[1] / 255) +
- (0.0722 * color.rgb[2] / 255);
- return new Dimension(luminance * color.alpha * 100, '%');
- },
- saturate: function (color, amount, method) {
-
-
- if (!color.rgb) {
- return null;
- }
- var hsl = toHSL(color);
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.s += hsl.s * amount.value / 100;
- }
- else {
- hsl.s += amount.value / 100;
- }
- hsl.s = clamp$1(hsl.s);
- return hsla(color, hsl);
- },
- desaturate: function (color, amount, method) {
- var hsl = toHSL(color);
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.s -= hsl.s * amount.value / 100;
- }
- else {
- hsl.s -= amount.value / 100;
- }
- hsl.s = clamp$1(hsl.s);
- return hsla(color, hsl);
- },
- lighten: function (color, amount, method) {
- var hsl = toHSL(color);
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.l += hsl.l * amount.value / 100;
- }
- else {
- hsl.l += amount.value / 100;
- }
- hsl.l = clamp$1(hsl.l);
- return hsla(color, hsl);
- },
- darken: function (color, amount, method) {
- var hsl = toHSL(color);
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.l -= hsl.l * amount.value / 100;
- }
- else {
- hsl.l -= amount.value / 100;
- }
- hsl.l = clamp$1(hsl.l);
- return hsla(color, hsl);
- },
- fadein: function (color, amount, method) {
- var hsl = toHSL(color);
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.a += hsl.a * amount.value / 100;
- }
- else {
- hsl.a += amount.value / 100;
- }
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- fadeout: function (color, amount, method) {
- var hsl = toHSL(color);
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.a -= hsl.a * amount.value / 100;
- }
- else {
- hsl.a -= amount.value / 100;
- }
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- fade: function (color, amount) {
- var hsl = toHSL(color);
- hsl.a = amount.value / 100;
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- spin: function (color, amount) {
- var hsl = toHSL(color);
- var hue = (hsl.h + amount.value) % 360;
- hsl.h = hue < 0 ? 360 + hue : hue;
- return hsla(color, hsl);
- },
-
-
-
-
- mix: function (color1, color2, weight) {
- if (!weight) {
- weight = new Dimension(50);
- }
- var p = weight.value / 100.0;
- var w = p * 2 - 1;
- var a = toHSL(color1).a - toHSL(color2).a;
- var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
- var w2 = 1 - w1;
- var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
- color1.rgb[1] * w1 + color2.rgb[1] * w2,
- color1.rgb[2] * w1 + color2.rgb[2] * w2];
- var alpha = color1.alpha * p + color2.alpha * (1 - p);
- return new Color(rgb, alpha);
- },
- greyscale: function (color) {
- return colorFunctions.desaturate(color, new Dimension(100));
- },
- contrast: function (color, dark, light, threshold) {
-
-
- if (!color.rgb) {
- return null;
- }
- if (typeof light === 'undefined') {
- light = colorFunctions.rgba(255, 255, 255, 1.0);
- }
- if (typeof dark === 'undefined') {
- dark = colorFunctions.rgba(0, 0, 0, 1.0);
- }
-
- if (dark.luma() > light.luma()) {
- var t = light;
- light = dark;
- dark = t;
- }
- if (typeof threshold === 'undefined') {
- threshold = 0.43;
- }
- else {
- threshold = number(threshold);
- }
- if (color.luma() < threshold) {
- return light;
- }
- else {
- return dark;
- }
- },
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- argb: function (color) {
- return new Anonymous(color.toARGB());
- },
- color: function (c) {
- if ((c instanceof Quoted) &&
- (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
- var val = c.value.slice(1);
- return new Color(val, undefined, "#" + val);
- }
- if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
- c.value = undefined;
- return c;
- }
- throw {
- type: 'Argument',
- message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
- };
- },
- tint: function (color, amount) {
- return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
- },
- shade: function (color, amount) {
- return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
- }
- };
- var color = colorFunctions;
-
-
- function colorBlend(mode, color1, color2) {
- var ab = color1.alpha;
- var
- cb;
- var as = color2.alpha;
- var
- cs;
- var ar;
- var cr;
- var r = [];
- ar = as + ab * (1 - as);
- for (var i = 0; i < 3; i++) {
- cb = color1.rgb[i] / 255;
- cs = color2.rgb[i] / 255;
- cr = mode(cb, cs);
- if (ar) {
- cr = (as * cs + ab * (cb -
- as * (cb + cs - cr))) / ar;
- }
- r[i] = cr * 255;
- }
- return new Color(r, ar);
- }
- var colorBlendModeFunctions = {
- multiply: function (cb, cs) {
- return cb * cs;
- },
- screen: function (cb, cs) {
- return cb + cs - cb * cs;
- },
- overlay: function (cb, cs) {
- cb *= 2;
- return (cb <= 1) ?
- colorBlendModeFunctions.multiply(cb, cs) :
- colorBlendModeFunctions.screen(cb - 1, cs);
- },
- softlight: function (cb, cs) {
- var d = 1;
- var e = cb;
- if (cs > 0.5) {
- e = 1;
- d = (cb > 0.25) ? Math.sqrt(cb)
- : ((16 * cb - 12) * cb + 4) * cb;
- }
- return cb - (1 - 2 * cs) * e * (d - cb);
- },
- hardlight: function (cb, cs) {
- return colorBlendModeFunctions.overlay(cs, cb);
- },
- difference: function (cb, cs) {
- return Math.abs(cb - cs);
- },
- exclusion: function (cb, cs) {
- return cb + cs - 2 * cb * cs;
- },
-
- average: function (cb, cs) {
- return (cb + cs) / 2;
- },
- negation: function (cb, cs) {
- return 1 - Math.abs(cb + cs - 1);
- }
- };
- for (var f in colorBlendModeFunctions) {
- if (colorBlendModeFunctions.hasOwnProperty(f)) {
- colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
- }
- }
- var dataUri = (function (environment) {
- var fallback = function (functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
- return { 'data-uri': function (mimetypeNode, filePathNode) {
- if (!filePathNode) {
- filePathNode = mimetypeNode;
- mimetypeNode = null;
- }
- var mimetype = mimetypeNode && mimetypeNode.value;
- var filePath = filePathNode.value;
- var currentFileInfo = this.currentFileInfo;
- var currentDirectory = currentFileInfo.rewriteUrls ?
- currentFileInfo.currentDirectory : currentFileInfo.entryPath;
- var fragmentStart = filePath.indexOf('#');
- var fragment = '';
- if (fragmentStart !== -1) {
- fragment = filePath.slice(fragmentStart);
- filePath = filePath.slice(0, fragmentStart);
- }
- var context = clone(this.context);
- context.rawBuffer = true;
- var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
- if (!fileManager) {
- return fallback(this, filePathNode);
- }
- var useBase64 = false;
-
- if (!mimetypeNode) {
- mimetype = environment.mimeLookup(filePath);
- if (mimetype === 'image/svg+xml') {
- useBase64 = false;
- }
- else {
-
- var charset = environment.charsetLookup(mimetype);
- useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
- }
- if (useBase64) {
- mimetype += ';base64';
- }
- }
- else {
- useBase64 = /;base64$/.test(mimetype);
- }
- var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
- if (!fileSync.contents) {
- logger.warn("Skipped data-uri embedding of " + filePath + " because file not found");
- return fallback(this, filePathNode || mimetypeNode);
- }
- var buf = fileSync.contents;
- if (useBase64 && !environment.encodeBase64) {
- return fallback(this, filePathNode);
- }
- buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
- var uri = "data:" + mimetype + "," + buf + fragment;
- return new URL(new Quoted("\"" + uri + "\"", uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
- } };
- });
- var getItemsFromNode = function (node) {
-
-
- var items = Array.isArray(node.value) ?
- node.value : Array(node);
- return items;
- };
- var list = {
- _SELF: function (n) {
- return n;
- },
- extract: function (values, index) {
-
- index = index.value - 1;
- return getItemsFromNode(values)[index];
- },
- length: function (values) {
- return new Dimension(getItemsFromNode(values).length);
- },
-
- range: function (start, end, step) {
- var from;
- var to;
- var stepValue = 1;
- var list = [];
- if (end) {
- to = end;
- from = start.value;
- if (step) {
- stepValue = step.value;
- }
- }
- else {
- from = 1;
- to = start;
- }
- for (var i = from; i <= to.value; i += stepValue) {
- list.push(new Dimension(i, to.unit));
- }
- return new Expression(list);
- },
- each: function (list, rs) {
- var _this = this;
- var rules = [];
- var newRules;
- var iterator;
- var tryEval = function (val) {
- if (val instanceof Node) {
- return val.eval(_this.context);
- }
- return val;
- };
- if (list.value && !(list instanceof Quoted)) {
- if (Array.isArray(list.value)) {
- iterator = list.value.map(tryEval);
- }
- else {
- iterator = [tryEval(list.value)];
- }
- }
- else if (list.ruleset) {
- iterator = tryEval(list.ruleset).rules;
- }
- else if (list.rules) {
- iterator = list.rules.map(tryEval);
- }
- else if (Array.isArray(list)) {
- iterator = list.map(tryEval);
- }
- else {
- iterator = [tryEval(list)];
- }
- var valueName = '@value';
- var keyName = '@key';
- var indexName = '@index';
- if (rs.params) {
- valueName = rs.params[0] && rs.params[0].name;
- keyName = rs.params[1] && rs.params[1].name;
- indexName = rs.params[2] && rs.params[2].name;
- rs = rs.rules;
- }
- else {
- rs = rs.ruleset;
- }
- for (var i = 0; i < iterator.length; i++) {
- var key = void 0;
- var value = void 0;
- var item = iterator[i];
- if (item instanceof Declaration) {
- key = typeof item.name === 'string' ? item.name : item.name[0].value;
- value = item.value;
- }
- else {
- key = new Dimension(i + 1);
- value = item;
- }
- if (item instanceof Comment) {
- continue;
- }
- newRules = rs.rules.slice(0);
- if (valueName) {
- newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
- }
- if (indexName) {
- newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
- }
- if (keyName) {
- newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
- }
- rules.push(new Ruleset([new (Selector)([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
- }
- return new Ruleset([new (Selector)([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
- }
- };
- var MathHelper = function (fn, unit, n) {
- if (!(n instanceof Dimension)) {
- throw { type: 'Argument', message: 'argument must be a number' };
- }
- if (unit == null) {
- unit = n.unit;
- }
- else {
- n = n.unify();
- }
- return new Dimension(fn(parseFloat(n.value)), unit);
- };
- var mathFunctions = {
-
- ceil: null,
- floor: null,
- sqrt: null,
- abs: null,
- tan: '',
- sin: '',
- cos: '',
- atan: 'rad',
- asin: 'rad',
- acos: 'rad'
- };
- for (var f$1 in mathFunctions) {
- if (mathFunctions.hasOwnProperty(f$1)) {
- mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
- }
- }
- mathFunctions.round = function (n, f) {
- var fraction = typeof f === 'undefined' ? 0 : f.value;
- return MathHelper(function (num) { return num.toFixed(fraction); }, null, n);
- };
- var minMax = function (isMin, args) {
- args = Array.prototype.slice.call(args);
- switch (args.length) {
- case 0: throw { type: 'Argument', message: 'one or more arguments required' };
- }
- var i;
- var j;
- var current;
- var currentUnified;
- var referenceUnified;
- var unit;
- var unitStatic;
- var unitClone;
- var
- order = [];
- var values = {};
-
- for (i = 0; i < args.length; i++) {
- current = args[i];
- if (!(current instanceof Dimension)) {
- if (Array.isArray(args[i].value)) {
- Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
- }
- continue;
- }
- currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
- unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
- unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
- unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
- j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
- if (j === undefined) {
- if (unitStatic !== undefined && unit !== unitStatic) {
- throw { type: 'Argument', message: 'incompatible types' };
- }
- values[unit] = order.length;
- order.push(current);
- continue;
- }
- referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
- if (isMin && currentUnified.value < referenceUnified.value ||
- !isMin && currentUnified.value > referenceUnified.value) {
- order[j] = current;
- }
- }
- if (order.length == 1) {
- return order[0];
- }
- args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
- return new Anonymous((isMin ? 'min' : 'max') + "(" + args + ")");
- };
- var number$1 = {
- min: function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return minMax(true, args);
- },
- max: function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return minMax(false, args);
- },
- convert: function (val, unit) {
- return val.convertTo(unit.value);
- },
- pi: function () {
- return new Dimension(Math.PI);
- },
- mod: function (a, b) {
- return new Dimension(a.value % b.value, a.unit);
- },
- pow: function (x, y) {
- if (typeof x === 'number' && typeof y === 'number') {
- x = new Dimension(x);
- y = new Dimension(y);
- }
- else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
- throw { type: 'Argument', message: 'arguments must be numbers' };
- }
- return new Dimension(Math.pow(x.value, y.value), x.unit);
- },
- percentage: function (n) {
- var result = MathHelper(function (num) { return num * 100; }, '%', n);
- return result;
- }
- };
- var string = {
- e: function (str) {
- return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
- },
- escape: function (str) {
- return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
- .replace(/\(/g, '%28').replace(/\)/g, '%29'));
- },
- replace: function (string, pattern, replacement, flags) {
- var result = string.value;
- replacement = (replacement.type === 'Quoted') ?
- replacement.value : replacement.toCSS();
- result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
- return new Quoted(string.quote || '', result, string.escaped);
- },
- '%': function (string /* arg, arg, ... */) {
- var args = Array.prototype.slice.call(arguments, 1);
- var result = string.value;
- var _loop_1 = function (i) {
-
- result = result.replace(/%[sda]/i, function (token) {
- var value = ((args[i].type === 'Quoted') &&
- token.match(/s/i)) ? args[i].value : args[i].toCSS();
- return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
- });
- };
- for (var i = 0; i < args.length; i++) {
- _loop_1(i);
- }
- result = result.replace(/%%/g, '%');
- return new Quoted(string.quote || '', result, string.escaped);
- }
- };
- var svg = (function (environment) {
- return { 'svg-gradient': function (direction) {
- var stops;
- var gradientDirectionSvg;
- var gradientType = 'linear';
- var rectangleDimension = 'x="0" y="0" width="1" height="1"';
- var renderEnv = { compress: false };
- var returner;
- var directionValue = direction.toCSS(renderEnv);
- var i;
- var color;
- var position;
- var positionValue;
- var alpha;
- function throwArgumentDescriptor() {
- throw { type: 'Argument',
- message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
- ' end_color [end_position] or direction, color list' };
- }
- if (arguments.length == 2) {
- if (arguments[1].value.length < 2) {
- throwArgumentDescriptor();
- }
- stops = arguments[1].value;
- }
- else if (arguments.length < 3) {
- throwArgumentDescriptor();
- }
- else {
- stops = Array.prototype.slice.call(arguments, 1);
- }
- switch (directionValue) {
- case 'to bottom':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
- break;
- case 'to right':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
- break;
- case 'to bottom right':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
- break;
- case 'to top right':
- gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
- break;
- case 'ellipse':
- case 'ellipse at center':
- gradientType = 'radial';
- gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
- rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
- break;
- default:
- throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
- ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
- }
- returner = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><" + gradientType + "Gradient id=\"g\" " + gradientDirectionSvg + ">";
- for (i = 0; i < stops.length; i += 1) {
- if (stops[i] instanceof Expression) {
- color = stops[i].value[0];
- position = stops[i].value[1];
- }
- else {
- color = stops[i];
- position = undefined;
- }
- if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
- throwArgumentDescriptor();
- }
- positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
- alpha = color.alpha;
- returner += "<stop offset=\"" + positionValue + "\" stop-color=\"" + color.toRGB() + "\"" + (alpha < 1 ? " stop-opacity=\"" + alpha + "\"" : '') + "/>";
- }
- returner += "</" + gradientType + "Gradient><rect " + rectangleDimension + " fill=\"url(#g)\" /></svg>";
- returner = encodeURIComponent(returner);
- returner = "data:image/svg+xml," + returner;
- return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
- } };
- });
- var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; };
- var isunit = function (n, unit) {
- if (unit === undefined) {
- throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
- }
- unit = typeof unit.value === 'string' ? unit.value : unit;
- if (typeof unit !== 'string') {
- throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
- }
- return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
- };
- var types = {
- isruleset: function (n) {
- return isa(n, DetachedRuleset);
- },
- iscolor: function (n) {
- return isa(n, Color);
- },
- isnumber: function (n) {
- return isa(n, Dimension);
- },
- isstring: function (n) {
- return isa(n, Quoted);
- },
- iskeyword: function (n) {
- return isa(n, Keyword);
- },
- isurl: function (n) {
- return isa(n, URL);
- },
- ispixel: function (n) {
- return isunit(n, 'px');
- },
- ispercentage: function (n) {
- return isunit(n, '%');
- },
- isem: function (n) {
- return isunit(n, 'em');
- },
- isunit: isunit,
- unit: function (val, unit) {
- if (!(val instanceof Dimension)) {
- throw { type: 'Argument', message: "the first argument to unit must be a number" + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
- }
- if (unit) {
- if (unit instanceof Keyword) {
- unit = unit.value;
- }
- else {
- unit = unit.toCSS();
- }
- }
- else {
- unit = '';
- }
- return new Dimension(val.value, unit);
- },
- 'get-unit': function (n) {
- return new Anonymous(n.unit);
- }
- };
- var Functions = (function (environment) {
- var functions = { functionRegistry: functionRegistry, functionCaller: functionCaller };
-
- functionRegistry.addMultiple(boolean$1);
- functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
- functionRegistry.addMultiple(color);
- functionRegistry.addMultiple(colorBlend);
- functionRegistry.addMultiple(dataUri(environment));
- functionRegistry.addMultiple(list);
- functionRegistry.addMultiple(mathFunctions);
- functionRegistry.addMultiple(number$1);
- functionRegistry.addMultiple(string);
- functionRegistry.addMultiple(svg());
- functionRegistry.addMultiple(types);
- return functions;
- });
- var sourceMapOutput = (function (environment) {
- var SourceMapOutput = (function () {
- function SourceMapOutput(options) {
- this._css = [];
- this._rootNode = options.rootNode;
- this._contentsMap = options.contentsMap;
- this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
- if (options.sourceMapFilename) {
- this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
- }
- this._outputFilename = options.outputFilename;
- this.sourceMapURL = options.sourceMapURL;
- if (options.sourceMapBasepath) {
- this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
- }
- if (options.sourceMapRootpath) {
- this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
- if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
- this._sourceMapRootpath += '/';
- }
- }
- else {
- this._sourceMapRootpath = '';
- }
- this._outputSourceFiles = options.outputSourceFiles;
- this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
- this._lineNumber = 0;
- this._column = 0;
- }
- SourceMapOutput.prototype.removeBasepath = function (path) {
- if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
- path = path.substring(this._sourceMapBasepath.length);
- if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
- path = path.substring(1);
- }
- }
- return path;
- };
- SourceMapOutput.prototype.normalizeFilename = function (filename) {
- filename = filename.replace(/\\/g, '/');
- filename = this.removeBasepath(filename);
- return (this._sourceMapRootpath || '') + filename;
- };
- SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
-
- if (!chunk) {
- return;
- }
- var lines;
- var sourceLines;
- var columns;
- var sourceColumns;
- var i;
- if (fileInfo && fileInfo.filename) {
- var inputSource = this._contentsMap[fileInfo.filename];
-
- if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
-
- index -= this._contentsIgnoredCharsMap[fileInfo.filename];
- if (index < 0) {
- index = 0;
- }
-
- inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
- }
-
- if (inputSource === undefined) {
- this._css.push(chunk);
- return;
- }
- inputSource = inputSource.substring(0, index);
- sourceLines = inputSource.split('\n');
- sourceColumns = sourceLines[sourceLines.length - 1];
- }
- lines = chunk.split('\n');
- columns = lines[lines.length - 1];
- if (fileInfo && fileInfo.filename) {
- if (!mapLines) {
- this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
- original: { line: sourceLines.length, column: sourceColumns.length },
- source: this.normalizeFilename(fileInfo.filename) });
- }
- else {
- for (i = 0; i < lines.length; i++) {
- this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
- original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
- source: this.normalizeFilename(fileInfo.filename) });
- }
- }
- }
- if (lines.length === 1) {
- this._column += columns.length;
- }
- else {
- this._lineNumber += lines.length - 1;
- this._column = columns.length;
- }
- this._css.push(chunk);
- };
- SourceMapOutput.prototype.isEmpty = function () {
- return this._css.length === 0;
- };
- SourceMapOutput.prototype.toCSS = function (context) {
- this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
- if (this._outputSourceFiles) {
- for (var filename in this._contentsMap) {
- if (this._contentsMap.hasOwnProperty(filename)) {
- var source = this._contentsMap[filename];
- if (this._contentsIgnoredCharsMap[filename]) {
- source = source.slice(this._contentsIgnoredCharsMap[filename]);
- }
- this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
- }
- }
- }
- this._rootNode.genCSS(context, this);
- if (this._css.length > 0) {
- var sourceMapURL = void 0;
- var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
- if (this.sourceMapURL) {
- sourceMapURL = this.sourceMapURL;
- }
- else if (this._sourceMapFilename) {
- sourceMapURL = this._sourceMapFilename;
- }
- this.sourceMapURL = sourceMapURL;
- this.sourceMap = sourceMapContent;
- }
- return this._css.join('');
- };
- return SourceMapOutput;
- }());
- return SourceMapOutput;
- });
- var sourceMapBuilder = (function (SourceMapOutput, environment) {
- var SourceMapBuilder = (function () {
- function SourceMapBuilder(options) {
- this.options = options;
- }
- SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
- var sourceMapOutput = new SourceMapOutput({
- contentsIgnoredCharsMap: imports.contentsIgnoredChars,
- rootNode: rootNode,
- contentsMap: imports.contents,
- sourceMapFilename: this.options.sourceMapFilename,
- sourceMapURL: this.options.sourceMapURL,
- outputFilename: this.options.sourceMapOutputFilename,
- sourceMapBasepath: this.options.sourceMapBasepath,
- sourceMapRootpath: this.options.sourceMapRootpath,
- outputSourceFiles: this.options.outputSourceFiles,
- sourceMapGenerator: this.options.sourceMapGenerator,
- sourceMapFileInline: this.options.sourceMapFileInline,
- disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
- });
- var css = sourceMapOutput.toCSS(options);
- this.sourceMap = sourceMapOutput.sourceMap;
- this.sourceMapURL = sourceMapOutput.sourceMapURL;
- if (this.options.sourceMapInputFilename) {
- this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
- }
- if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
- this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
- }
- return css + this.getCSSAppendage();
- };
- SourceMapBuilder.prototype.getCSSAppendage = function () {
- var sourceMapURL = this.sourceMapURL;
- if (this.options.sourceMapFileInline) {
- if (this.sourceMap === undefined) {
- return '';
- }
- sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
- }
- if (this.options.disableSourcemapAnnotation) {
- return '';
- }
- if (sourceMapURL) {
- return "/*# sourceMappingURL=" + sourceMapURL + " */";
- }
- return '';
- };
- SourceMapBuilder.prototype.getExternalSourceMap = function () {
- return this.sourceMap;
- };
- SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
- this.sourceMap = sourceMap;
- };
- SourceMapBuilder.prototype.isInline = function () {
- return this.options.sourceMapFileInline;
- };
- SourceMapBuilder.prototype.getSourceMapURL = function () {
- return this.sourceMapURL;
- };
- SourceMapBuilder.prototype.getOutputFilename = function () {
- return this.options.sourceMapOutputFilename;
- };
- SourceMapBuilder.prototype.getInputFilename = function () {
- return this.sourceMapInputFilename;
- };
- return SourceMapBuilder;
- }());
- return SourceMapBuilder;
- });
- var transformTree = (function (root, options) {
- if (options === void 0) { options = {}; }
- var evaldRoot;
- var variables = options.variables;
- var evalEnv = new contexts.Eval(options);
-
-
-
-
-
-
-
-
-
-
-
-
-
- if (typeof variables === 'object' && !Array.isArray(variables)) {
- variables = Object.keys(variables).map(function (k) {
- var value = variables[k];
- if (!(value instanceof tree.Value)) {
- if (!(value instanceof tree.Expression)) {
- value = new tree.Expression([value]);
- }
- value = new tree.Value([value]);
- }
- return new tree.Declaration("@" + k, value, false, null, 0);
- });
- evalEnv.frames = [new tree.Ruleset(null, variables)];
- }
- var visitors$1 = [
- new visitors.JoinSelectorVisitor(),
- new visitors.MarkVisibleSelectorsVisitor(true),
- new visitors.ExtendVisitor(),
- new visitors.ToCSSVisitor({ compress: Boolean(options.compress) })
- ];
- var preEvalVisitors = [];
- var v;
- var visitorIterator;
-
- if (options.pluginManager) {
- visitorIterator = options.pluginManager.visitor();
- for (var i = 0; i < 2; i++) {
- visitorIterator.first();
- while ((v = visitorIterator.get())) {
- if (v.isPreEvalVisitor) {
- if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
- preEvalVisitors.push(v);
- v.run(root);
- }
- }
- else {
- if (i === 0 || visitors$1.indexOf(v) === -1) {
- if (v.isPreVisitor) {
- visitors$1.unshift(v);
- }
- else {
- visitors$1.push(v);
- }
- }
- }
- }
- }
- }
- evaldRoot = root.eval(evalEnv);
- for (var i = 0; i < visitors$1.length; i++) {
- visitors$1[i].run(evaldRoot);
- }
-
- if (options.pluginManager) {
- visitorIterator.first();
- while ((v = visitorIterator.get())) {
- if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
- v.run(evaldRoot);
- }
- }
- }
- return evaldRoot;
- });
- var parseTree = (function (SourceMapBuilder) {
- var ParseTree = (function () {
- function ParseTree(root, imports) {
- this.root = root;
- this.imports = imports;
- }
- ParseTree.prototype.toCSS = function (options) {
- var evaldRoot;
- var result = {};
- var sourceMapBuilder;
- try {
- evaldRoot = transformTree(this.root, options);
- }
- catch (e) {
- throw new LessError(e, this.imports);
- }
- try {
- var compress = Boolean(options.compress);
- if (compress) {
- logger.warn('The compress option has been deprecated. ' +
- 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
- }
- var toCSSOptions = {
- compress: compress,
- dumpLineNumbers: options.dumpLineNumbers,
- strictUnits: Boolean(options.strictUnits),
- numPrecision: 8
- };
- if (options.sourceMap) {
- sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
- result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
- }
- else {
- result.css = evaldRoot.toCSS(toCSSOptions);
- }
- }
- catch (e) {
- throw new LessError(e, this.imports);
- }
- if (options.pluginManager) {
- var postProcessors = options.pluginManager.getPostProcessors();
- for (var i = 0; i < postProcessors.length; i++) {
- result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
- }
- }
- if (options.sourceMap) {
- result.map = sourceMapBuilder.getExternalSourceMap();
- }
- result.imports = [];
- for (var file in this.imports.files) {
- if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
- result.imports.push(file);
- }
- }
- return result;
- };
- return ParseTree;
- }());
- return ParseTree;
- });
- function importManager (environment) {
-
-
-
-
-
-
-
-
- var ImportManager = (function () {
- function ImportManager(less, context, rootFileInfo) {
- this.less = less;
- this.rootFilename = rootFileInfo.filename;
- this.paths = context.paths || [];
- this.contents = {};
- this.contentsIgnoredChars = {};
- this.mime = context.mime;
- this.error = null;
- this.context = context;
-
- this.queue = [];
- this.files = {};
- }
-
- ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
- var importManager = this, pluginLoader = this.context.pluginManager.Loader;
- this.queue.push(path);
- var fileParsedFunc = function (e, root, fullPath) {
- importManager.queue.splice(importManager.queue.indexOf(path), 1);
- var importedEqualsRoot = fullPath === importManager.rootFilename;
- if (importOptions.optional && e) {
- callback(null, { rules: [] }, false, null);
- logger.info("The file " + fullPath + " was skipped because it was not found and the import was marked optional.");
- }
- else {
-
-
-
- if (!importManager.files[fullPath] && !importOptions.inline) {
- importManager.files[fullPath] = { root: root, options: importOptions };
- }
- if (e && !importManager.error) {
- importManager.error = e;
- }
- callback(e, root, importedEqualsRoot, fullPath);
- }
- };
- var newFileInfo = {
- rewriteUrls: this.context.rewriteUrls,
- entryPath: currentFileInfo.entryPath,
- rootpath: currentFileInfo.rootpath,
- rootFilename: currentFileInfo.rootFilename
- };
- var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
- if (!fileManager) {
- fileParsedFunc({ message: "Could not find a file-manager for " + path });
- return;
- }
- var loadFileCallback = function (loadedFile) {
- var plugin;
- var resolvedFilename = loadedFile.filename;
- var contents = loadedFile.contents.replace(/^\uFEFF/, '');
-
-
-
-
-
-
-
-
- newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
- if (newFileInfo.rewriteUrls) {
- newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
- if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
- newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
- }
- }
- newFileInfo.filename = resolvedFilename;
- var newEnv = new contexts.Parse(importManager.context);
- newEnv.processImports = false;
- importManager.contents[resolvedFilename] = contents;
- if (currentFileInfo.reference || importOptions.reference) {
- newFileInfo.reference = true;
- }
- if (importOptions.isPlugin) {
- plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
- if (plugin instanceof LessError) {
- fileParsedFunc(plugin, null, resolvedFilename);
- }
- else {
- fileParsedFunc(null, plugin, resolvedFilename);
- }
- }
- else if (importOptions.inline) {
- fileParsedFunc(null, contents, resolvedFilename);
- }
- else {
-
-
- if (importManager.files[resolvedFilename]
- && !importManager.files[resolvedFilename].options.multiple
- && !importOptions.multiple) {
- fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
- }
- else {
- new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
- fileParsedFunc(e, root, resolvedFilename);
- });
- }
- }
- };
- var loadedFile;
- var promise;
- var context = clone(this.context);
- if (tryAppendExtension) {
- context.ext = importOptions.isPlugin ? '.js' : '.less';
- }
- if (importOptions.isPlugin) {
- context.mime = 'application/javascript';
- if (context.syncImport) {
- loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
- }
- else {
- promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
- }
- }
- else {
- if (context.syncImport) {
- loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
- }
- else {
- promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
- if (err) {
- fileParsedFunc(err);
- }
- else {
- loadFileCallback(loadedFile);
- }
- });
- }
- }
- if (loadedFile) {
- if (!loadedFile.filename) {
- fileParsedFunc(loadedFile);
- }
- else {
- loadFileCallback(loadedFile);
- }
- }
- else if (promise) {
- promise.then(loadFileCallback, fileParsedFunc);
- }
- };
- return ImportManager;
- }());
- return ImportManager;
- }
- var Render = (function (environment, ParseTree, ImportManager) {
- var render = function (input, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = copyOptions(this.options, {});
- }
- else {
- options = copyOptions(this.options, options || {});
- }
- if (!callback) {
- var self_1 = this;
- return new Promise(function (resolve, reject) {
- render.call(self_1, input, options, function (err, output) {
- if (err) {
- reject(err);
- }
- else {
- resolve(output);
- }
- });
- });
- }
- else {
- this.parse(input, options, function (err, root, imports, options) {
- if (err) {
- return callback(err);
- }
- var result;
- try {
- var parseTree = new ParseTree(root, imports);
- result = parseTree.toCSS(options);
- }
- catch (err) {
- return callback(err);
- }
- callback(null, result);
- });
- }
- };
- return render;
- });
-
- var PluginManager = (function () {
- function PluginManager(less) {
- this.less = less;
- this.visitors = [];
- this.preProcessors = [];
- this.postProcessors = [];
- this.installedPlugins = [];
- this.fileManagers = [];
- this.iterator = -1;
- this.pluginCache = {};
- this.Loader = new less.PluginLoader(less);
- }
-
- PluginManager.prototype.addPlugins = function (plugins) {
- if (plugins) {
- for (var i = 0; i < plugins.length; i++) {
- this.addPlugin(plugins[i]);
- }
- }
- };
-
- PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
- this.installedPlugins.push(plugin);
- if (filename) {
- this.pluginCache[filename] = plugin;
- }
- if (plugin.install) {
- plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
- }
- };
-
- PluginManager.prototype.get = function (filename) {
- return this.pluginCache[filename];
- };
-
- PluginManager.prototype.addVisitor = function (visitor) {
- this.visitors.push(visitor);
- };
-
- PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
- var indexToInsertAt;
- for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
- if (this.preProcessors[indexToInsertAt].priority >= priority) {
- break;
- }
- }
- this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
- };
-
- PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
- var indexToInsertAt;
- for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
- if (this.postProcessors[indexToInsertAt].priority >= priority) {
- break;
- }
- }
- this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
- };
-
- PluginManager.prototype.addFileManager = function (manager) {
- this.fileManagers.push(manager);
- };
-
- PluginManager.prototype.getPreProcessors = function () {
- var preProcessors = [];
- for (var i = 0; i < this.preProcessors.length; i++) {
- preProcessors.push(this.preProcessors[i].preProcessor);
- }
- return preProcessors;
- };
-
- PluginManager.prototype.getPostProcessors = function () {
- var postProcessors = [];
- for (var i = 0; i < this.postProcessors.length; i++) {
- postProcessors.push(this.postProcessors[i].postProcessor);
- }
- return postProcessors;
- };
-
- PluginManager.prototype.getVisitors = function () {
- return this.visitors;
- };
- PluginManager.prototype.visitor = function () {
- var self = this;
- return {
- first: function () {
- self.iterator = -1;
- return self.visitors[self.iterator];
- },
- get: function () {
- self.iterator += 1;
- return self.visitors[self.iterator];
- }
- };
- };
-
- PluginManager.prototype.getFileManagers = function () {
- return this.fileManagers;
- };
- return PluginManager;
- }());
- var pm;
- function PluginManagerFactory(less, newFactory) {
- if (newFactory || !pm) {
- pm = new PluginManager(less);
- }
- return pm;
- }
- var Parse = (function (environment, ParseTree, ImportManager) {
- var parse = function (input, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = copyOptions(this.options, {});
- }
- else {
- options = copyOptions(this.options, options || {});
- }
- if (!callback) {
- var self_1 = this;
- return new Promise(function (resolve, reject) {
- parse.call(self_1, input, options, function (err, output) {
- if (err) {
- reject(err);
- }
- else {
- resolve(output);
- }
- });
- });
- }
- else {
- var context_1;
- var rootFileInfo = void 0;
- var pluginManager_1 = new PluginManagerFactory(this, !options.reUsePluginManager);
- options.pluginManager = pluginManager_1;
- context_1 = new contexts.Parse(options);
- if (options.rootFileInfo) {
- rootFileInfo = options.rootFileInfo;
- }
- else {
- var filename = options.filename || 'input';
- var entryPath = filename.replace(/[^\/\\]*$/, '');
- rootFileInfo = {
- filename: filename,
- rewriteUrls: context_1.rewriteUrls,
- rootpath: context_1.rootpath || '',
- currentDirectory: entryPath,
- entryPath: entryPath,
- rootFilename: filename
- };
-
- if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
- rootFileInfo.rootpath += '/';
- }
- }
- var imports_1 = new ImportManager(this, context_1, rootFileInfo);
- this.importManager = imports_1;
-
-
- if (options.plugins) {
- options.plugins.forEach(function (plugin) {
- var evalResult;
- var contents;
- if (plugin.fileContent) {
- contents = plugin.fileContent.replace(/^\uFEFF/, '');
- evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
- if (evalResult instanceof LessError) {
- return callback(evalResult);
- }
- }
- else {
- pluginManager_1.addPlugin(plugin);
- }
- });
- }
- new Parser(context_1, imports_1, rootFileInfo)
- .parse(input, function (e, root) {
- if (e) {
- return callback(e);
- }
- callback(null, root, imports_1, options);
- }, options);
- }
- };
- return parse;
- });
- var lessRoot = (function (environment$1, fileManagers) {
-
- environment$1 = new environment(environment$1, fileManagers);
- var SourceMapOutput = sourceMapOutput(environment$1);
- var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment$1);
- var ParseTree = parseTree(SourceMapBuilder);
- var ImportManager = importManager(environment$1);
- var render = Render(environment$1, ParseTree);
- var parse = Parse(environment$1, ParseTree, ImportManager);
- var functions = Functions(environment$1);
-
- var initial = {
- version: [3, 13, 1],
- data: data,
- tree: tree,
- Environment: environment,
- AbstractFileManager: AbstractFileManager,
- AbstractPluginLoader: AbstractPluginLoader,
- environment: environment$1,
- visitors: visitors,
- Parser: Parser,
- functions: functions,
- contexts: contexts,
- SourceMapOutput: SourceMapOutput,
- SourceMapBuilder: SourceMapBuilder,
- ParseTree: ParseTree,
- ImportManager: ImportManager,
- render: render,
- parse: parse,
- LessError: LessError,
- transformTree: transformTree,
- utils: utils,
- PluginManager: PluginManagerFactory,
- logger: logger
- };
-
- var ctor = function (t) { return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return new (t.bind.apply(t, __spreadArrays([void 0], args)))();
- }; };
- var t;
- var api = Object.create(initial);
- for (var n in initial.tree) {
-
- t = initial.tree[n];
- if (typeof t === 'function') {
- api[n.toLowerCase()] = ctor(t);
- }
- else {
- api[n] = Object.create(null);
- for (var o in t) {
-
- api[n][o.toLowerCase()] = ctor(t[o]);
- }
- }
- }
-
- initial.parse = initial.parse.bind(api);
- initial.render = initial.render.bind(api);
- return api;
- });
-
- var options;
- var logger$1;
- var fileCache = {};
-
- var FileManager = (function (_super) {
- __extends(FileManager, _super);
- function FileManager() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- FileManager.prototype.alwaysMakePathsAbsolute = function () {
- return true;
- };
- FileManager.prototype.join = function (basePath, laterPath) {
- if (!basePath) {
- return laterPath;
- }
- return this.extractUrlParts(laterPath, basePath).path;
- };
- FileManager.prototype.doXHR = function (url, type, callback, errback) {
- var xhr = new XMLHttpRequest();
- var async = options.isFileProtocol ? options.fileAsync : true;
- if (typeof xhr.overrideMimeType === 'function') {
- xhr.overrideMimeType('text/css');
- }
- logger$1.debug("XHR: Getting '" + url + "'");
- xhr.open('GET', url, async);
- xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
- xhr.send(null);
- function handleResponse(xhr, callback, errback) {
- if (xhr.status >= 200 && xhr.status < 300) {
- callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
- }
- else if (typeof errback === 'function') {
- errback(xhr.status, url);
- }
- }
- if (options.isFileProtocol && !options.fileAsync) {
- if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
- callback(xhr.responseText);
- }
- else {
- errback(xhr.status, url);
- }
- }
- else if (async) {
- xhr.onreadystatechange = function () {
- if (xhr.readyState == 4) {
- handleResponse(xhr, callback, errback);
- }
- };
- }
- else {
- handleResponse(xhr, callback, errback);
- }
- };
- FileManager.prototype.supports = function () {
- return true;
- };
- FileManager.prototype.clearFileCache = function () {
- fileCache = {};
- };
- FileManager.prototype.loadFile = function (filename, currentDirectory, options, environment) {
-
-
- if (currentDirectory && !this.isPathAbsolute(filename)) {
- filename = currentDirectory + filename;
- }
- filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
- options = options || {};
-
-
- var hrefParts = this.extractUrlParts(filename, window.location.href);
- var href = hrefParts.url;
- var self = this;
- return new Promise(function (resolve, reject) {
- if (options.useFileCache && fileCache[href]) {
- try {
- var lessText = fileCache[href];
- return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() } });
- }
- catch (e) {
- return reject({ filename: href, message: "Error loading file " + href + " error was " + e.message });
- }
- }
- self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
-
- fileCache[href] = data;
-
- resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
- }, function doXHRError(status, url) {
- reject({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
- });
- });
- };
- return FileManager;
- }(AbstractFileManager));
- var FM = (function (opts, log) {
- options = opts;
- logger$1 = log;
- return FileManager;
- });
-
-
- var PluginLoader = (function (_super) {
- __extends(PluginLoader, _super);
- function PluginLoader(less) {
- var _this = _super.call(this) || this;
- _this.less = less;
- return _this;
-
- }
- PluginLoader.prototype.loadPlugin = function (filename, basePath, context, environment, fileManager) {
- return new Promise(function (fulfill, reject) {
- fileManager.loadFile(filename, basePath, context, environment)
- .then(fulfill).catch(reject);
- });
- };
- return PluginLoader;
- }(AbstractPluginLoader));
- var LogListener = (function (less, options) {
- var logLevel_debug = 4;
- var logLevel_info = 3;
- var logLevel_warn = 2;
- var logLevel_error = 1;
-
-
-
-
-
-
- options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
- if (!options.loggers) {
- options.loggers = [{
- debug: function (msg) {
- if (options.logLevel >= logLevel_debug) {
- console.log(msg);
- }
- },
- info: function (msg) {
- if (options.logLevel >= logLevel_info) {
- console.log(msg);
- }
- },
- warn: function (msg) {
- if (options.logLevel >= logLevel_warn) {
- console.warn(msg);
- }
- },
- error: function (msg) {
- if (options.logLevel >= logLevel_error) {
- console.error(msg);
- }
- }
- }];
- }
- for (var i = 0; i < options.loggers.length; i++) {
- less.logger.addListener(options.loggers[i]);
- }
- });
- var ErrorReporting = (function (window, less, options) {
- function errorHTML(e, rootHref) {
- var id = "less-error-message:" + extractId(rootHref || '');
- var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
- var elem = window.document.createElement('div');
- var timer;
- var content;
- var errors = [];
- var filename = e.filename || rootHref;
- var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
- elem.id = id;
- elem.className = 'less-error-message';
- content = "<h3>" + (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') +
- ("</h3><p>in <a href=\"" + filename + "\">" + filenameNoPath + "</a> ");
- var errorline = function (e, i, classname) {
- if (e.extract[i] !== undefined) {
- errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
- .replace(/\{class\}/, classname)
- .replace(/\{content\}/, e.extract[i]));
- }
- };
- if (e.line) {
- errorline(e, 0, '');
- errorline(e, 1, 'line');
- errorline(e, 2, '');
- content += "on line " + e.line + ", column " + (e.column + 1) + ":</p><ul>" + errors.join('') + "</ul>";
- }
- if (e.stack && (e.extract || options.logLevel >= 4)) {
- content += "<br/>Stack Trace</br />" + e.stack.split('\n').slice(1).join('<br/>');
- }
- elem.innerHTML = content;
-
- browser.createCSS(window.document, [
- '.less-error-message ul, .less-error-message li {',
- 'list-style-type: none;',
- 'margin-right: 15px;',
- 'padding: 4px 0;',
- 'margin: 0;',
- '}',
- '.less-error-message label {',
- 'font-size: 12px;',
- 'margin-right: 15px;',
- 'padding: 4px 0;',
- 'color: #cc7777;',
- '}',
- '.less-error-message pre {',
- 'color: #dd6666;',
- 'padding: 4px 0;',
- 'margin: 0;',
- 'display: inline-block;',
- '}',
- '.less-error-message pre.line {',
- 'color: #ff0000;',
- '}',
- '.less-error-message h3 {',
- 'font-size: 20px;',
- 'font-weight: bold;',
- 'padding: 15px 0 5px 0;',
- 'margin: 0;',
- '}',
- '.less-error-message a {',
- 'color: #10a',
- '}',
- '.less-error-message .error {',
- 'color: red;',
- 'font-weight: bold;',
- 'padding-bottom: 2px;',
- 'border-bottom: 1px dashed red;',
- '}'
- ].join('\n'), { title: 'error-message' });
- elem.style.cssText = [
- 'font-family: Arial, sans-serif',
- 'border: 1px solid #e00',
- 'background-color: #eee',
- 'border-radius: 5px',
- '-webkit-border-radius: 5px',
- '-moz-border-radius: 5px',
- 'color: #e00',
- 'padding: 15px',
- 'margin-bottom: 15px'
- ].join(';');
- if (options.env === 'development') {
- timer = setInterval(function () {
- var document = window.document;
- var body = document.body;
- if (body) {
- if (document.getElementById(id)) {
- body.replaceChild(elem, document.getElementById(id));
- }
- else {
- body.insertBefore(elem, body.firstChild);
- }
- clearInterval(timer);
- }
- }, 10);
- }
- }
- function removeErrorHTML(path) {
- var node = window.document.getElementById("less-error-message:" + extractId(path));
- if (node) {
- node.parentNode.removeChild(node);
- }
- }
- function removeError(path) {
- if (!options.errorReporting || options.errorReporting === 'html') {
- removeErrorHTML(path);
- }
- else if (options.errorReporting === 'console') ;
- else if (typeof options.errorReporting === 'function') {
- options.errorReporting('remove', path);
- }
- }
- function errorConsole(e, rootHref) {
- var template = '{line} {content}';
- var filename = e.filename || rootHref;
- var errors = [];
- var content = (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename;
- var errorline = function (e, i, classname) {
- if (e.extract[i] !== undefined) {
- errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
- .replace(/\{class\}/, classname)
- .replace(/\{content\}/, e.extract[i]));
- }
- };
- if (e.line) {
- errorline(e, 0, '');
- errorline(e, 1, 'line');
- errorline(e, 2, '');
- content += " on line " + e.line + ", column " + (e.column + 1) + ":\n" + errors.join('\n');
- }
- if (e.stack && (e.extract || options.logLevel >= 4)) {
- content += "\nStack Trace\n" + e.stack;
- }
- less.logger.error(content);
- }
- function error(e, rootHref) {
- if (!options.errorReporting || options.errorReporting === 'html') {
- errorHTML(e, rootHref);
- }
- else if (options.errorReporting === 'console') {
- errorConsole(e, rootHref);
- }
- else if (typeof options.errorReporting === 'function') {
- options.errorReporting('add', e, rootHref);
- }
- }
- return {
- add: error,
- remove: removeError
- };
- });
-
- var Cache = (function (window, options, logger) {
- var cache = null;
- if (options.env !== 'development') {
- try {
- cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
- }
- catch (_) { }
- }
- return {
- setCSS: function (path, lastModified, modifyVars, styles) {
- if (cache) {
- logger.info("saving " + path + " to cache.");
- try {
- cache.setItem(path, styles);
- cache.setItem(path + ":timestamp", lastModified);
- if (modifyVars) {
- cache.setItem(path + ":vars", JSON.stringify(modifyVars));
- }
- }
- catch (e) {
-
- logger.error("failed to save \"" + path + "\" to local storage for caching.");
- }
- }
- },
- getCSS: function (path, webInfo, modifyVars) {
- var css = cache && cache.getItem(path);
- var timestamp = cache && cache.getItem(path + ":timestamp");
- var vars = cache && cache.getItem(path + ":vars");
- modifyVars = modifyVars || {};
- vars = vars || "{}";
- if (timestamp && webInfo.lastModified &&
- (new Date(webInfo.lastModified).valueOf() ===
- new Date(timestamp).valueOf()) &&
- JSON.stringify(modifyVars) === vars) {
-
- return css;
- }
- }
- };
- });
- var ImageSize = (function () {
- function imageSize() {
- throw {
- type: 'Runtime',
- message: 'Image size functions are not supported in browser version of less'
- };
- }
- var imageFunctions = {
- 'image-size': function (filePathNode) {
- imageSize();
- return -1;
- },
- 'image-width': function (filePathNode) {
- imageSize();
- return -1;
- },
- 'image-height': function (filePathNode) {
- imageSize();
- return -1;
- }
- };
- functionRegistry.addMultiple(imageFunctions);
- });
-
- var root = (function (window, options) {
- var document = window.document;
- var less = lessRoot();
- less.options = options;
- var environment = less.environment;
- var FileManager = FM(options, less.logger);
- var fileManager = new FileManager();
- environment.addFileManager(fileManager);
- less.FileManager = FileManager;
- less.PluginLoader = PluginLoader;
- LogListener(less, options);
- var errors = ErrorReporting(window, less, options);
- var cache = less.cache = options.cache || Cache(window, options, less.logger);
- ImageSize(less.environment);
-
- if (options.functions) {
- less.functions.functionRegistry.addMultiple(options.functions);
- }
- var typePattern = /^text\/(x-)?less$/;
- function clone(obj) {
- var cloned = {};
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- cloned[prop] = obj[prop];
- }
- }
- return cloned;
- }
-
- function bind(func, thisArg) {
- var curryArgs = Array.prototype.slice.call(arguments, 2);
- return function () {
- var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
- return func.apply(thisArg, args);
- };
- }
- function loadStyles(modifyVars) {
- var styles = document.getElementsByTagName('style');
- var style;
- for (var i = 0; i < styles.length; i++) {
- style = styles[i];
- if (style.type.match(typePattern)) {
- var instanceOptions = clone(options);
- instanceOptions.modifyVars = modifyVars;
- var lessText = style.innerHTML || '';
- instanceOptions.filename = document.location.href.replace(/#.*$/, '');
-
-
- less.render(lessText, instanceOptions, bind(function (style, e, result) {
- if (e) {
- errors.add(e, 'inline');
- }
- else {
- style.type = 'text/css';
- if (style.styleSheet) {
- style.styleSheet.cssText = result.css;
- }
- else {
- style.innerHTML = result.css;
- }
- }
- }, null, style));
- }
- }
- }
- function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
- var instanceOptions = clone(options);
- addDataAttr(instanceOptions, sheet);
- instanceOptions.mime = sheet.type;
- if (modifyVars) {
- instanceOptions.modifyVars = modifyVars;
- }
- function loadInitialFileCallback(loadedFile) {
- var data = loadedFile.contents;
- var path = loadedFile.filename;
- var webInfo = loadedFile.webInfo;
- var newFileInfo = {
- currentDirectory: fileManager.getPath(path),
- filename: path,
- rootFilename: path,
- rewriteUrls: instanceOptions.rewriteUrls
- };
- newFileInfo.entryPath = newFileInfo.currentDirectory;
- newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
- if (webInfo) {
- webInfo.remaining = remaining;
- var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
- if (!reload && css) {
- webInfo.local = true;
- callback(null, css, data, sheet, webInfo, path);
- return;
- }
- }
-
- errors.remove(path);
- instanceOptions.rootFileInfo = newFileInfo;
- less.render(data, instanceOptions, function (e, result) {
- if (e) {
- e.href = path;
- callback(e);
- }
- else {
- cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
- callback(null, result.css, data, sheet, webInfo, path);
- }
- });
- }
- fileManager.loadFile(sheet.href, null, instanceOptions, environment)
- .then(function (loadedFile) {
- loadInitialFileCallback(loadedFile);
- }).catch(function (err) {
- console.log(err);
- callback(err);
- });
- }
- function loadStyleSheets(callback, reload, modifyVars) {
- for (var i = 0; i < less.sheets.length; i++) {
- loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
- }
- }
- function initRunningMode() {
- if (less.env === 'development') {
- less.watchTimer = setInterval(function () {
- if (less.watchMode) {
- fileManager.clearFileCache();
- loadStyleSheets(function (e, css, _, sheet, webInfo) {
- if (e) {
- errors.add(e, e.href || sheet.href);
- }
- else if (css) {
- browser.createCSS(window.document, css, sheet);
- }
- });
- }
- }, options.poll);
- }
- }
-
-
-
- less.watch = function () {
- if (!less.watchMode) {
- less.env = 'development';
- initRunningMode();
- }
- this.watchMode = true;
- return true;
- };
- less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
-
-
-
-
- less.registerStylesheetsImmediately = function () {
- var links = document.getElementsByTagName('link');
- less.sheets = [];
- for (var i = 0; i < links.length; i++) {
- if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
- (links[i].type.match(typePattern)))) {
- less.sheets.push(links[i]);
- }
- }
- };
-
-
-
-
- less.registerStylesheets = function () { return new Promise(function (resolve, reject) {
- less.registerStylesheetsImmediately();
- resolve();
- }); };
-
-
-
-
- less.modifyVars = function (record) { return less.refresh(true, record, false); };
- less.refresh = function (reload, modifyVars, clearFileCache) {
- if ((reload || clearFileCache) && clearFileCache !== false) {
- fileManager.clearFileCache();
- }
- return new Promise(function (resolve, reject) {
- var startTime;
- var endTime;
- var totalMilliseconds;
- var remainingSheets;
- startTime = endTime = new Date();
-
- remainingSheets = less.sheets.length;
- if (remainingSheets === 0) {
- endTime = new Date();
- totalMilliseconds = endTime - startTime;
- less.logger.info('Less has finished and no sheets were loaded.');
- resolve({
- startTime: startTime,
- endTime: endTime,
- totalMilliseconds: totalMilliseconds,
- sheets: less.sheets.length
- });
- }
- else {
-
- loadStyleSheets(function (e, css, _, sheet, webInfo) {
- if (e) {
- errors.add(e, e.href || sheet.href);
- reject(e);
- return;
- }
- if (webInfo.local) {
- less.logger.info("Loading " + sheet.href + " from cache.");
- }
- else {
- less.logger.info("Rendered " + sheet.href + " successfully.");
- }
- browser.createCSS(window.document, css, sheet);
- less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + "ms");
-
- remainingSheets--;
-
- if (remainingSheets === 0) {
- totalMilliseconds = new Date() - startTime;
- less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + "ms");
- resolve({
- startTime: startTime,
- endTime: endTime,
- totalMilliseconds: totalMilliseconds,
- sheets: less.sheets.length
- });
- }
- endTime = new Date();
- }, reload, modifyVars);
- }
- loadStyles(modifyVars);
- });
- };
- less.refreshStyles = loadStyles;
- return less;
- });
-
- var options$1 = defaultOptions();
- if (window.less) {
- for (var key in window.less) {
- if (window.less.hasOwnProperty(key)) {
- options$1[key] = window.less[key];
- }
- }
- }
- addDefaultOptions(window, options$1);
- options$1.plugins = options$1.plugins || [];
- if (window.LESS_PLUGINS) {
- options$1.plugins = options$1.plugins.concat(window.LESS_PLUGINS);
- }
- var less = root(window, options$1);
- window.less = less;
- var css;
- var head;
- var style;
-
- function resolveOrReject(data) {
- if (data.filename) {
- console.warn(data);
- }
- if (!options$1.async) {
- head.removeChild(style);
- }
- }
- if (options$1.onReady) {
- if (/!watch/.test(window.location.hash)) {
- less.watch();
- }
-
- if (!options$1.async) {
- css = 'body { display: none !important }';
- head = document.head || document.getElementsByTagName('head')[0];
- style = document.createElement('style');
- style.type = 'text/css';
- if (style.styleSheet) {
- style.styleSheet.cssText = css;
- }
- else {
- style.appendChild(document.createTextNode(css));
- }
- head.appendChild(style);
- }
- less.registerStylesheetsImmediately();
- less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
- }
- return less;
- })));
|