main.js 329 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858
  1. /*
  2. THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
  3. if you want to view the source visit the plugins github repository
  4. */
  5. 'use strict';
  6. var obsidian = require('obsidian');
  7. /*! *****************************************************************************
  8. Copyright (c) Microsoft Corporation.
  9. Permission to use, copy, modify, and/or distribute this software for any
  10. purpose with or without fee is hereby granted.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  12. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  13. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  14. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  15. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  16. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  17. PERFORMANCE OF THIS SOFTWARE.
  18. ***************************************************************************** */
  19. function __awaiter(thisArg, _arguments, P, generator) {
  20. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  21. return new (P || (P = Promise))(function (resolve, reject) {
  22. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  23. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  24. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  25. step((generator = generator.apply(thisArg, _arguments || [])).next());
  26. });
  27. }
  28. class ExportModal extends obsidian.Modal {
  29. constructor(app, plugin, section, config) {
  30. super(app);
  31. this.plugin = plugin;
  32. this.config = config;
  33. this.section = section;
  34. }
  35. onOpen() {
  36. const { contentEl, modalEl } = this;
  37. modalEl.addClass('modal-style-settings');
  38. new obsidian.Setting(contentEl)
  39. .setName(`Export settings for: ${this.section}`)
  40. .then((setting) => {
  41. const output = JSON.stringify(this.config, null, 2);
  42. // Build a copy to clipboard link
  43. setting.controlEl.createEl('a', {
  44. cls: 'style-settings-copy',
  45. text: 'Copy to clipboard',
  46. href: '#',
  47. }, (copyButton) => {
  48. new obsidian.TextAreaComponent(contentEl)
  49. .setValue(output)
  50. .then((textarea) => {
  51. copyButton.addEventListener('click', (e) => {
  52. e.preventDefault();
  53. // Select the textarea contents and copy them to the clipboard
  54. textarea.inputEl.select();
  55. textarea.inputEl.setSelectionRange(0, 99999);
  56. document.execCommand('copy');
  57. copyButton.addClass('success');
  58. setTimeout(() => {
  59. // If the button is still in the dom, remove the success class
  60. if (copyButton.parentNode) {
  61. copyButton.removeClass('success');
  62. }
  63. }, 2000);
  64. });
  65. });
  66. });
  67. // Build a download link
  68. setting.controlEl.createEl('a', {
  69. cls: 'style-settings-download',
  70. text: 'Download',
  71. attr: {
  72. download: 'style-settings.json',
  73. href: `data:application/json;charset=utf-8,${encodeURIComponent(output)}`,
  74. },
  75. });
  76. });
  77. }
  78. onClose() {
  79. const { contentEl } = this;
  80. contentEl.empty();
  81. }
  82. }
  83. class ImportModal extends obsidian.Modal {
  84. constructor(app, plugin) {
  85. super(app);
  86. this.plugin = plugin;
  87. }
  88. onOpen() {
  89. const { contentEl, modalEl } = this;
  90. modalEl.addClass('modal-style-settings');
  91. new obsidian.Setting(contentEl)
  92. .setName('Import style setting')
  93. .setDesc('Import an entire or partial configuration. Warning: this may override existing settings');
  94. new obsidian.Setting(contentEl).then((setting) => {
  95. // Build an error message container
  96. const errorSpan = createSpan({
  97. cls: 'style-settings-import-error',
  98. text: 'Error importing config',
  99. });
  100. setting.nameEl.appendChild(errorSpan);
  101. // Attempt to parse the imported data and close if successful
  102. const importAndClose = (str) => __awaiter(this, void 0, void 0, function* () {
  103. if (str) {
  104. try {
  105. const importedSettings = JSON.parse(str);
  106. yield this.plugin.settingsManager.setSettings(importedSettings);
  107. this.plugin.settingsTab.display();
  108. this.close();
  109. }
  110. catch (e) {
  111. errorSpan.addClass('active');
  112. errorSpan.setText(`Error importing style settings: ${e}`);
  113. }
  114. }
  115. else {
  116. errorSpan.addClass('active');
  117. errorSpan.setText(`Error importing style settings: config is empty`);
  118. }
  119. });
  120. // Build a file input
  121. setting.controlEl.createEl('input', {
  122. cls: 'style-settings-import-input',
  123. attr: {
  124. id: 'style-settings-import-input',
  125. name: 'style-settings-import-input',
  126. type: 'file',
  127. accept: '.json',
  128. },
  129. }, (importInput) => {
  130. // Set up a FileReader so we can parse the file contents
  131. importInput.addEventListener('change', (e) => {
  132. const reader = new FileReader();
  133. reader.onload = (e) => __awaiter(this, void 0, void 0, function* () {
  134. yield importAndClose(e.target.result.toString().trim());
  135. });
  136. reader.readAsText(e.target.files[0]);
  137. });
  138. });
  139. // Build a label we will style as a link
  140. setting.controlEl.createEl('label', {
  141. cls: 'style-settings-import-label',
  142. text: 'Import from file',
  143. attr: {
  144. for: 'style-settings-import-input',
  145. },
  146. });
  147. new obsidian.TextAreaComponent(contentEl)
  148. .setPlaceholder('Paste config here...')
  149. .then((ta) => {
  150. new obsidian.ButtonComponent(contentEl)
  151. .setButtonText('Save')
  152. .onClick(() => __awaiter(this, void 0, void 0, function* () {
  153. yield importAndClose(ta.getValue().trim());
  154. }));
  155. });
  156. });
  157. }
  158. onClose() {
  159. const { contentEl } = this;
  160. contentEl.empty();
  161. }
  162. }
  163. const SettingType = {
  164. HEADING: 'heading',
  165. INFO_TEXT: 'info-text',
  166. CLASS_TOGGLE: 'class-toggle',
  167. CLASS_SELECT: 'class-select',
  168. VARIABLE_TEXT: 'variable-text',
  169. VARIABLE_NUMBER: 'variable-number',
  170. VARIABLE_NUMBER_SLIDER: 'variable-number-slider',
  171. VARIABLE_SELECT: 'variable-select',
  172. VARIABLE_COLOR: 'variable-color',
  173. VARIABLE_THEMED_COLOR: 'variable-themed-color',
  174. COLOR_GRADIENT: 'color-gradient',
  175. };
  176. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  177. function getDefaultExportFromCjs (x) {
  178. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  179. }
  180. function createCommonjsModule(fn, basedir, module) {
  181. return module = {
  182. path: basedir,
  183. exports: {},
  184. require: function (path, base) {
  185. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  186. }
  187. }, fn(module, module.exports), module.exports;
  188. }
  189. function commonjsRequire () {
  190. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  191. }
  192. var chroma = createCommonjsModule(function (module, exports) {
  193. /**
  194. * chroma.js - JavaScript library for color conversions
  195. *
  196. * Copyright (c) 2011-2019, Gregor Aisch
  197. * All rights reserved.
  198. *
  199. * Redistribution and use in source and binary forms, with or without
  200. * modification, are permitted provided that the following conditions are met:
  201. *
  202. * 1. Redistributions of source code must retain the above copyright notice, this
  203. * list of conditions and the following disclaimer.
  204. *
  205. * 2. Redistributions in binary form must reproduce the above copyright notice,
  206. * this list of conditions and the following disclaimer in the documentation
  207. * and/or other materials provided with the distribution.
  208. *
  209. * 3. The name Gregor Aisch may not be used to endorse or promote products
  210. * derived from this software without specific prior written permission.
  211. *
  212. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  213. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  214. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  215. * DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  216. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  217. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  218. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  219. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  220. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  221. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  222. *
  223. * -------------------------------------------------------
  224. *
  225. * chroma.js includes colors from colorbrewer2.org, which are released under
  226. * the following license:
  227. *
  228. * Copyright (c) 2002 Cynthia Brewer, Mark Harrower,
  229. * and The Pennsylvania State University.
  230. *
  231. * Licensed under the Apache License, Version 2.0 (the "License");
  232. * you may not use this file except in compliance with the License.
  233. * You may obtain a copy of the License at
  234. * http://www.apache.org/licenses/LICENSE-2.0
  235. *
  236. * Unless required by applicable law or agreed to in writing,
  237. * software distributed under the License is distributed on an
  238. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  239. * either express or implied. See the License for the specific
  240. * language governing permissions and limitations under the License.
  241. *
  242. * ------------------------------------------------------
  243. *
  244. * Named colors are taken from X11 Color Names.
  245. * http://www.w3.org/TR/css3-color/#svg-color
  246. *
  247. * @preserve
  248. */
  249. (function (global, factory) {
  250. module.exports = factory() ;
  251. }(commonjsGlobal, (function () {
  252. var limit = function (x, min, max) {
  253. if ( min === void 0 ) min=0;
  254. if ( max === void 0 ) max=1;
  255. return x < min ? min : x > max ? max : x;
  256. };
  257. var clip_rgb = function (rgb) {
  258. rgb._clipped = false;
  259. rgb._unclipped = rgb.slice(0);
  260. for (var i=0; i<=3; i++) {
  261. if (i < 3) {
  262. if (rgb[i] < 0 || rgb[i] > 255) { rgb._clipped = true; }
  263. rgb[i] = limit(rgb[i], 0, 255);
  264. } else if (i === 3) {
  265. rgb[i] = limit(rgb[i], 0, 1);
  266. }
  267. }
  268. return rgb;
  269. };
  270. // ported from jQuery's $.type
  271. var classToType = {};
  272. for (var i = 0, list = ['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Undefined', 'Null']; i < list.length; i += 1) {
  273. var name = list[i];
  274. classToType[("[object " + name + "]")] = name.toLowerCase();
  275. }
  276. var type = function(obj) {
  277. return classToType[Object.prototype.toString.call(obj)] || "object";
  278. };
  279. var unpack = function (args, keyOrder) {
  280. if ( keyOrder === void 0 ) keyOrder=null;
  281. // if called with more than 3 arguments, we return the arguments
  282. if (args.length >= 3) { return Array.prototype.slice.call(args); }
  283. // with less than 3 args we check if first arg is object
  284. // and use the keyOrder string to extract and sort properties
  285. if (type(args[0]) == 'object' && keyOrder) {
  286. return keyOrder.split('')
  287. .filter(function (k) { return args[0][k] !== undefined; })
  288. .map(function (k) { return args[0][k]; });
  289. }
  290. // otherwise we just return the first argument
  291. // (which we suppose is an array of args)
  292. return args[0];
  293. };
  294. var last = function (args) {
  295. if (args.length < 2) { return null; }
  296. var l = args.length-1;
  297. if (type(args[l]) == 'string') { return args[l].toLowerCase(); }
  298. return null;
  299. };
  300. var PI = Math.PI;
  301. var utils = {
  302. clip_rgb: clip_rgb,
  303. limit: limit,
  304. type: type,
  305. unpack: unpack,
  306. last: last,
  307. PI: PI,
  308. TWOPI: PI*2,
  309. PITHIRD: PI/3,
  310. DEG2RAD: PI / 180,
  311. RAD2DEG: 180 / PI
  312. };
  313. var input = {
  314. format: {},
  315. autodetect: []
  316. };
  317. var last$1 = utils.last;
  318. var clip_rgb$1 = utils.clip_rgb;
  319. var type$1 = utils.type;
  320. var Color = function Color() {
  321. var args = [], len = arguments.length;
  322. while ( len-- ) args[ len ] = arguments[ len ];
  323. var me = this;
  324. if (type$1(args[0]) === 'object' &&
  325. args[0].constructor &&
  326. args[0].constructor === this.constructor) {
  327. // the argument is already a Color instance
  328. return args[0];
  329. }
  330. // last argument could be the mode
  331. var mode = last$1(args);
  332. var autodetect = false;
  333. if (!mode) {
  334. autodetect = true;
  335. if (!input.sorted) {
  336. input.autodetect = input.autodetect.sort(function (a,b) { return b.p - a.p; });
  337. input.sorted = true;
  338. }
  339. // auto-detect format
  340. for (var i = 0, list = input.autodetect; i < list.length; i += 1) {
  341. var chk = list[i];
  342. mode = chk.test.apply(chk, args);
  343. if (mode) { break; }
  344. }
  345. }
  346. if (input.format[mode]) {
  347. var rgb = input.format[mode].apply(null, autodetect ? args : args.slice(0,-1));
  348. me._rgb = clip_rgb$1(rgb);
  349. } else {
  350. throw new Error('unknown format: '+args);
  351. }
  352. // add alpha channel
  353. if (me._rgb.length === 3) { me._rgb.push(1); }
  354. };
  355. Color.prototype.toString = function toString () {
  356. if (type$1(this.hex) == 'function') { return this.hex(); }
  357. return ("[" + (this._rgb.join(',')) + "]");
  358. };
  359. var Color_1 = Color;
  360. var chroma = function () {
  361. var args = [], len = arguments.length;
  362. while ( len-- ) args[ len ] = arguments[ len ];
  363. return new (Function.prototype.bind.apply( chroma.Color, [ null ].concat( args) ));
  364. };
  365. chroma.Color = Color_1;
  366. chroma.version = '2.1.2';
  367. var chroma_1 = chroma;
  368. var unpack$1 = utils.unpack;
  369. var max = Math.max;
  370. var rgb2cmyk = function () {
  371. var args = [], len = arguments.length;
  372. while ( len-- ) args[ len ] = arguments[ len ];
  373. var ref = unpack$1(args, 'rgb');
  374. var r = ref[0];
  375. var g = ref[1];
  376. var b = ref[2];
  377. r = r / 255;
  378. g = g / 255;
  379. b = b / 255;
  380. var k = 1 - max(r,max(g,b));
  381. var f = k < 1 ? 1 / (1-k) : 0;
  382. var c = (1-r-k) * f;
  383. var m = (1-g-k) * f;
  384. var y = (1-b-k) * f;
  385. return [c,m,y,k];
  386. };
  387. var rgb2cmyk_1 = rgb2cmyk;
  388. var unpack$2 = utils.unpack;
  389. var cmyk2rgb = function () {
  390. var args = [], len = arguments.length;
  391. while ( len-- ) args[ len ] = arguments[ len ];
  392. args = unpack$2(args, 'cmyk');
  393. var c = args[0];
  394. var m = args[1];
  395. var y = args[2];
  396. var k = args[3];
  397. var alpha = args.length > 4 ? args[4] : 1;
  398. if (k === 1) { return [0,0,0,alpha]; }
  399. return [
  400. c >= 1 ? 0 : 255 * (1-c) * (1-k), // r
  401. m >= 1 ? 0 : 255 * (1-m) * (1-k), // g
  402. y >= 1 ? 0 : 255 * (1-y) * (1-k), // b
  403. alpha
  404. ];
  405. };
  406. var cmyk2rgb_1 = cmyk2rgb;
  407. var unpack$3 = utils.unpack;
  408. var type$2 = utils.type;
  409. Color_1.prototype.cmyk = function() {
  410. return rgb2cmyk_1(this._rgb);
  411. };
  412. chroma_1.cmyk = function () {
  413. var args = [], len = arguments.length;
  414. while ( len-- ) args[ len ] = arguments[ len ];
  415. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['cmyk']) ));
  416. };
  417. input.format.cmyk = cmyk2rgb_1;
  418. input.autodetect.push({
  419. p: 2,
  420. test: function () {
  421. var args = [], len = arguments.length;
  422. while ( len-- ) args[ len ] = arguments[ len ];
  423. args = unpack$3(args, 'cmyk');
  424. if (type$2(args) === 'array' && args.length === 4) {
  425. return 'cmyk';
  426. }
  427. }
  428. });
  429. var unpack$4 = utils.unpack;
  430. var last$2 = utils.last;
  431. var rnd = function (a) { return Math.round(a*100)/100; };
  432. /*
  433. * supported arguments:
  434. * - hsl2css(h,s,l)
  435. * - hsl2css(h,s,l,a)
  436. * - hsl2css([h,s,l], mode)
  437. * - hsl2css([h,s,l,a], mode)
  438. * - hsl2css({h,s,l,a}, mode)
  439. */
  440. var hsl2css = function () {
  441. var args = [], len = arguments.length;
  442. while ( len-- ) args[ len ] = arguments[ len ];
  443. var hsla = unpack$4(args, 'hsla');
  444. var mode = last$2(args) || 'lsa';
  445. hsla[0] = rnd(hsla[0] || 0);
  446. hsla[1] = rnd(hsla[1]*100) + '%';
  447. hsla[2] = rnd(hsla[2]*100) + '%';
  448. if (mode === 'hsla' || (hsla.length > 3 && hsla[3]<1)) {
  449. hsla[3] = hsla.length > 3 ? hsla[3] : 1;
  450. mode = 'hsla';
  451. } else {
  452. hsla.length = 3;
  453. }
  454. return (mode + "(" + (hsla.join(',')) + ")");
  455. };
  456. var hsl2css_1 = hsl2css;
  457. var unpack$5 = utils.unpack;
  458. /*
  459. * supported arguments:
  460. * - rgb2hsl(r,g,b)
  461. * - rgb2hsl(r,g,b,a)
  462. * - rgb2hsl([r,g,b])
  463. * - rgb2hsl([r,g,b,a])
  464. * - rgb2hsl({r,g,b,a})
  465. */
  466. var rgb2hsl = function () {
  467. var args = [], len = arguments.length;
  468. while ( len-- ) args[ len ] = arguments[ len ];
  469. args = unpack$5(args, 'rgba');
  470. var r = args[0];
  471. var g = args[1];
  472. var b = args[2];
  473. r /= 255;
  474. g /= 255;
  475. b /= 255;
  476. var min = Math.min(r, g, b);
  477. var max = Math.max(r, g, b);
  478. var l = (max + min) / 2;
  479. var s, h;
  480. if (max === min){
  481. s = 0;
  482. h = Number.NaN;
  483. } else {
  484. s = l < 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min);
  485. }
  486. if (r == max) { h = (g - b) / (max - min); }
  487. else if (g == max) { h = 2 + (b - r) / (max - min); }
  488. else if (b == max) { h = 4 + (r - g) / (max - min); }
  489. h *= 60;
  490. if (h < 0) { h += 360; }
  491. if (args.length>3 && args[3]!==undefined) { return [h,s,l,args[3]]; }
  492. return [h,s,l];
  493. };
  494. var rgb2hsl_1 = rgb2hsl;
  495. var unpack$6 = utils.unpack;
  496. var last$3 = utils.last;
  497. var round = Math.round;
  498. /*
  499. * supported arguments:
  500. * - rgb2css(r,g,b)
  501. * - rgb2css(r,g,b,a)
  502. * - rgb2css([r,g,b], mode)
  503. * - rgb2css([r,g,b,a], mode)
  504. * - rgb2css({r,g,b,a}, mode)
  505. */
  506. var rgb2css = function () {
  507. var args = [], len = arguments.length;
  508. while ( len-- ) args[ len ] = arguments[ len ];
  509. var rgba = unpack$6(args, 'rgba');
  510. var mode = last$3(args) || 'rgb';
  511. if (mode.substr(0,3) == 'hsl') {
  512. return hsl2css_1(rgb2hsl_1(rgba), mode);
  513. }
  514. rgba[0] = round(rgba[0]);
  515. rgba[1] = round(rgba[1]);
  516. rgba[2] = round(rgba[2]);
  517. if (mode === 'rgba' || (rgba.length > 3 && rgba[3]<1)) {
  518. rgba[3] = rgba.length > 3 ? rgba[3] : 1;
  519. mode = 'rgba';
  520. }
  521. return (mode + "(" + (rgba.slice(0,mode==='rgb'?3:4).join(',')) + ")");
  522. };
  523. var rgb2css_1 = rgb2css;
  524. var unpack$7 = utils.unpack;
  525. var round$1 = Math.round;
  526. var hsl2rgb = function () {
  527. var assign;
  528. var args = [], len = arguments.length;
  529. while ( len-- ) args[ len ] = arguments[ len ];
  530. args = unpack$7(args, 'hsl');
  531. var h = args[0];
  532. var s = args[1];
  533. var l = args[2];
  534. var r,g,b;
  535. if (s === 0) {
  536. r = g = b = l*255;
  537. } else {
  538. var t3 = [0,0,0];
  539. var c = [0,0,0];
  540. var t2 = l < 0.5 ? l * (1+s) : l+s-l*s;
  541. var t1 = 2 * l - t2;
  542. var h_ = h / 360;
  543. t3[0] = h_ + 1/3;
  544. t3[1] = h_;
  545. t3[2] = h_ - 1/3;
  546. for (var i=0; i<3; i++) {
  547. if (t3[i] < 0) { t3[i] += 1; }
  548. if (t3[i] > 1) { t3[i] -= 1; }
  549. if (6 * t3[i] < 1)
  550. { c[i] = t1 + (t2 - t1) * 6 * t3[i]; }
  551. else if (2 * t3[i] < 1)
  552. { c[i] = t2; }
  553. else if (3 * t3[i] < 2)
  554. { c[i] = t1 + (t2 - t1) * ((2 / 3) - t3[i]) * 6; }
  555. else
  556. { c[i] = t1; }
  557. }
  558. (assign = [round$1(c[0]*255),round$1(c[1]*255),round$1(c[2]*255)], r = assign[0], g = assign[1], b = assign[2]);
  559. }
  560. if (args.length > 3) {
  561. // keep alpha channel
  562. return [r,g,b,args[3]];
  563. }
  564. return [r,g,b,1];
  565. };
  566. var hsl2rgb_1 = hsl2rgb;
  567. var RE_RGB = /^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/;
  568. var RE_RGBA = /^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/;
  569. var RE_RGB_PCT = /^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/;
  570. var RE_RGBA_PCT = /^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/;
  571. var RE_HSL = /^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/;
  572. var RE_HSLA = /^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/;
  573. var round$2 = Math.round;
  574. var css2rgb = function (css) {
  575. css = css.toLowerCase().trim();
  576. var m;
  577. if (input.format.named) {
  578. try {
  579. return input.format.named(css);
  580. } catch (e) {
  581. // eslint-disable-next-line
  582. }
  583. }
  584. // rgb(250,20,0)
  585. if ((m = css.match(RE_RGB))) {
  586. var rgb = m.slice(1,4);
  587. for (var i=0; i<3; i++) {
  588. rgb[i] = +rgb[i];
  589. }
  590. rgb[3] = 1; // default alpha
  591. return rgb;
  592. }
  593. // rgba(250,20,0,0.4)
  594. if ((m = css.match(RE_RGBA))) {
  595. var rgb$1 = m.slice(1,5);
  596. for (var i$1=0; i$1<4; i$1++) {
  597. rgb$1[i$1] = +rgb$1[i$1];
  598. }
  599. return rgb$1;
  600. }
  601. // rgb(100%,0%,0%)
  602. if ((m = css.match(RE_RGB_PCT))) {
  603. var rgb$2 = m.slice(1,4);
  604. for (var i$2=0; i$2<3; i$2++) {
  605. rgb$2[i$2] = round$2(rgb$2[i$2] * 2.55);
  606. }
  607. rgb$2[3] = 1; // default alpha
  608. return rgb$2;
  609. }
  610. // rgba(100%,0%,0%,0.4)
  611. if ((m = css.match(RE_RGBA_PCT))) {
  612. var rgb$3 = m.slice(1,5);
  613. for (var i$3=0; i$3<3; i$3++) {
  614. rgb$3[i$3] = round$2(rgb$3[i$3] * 2.55);
  615. }
  616. rgb$3[3] = +rgb$3[3];
  617. return rgb$3;
  618. }
  619. // hsl(0,100%,50%)
  620. if ((m = css.match(RE_HSL))) {
  621. var hsl = m.slice(1,4);
  622. hsl[1] *= 0.01;
  623. hsl[2] *= 0.01;
  624. var rgb$4 = hsl2rgb_1(hsl);
  625. rgb$4[3] = 1;
  626. return rgb$4;
  627. }
  628. // hsla(0,100%,50%,0.5)
  629. if ((m = css.match(RE_HSLA))) {
  630. var hsl$1 = m.slice(1,4);
  631. hsl$1[1] *= 0.01;
  632. hsl$1[2] *= 0.01;
  633. var rgb$5 = hsl2rgb_1(hsl$1);
  634. rgb$5[3] = +m[4]; // default alpha = 1
  635. return rgb$5;
  636. }
  637. };
  638. css2rgb.test = function (s) {
  639. return RE_RGB.test(s) ||
  640. RE_RGBA.test(s) ||
  641. RE_RGB_PCT.test(s) ||
  642. RE_RGBA_PCT.test(s) ||
  643. RE_HSL.test(s) ||
  644. RE_HSLA.test(s);
  645. };
  646. var css2rgb_1 = css2rgb;
  647. var type$3 = utils.type;
  648. Color_1.prototype.css = function(mode) {
  649. return rgb2css_1(this._rgb, mode);
  650. };
  651. chroma_1.css = function () {
  652. var args = [], len = arguments.length;
  653. while ( len-- ) args[ len ] = arguments[ len ];
  654. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['css']) ));
  655. };
  656. input.format.css = css2rgb_1;
  657. input.autodetect.push({
  658. p: 5,
  659. test: function (h) {
  660. var rest = [], len = arguments.length - 1;
  661. while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ];
  662. if (!rest.length && type$3(h) === 'string' && css2rgb_1.test(h)) {
  663. return 'css';
  664. }
  665. }
  666. });
  667. var unpack$8 = utils.unpack;
  668. input.format.gl = function () {
  669. var args = [], len = arguments.length;
  670. while ( len-- ) args[ len ] = arguments[ len ];
  671. var rgb = unpack$8(args, 'rgba');
  672. rgb[0] *= 255;
  673. rgb[1] *= 255;
  674. rgb[2] *= 255;
  675. return rgb;
  676. };
  677. chroma_1.gl = function () {
  678. var args = [], len = arguments.length;
  679. while ( len-- ) args[ len ] = arguments[ len ];
  680. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['gl']) ));
  681. };
  682. Color_1.prototype.gl = function() {
  683. var rgb = this._rgb;
  684. return [rgb[0]/255, rgb[1]/255, rgb[2]/255, rgb[3]];
  685. };
  686. var unpack$9 = utils.unpack;
  687. var rgb2hcg = function () {
  688. var args = [], len = arguments.length;
  689. while ( len-- ) args[ len ] = arguments[ len ];
  690. var ref = unpack$9(args, 'rgb');
  691. var r = ref[0];
  692. var g = ref[1];
  693. var b = ref[2];
  694. var min = Math.min(r, g, b);
  695. var max = Math.max(r, g, b);
  696. var delta = max - min;
  697. var c = delta * 100 / 255;
  698. var _g = min / (255 - delta) * 100;
  699. var h;
  700. if (delta === 0) {
  701. h = Number.NaN;
  702. } else {
  703. if (r === max) { h = (g - b) / delta; }
  704. if (g === max) { h = 2+(b - r) / delta; }
  705. if (b === max) { h = 4+(r - g) / delta; }
  706. h *= 60;
  707. if (h < 0) { h += 360; }
  708. }
  709. return [h, c, _g];
  710. };
  711. var rgb2hcg_1 = rgb2hcg;
  712. var unpack$a = utils.unpack;
  713. var floor = Math.floor;
  714. /*
  715. * this is basically just HSV with some minor tweaks
  716. *
  717. * hue.. [0..360]
  718. * chroma .. [0..1]
  719. * grayness .. [0..1]
  720. */
  721. var hcg2rgb = function () {
  722. var assign, assign$1, assign$2, assign$3, assign$4, assign$5;
  723. var args = [], len = arguments.length;
  724. while ( len-- ) args[ len ] = arguments[ len ];
  725. args = unpack$a(args, 'hcg');
  726. var h = args[0];
  727. var c = args[1];
  728. var _g = args[2];
  729. var r,g,b;
  730. _g = _g * 255;
  731. var _c = c * 255;
  732. if (c === 0) {
  733. r = g = b = _g;
  734. } else {
  735. if (h === 360) { h = 0; }
  736. if (h > 360) { h -= 360; }
  737. if (h < 0) { h += 360; }
  738. h /= 60;
  739. var i = floor(h);
  740. var f = h - i;
  741. var p = _g * (1 - c);
  742. var q = p + _c * (1 - f);
  743. var t = p + _c * f;
  744. var v = p + _c;
  745. switch (i) {
  746. case 0: (assign = [v, t, p], r = assign[0], g = assign[1], b = assign[2]); break
  747. case 1: (assign$1 = [q, v, p], r = assign$1[0], g = assign$1[1], b = assign$1[2]); break
  748. case 2: (assign$2 = [p, v, t], r = assign$2[0], g = assign$2[1], b = assign$2[2]); break
  749. case 3: (assign$3 = [p, q, v], r = assign$3[0], g = assign$3[1], b = assign$3[2]); break
  750. case 4: (assign$4 = [t, p, v], r = assign$4[0], g = assign$4[1], b = assign$4[2]); break
  751. case 5: (assign$5 = [v, p, q], r = assign$5[0], g = assign$5[1], b = assign$5[2]); break
  752. }
  753. }
  754. return [r, g, b, args.length > 3 ? args[3] : 1];
  755. };
  756. var hcg2rgb_1 = hcg2rgb;
  757. var unpack$b = utils.unpack;
  758. var type$4 = utils.type;
  759. Color_1.prototype.hcg = function() {
  760. return rgb2hcg_1(this._rgb);
  761. };
  762. chroma_1.hcg = function () {
  763. var args = [], len = arguments.length;
  764. while ( len-- ) args[ len ] = arguments[ len ];
  765. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hcg']) ));
  766. };
  767. input.format.hcg = hcg2rgb_1;
  768. input.autodetect.push({
  769. p: 1,
  770. test: function () {
  771. var args = [], len = arguments.length;
  772. while ( len-- ) args[ len ] = arguments[ len ];
  773. args = unpack$b(args, 'hcg');
  774. if (type$4(args) === 'array' && args.length === 3) {
  775. return 'hcg';
  776. }
  777. }
  778. });
  779. var unpack$c = utils.unpack;
  780. var last$4 = utils.last;
  781. var round$3 = Math.round;
  782. var rgb2hex = function () {
  783. var args = [], len = arguments.length;
  784. while ( len-- ) args[ len ] = arguments[ len ];
  785. var ref = unpack$c(args, 'rgba');
  786. var r = ref[0];
  787. var g = ref[1];
  788. var b = ref[2];
  789. var a = ref[3];
  790. var mode = last$4(args) || 'auto';
  791. if (a === undefined) { a = 1; }
  792. if (mode === 'auto') {
  793. mode = a < 1 ? 'rgba' : 'rgb';
  794. }
  795. r = round$3(r);
  796. g = round$3(g);
  797. b = round$3(b);
  798. var u = r << 16 | g << 8 | b;
  799. var str = "000000" + u.toString(16); //#.toUpperCase();
  800. str = str.substr(str.length - 6);
  801. var hxa = '0' + round$3(a * 255).toString(16);
  802. hxa = hxa.substr(hxa.length - 2);
  803. switch (mode.toLowerCase()) {
  804. case 'rgba': return ("#" + str + hxa);
  805. case 'argb': return ("#" + hxa + str);
  806. default: return ("#" + str);
  807. }
  808. };
  809. var rgb2hex_1 = rgb2hex;
  810. var RE_HEX = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  811. var RE_HEXA = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/;
  812. var hex2rgb = function (hex) {
  813. if (hex.match(RE_HEX)) {
  814. // remove optional leading #
  815. if (hex.length === 4 || hex.length === 7) {
  816. hex = hex.substr(1);
  817. }
  818. // expand short-notation to full six-digit
  819. if (hex.length === 3) {
  820. hex = hex.split('');
  821. hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  822. }
  823. var u = parseInt(hex, 16);
  824. var r = u >> 16;
  825. var g = u >> 8 & 0xFF;
  826. var b = u & 0xFF;
  827. return [r,g,b,1];
  828. }
  829. // match rgba hex format, eg #FF000077
  830. if (hex.match(RE_HEXA)) {
  831. if (hex.length === 5 || hex.length === 9) {
  832. // remove optional leading #
  833. hex = hex.substr(1);
  834. }
  835. // expand short-notation to full eight-digit
  836. if (hex.length === 4) {
  837. hex = hex.split('');
  838. hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]+hex[3]+hex[3];
  839. }
  840. var u$1 = parseInt(hex, 16);
  841. var r$1 = u$1 >> 24 & 0xFF;
  842. var g$1 = u$1 >> 16 & 0xFF;
  843. var b$1 = u$1 >> 8 & 0xFF;
  844. var a = Math.round((u$1 & 0xFF) / 0xFF * 100) / 100;
  845. return [r$1,g$1,b$1,a];
  846. }
  847. // we used to check for css colors here
  848. // if _input.css? and rgb = _input.css hex
  849. // return rgb
  850. throw new Error(("unknown hex color: " + hex));
  851. };
  852. var hex2rgb_1 = hex2rgb;
  853. var type$5 = utils.type;
  854. Color_1.prototype.hex = function(mode) {
  855. return rgb2hex_1(this._rgb, mode);
  856. };
  857. chroma_1.hex = function () {
  858. var args = [], len = arguments.length;
  859. while ( len-- ) args[ len ] = arguments[ len ];
  860. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hex']) ));
  861. };
  862. input.format.hex = hex2rgb_1;
  863. input.autodetect.push({
  864. p: 4,
  865. test: function (h) {
  866. var rest = [], len = arguments.length - 1;
  867. while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ];
  868. if (!rest.length && type$5(h) === 'string' && [3,4,5,6,7,8,9].indexOf(h.length) >= 0) {
  869. return 'hex';
  870. }
  871. }
  872. });
  873. var unpack$d = utils.unpack;
  874. var TWOPI = utils.TWOPI;
  875. var min = Math.min;
  876. var sqrt = Math.sqrt;
  877. var acos = Math.acos;
  878. var rgb2hsi = function () {
  879. var args = [], len = arguments.length;
  880. while ( len-- ) args[ len ] = arguments[ len ];
  881. /*
  882. borrowed from here:
  883. http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/rgb2hsi.cpp
  884. */
  885. var ref = unpack$d(args, 'rgb');
  886. var r = ref[0];
  887. var g = ref[1];
  888. var b = ref[2];
  889. r /= 255;
  890. g /= 255;
  891. b /= 255;
  892. var h;
  893. var min_ = min(r,g,b);
  894. var i = (r+g+b) / 3;
  895. var s = i > 0 ? 1 - min_/i : 0;
  896. if (s === 0) {
  897. h = NaN;
  898. } else {
  899. h = ((r-g)+(r-b)) / 2;
  900. h /= sqrt((r-g)*(r-g) + (r-b)*(g-b));
  901. h = acos(h);
  902. if (b > g) {
  903. h = TWOPI - h;
  904. }
  905. h /= TWOPI;
  906. }
  907. return [h*360,s,i];
  908. };
  909. var rgb2hsi_1 = rgb2hsi;
  910. var unpack$e = utils.unpack;
  911. var limit$1 = utils.limit;
  912. var TWOPI$1 = utils.TWOPI;
  913. var PITHIRD = utils.PITHIRD;
  914. var cos = Math.cos;
  915. /*
  916. * hue [0..360]
  917. * saturation [0..1]
  918. * intensity [0..1]
  919. */
  920. var hsi2rgb = function () {
  921. var args = [], len = arguments.length;
  922. while ( len-- ) args[ len ] = arguments[ len ];
  923. /*
  924. borrowed from here:
  925. http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/hsi2rgb.cpp
  926. */
  927. args = unpack$e(args, 'hsi');
  928. var h = args[0];
  929. var s = args[1];
  930. var i = args[2];
  931. var r,g,b;
  932. if (isNaN(h)) { h = 0; }
  933. if (isNaN(s)) { s = 0; }
  934. // normalize hue
  935. if (h > 360) { h -= 360; }
  936. if (h < 0) { h += 360; }
  937. h /= 360;
  938. if (h < 1/3) {
  939. b = (1-s)/3;
  940. r = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3;
  941. g = 1 - (b+r);
  942. } else if (h < 2/3) {
  943. h -= 1/3;
  944. r = (1-s)/3;
  945. g = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3;
  946. b = 1 - (r+g);
  947. } else {
  948. h -= 2/3;
  949. g = (1-s)/3;
  950. b = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3;
  951. r = 1 - (g+b);
  952. }
  953. r = limit$1(i*r*3);
  954. g = limit$1(i*g*3);
  955. b = limit$1(i*b*3);
  956. return [r*255, g*255, b*255, args.length > 3 ? args[3] : 1];
  957. };
  958. var hsi2rgb_1 = hsi2rgb;
  959. var unpack$f = utils.unpack;
  960. var type$6 = utils.type;
  961. Color_1.prototype.hsi = function() {
  962. return rgb2hsi_1(this._rgb);
  963. };
  964. chroma_1.hsi = function () {
  965. var args = [], len = arguments.length;
  966. while ( len-- ) args[ len ] = arguments[ len ];
  967. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsi']) ));
  968. };
  969. input.format.hsi = hsi2rgb_1;
  970. input.autodetect.push({
  971. p: 2,
  972. test: function () {
  973. var args = [], len = arguments.length;
  974. while ( len-- ) args[ len ] = arguments[ len ];
  975. args = unpack$f(args, 'hsi');
  976. if (type$6(args) === 'array' && args.length === 3) {
  977. return 'hsi';
  978. }
  979. }
  980. });
  981. var unpack$g = utils.unpack;
  982. var type$7 = utils.type;
  983. Color_1.prototype.hsl = function() {
  984. return rgb2hsl_1(this._rgb);
  985. };
  986. chroma_1.hsl = function () {
  987. var args = [], len = arguments.length;
  988. while ( len-- ) args[ len ] = arguments[ len ];
  989. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsl']) ));
  990. };
  991. input.format.hsl = hsl2rgb_1;
  992. input.autodetect.push({
  993. p: 2,
  994. test: function () {
  995. var args = [], len = arguments.length;
  996. while ( len-- ) args[ len ] = arguments[ len ];
  997. args = unpack$g(args, 'hsl');
  998. if (type$7(args) === 'array' && args.length === 3) {
  999. return 'hsl';
  1000. }
  1001. }
  1002. });
  1003. var unpack$h = utils.unpack;
  1004. var min$1 = Math.min;
  1005. var max$1 = Math.max;
  1006. /*
  1007. * supported arguments:
  1008. * - rgb2hsv(r,g,b)
  1009. * - rgb2hsv([r,g,b])
  1010. * - rgb2hsv({r,g,b})
  1011. */
  1012. var rgb2hsl$1 = function () {
  1013. var args = [], len = arguments.length;
  1014. while ( len-- ) args[ len ] = arguments[ len ];
  1015. args = unpack$h(args, 'rgb');
  1016. var r = args[0];
  1017. var g = args[1];
  1018. var b = args[2];
  1019. var min_ = min$1(r, g, b);
  1020. var max_ = max$1(r, g, b);
  1021. var delta = max_ - min_;
  1022. var h,s,v;
  1023. v = max_ / 255.0;
  1024. if (max_ === 0) {
  1025. h = Number.NaN;
  1026. s = 0;
  1027. } else {
  1028. s = delta / max_;
  1029. if (r === max_) { h = (g - b) / delta; }
  1030. if (g === max_) { h = 2+(b - r) / delta; }
  1031. if (b === max_) { h = 4+(r - g) / delta; }
  1032. h *= 60;
  1033. if (h < 0) { h += 360; }
  1034. }
  1035. return [h, s, v]
  1036. };
  1037. var rgb2hsv = rgb2hsl$1;
  1038. var unpack$i = utils.unpack;
  1039. var floor$1 = Math.floor;
  1040. var hsv2rgb = function () {
  1041. var assign, assign$1, assign$2, assign$3, assign$4, assign$5;
  1042. var args = [], len = arguments.length;
  1043. while ( len-- ) args[ len ] = arguments[ len ];
  1044. args = unpack$i(args, 'hsv');
  1045. var h = args[0];
  1046. var s = args[1];
  1047. var v = args[2];
  1048. var r,g,b;
  1049. v *= 255;
  1050. if (s === 0) {
  1051. r = g = b = v;
  1052. } else {
  1053. if (h === 360) { h = 0; }
  1054. if (h > 360) { h -= 360; }
  1055. if (h < 0) { h += 360; }
  1056. h /= 60;
  1057. var i = floor$1(h);
  1058. var f = h - i;
  1059. var p = v * (1 - s);
  1060. var q = v * (1 - s * f);
  1061. var t = v * (1 - s * (1 - f));
  1062. switch (i) {
  1063. case 0: (assign = [v, t, p], r = assign[0], g = assign[1], b = assign[2]); break
  1064. case 1: (assign$1 = [q, v, p], r = assign$1[0], g = assign$1[1], b = assign$1[2]); break
  1065. case 2: (assign$2 = [p, v, t], r = assign$2[0], g = assign$2[1], b = assign$2[2]); break
  1066. case 3: (assign$3 = [p, q, v], r = assign$3[0], g = assign$3[1], b = assign$3[2]); break
  1067. case 4: (assign$4 = [t, p, v], r = assign$4[0], g = assign$4[1], b = assign$4[2]); break
  1068. case 5: (assign$5 = [v, p, q], r = assign$5[0], g = assign$5[1], b = assign$5[2]); break
  1069. }
  1070. }
  1071. return [r,g,b,args.length > 3?args[3]:1];
  1072. };
  1073. var hsv2rgb_1 = hsv2rgb;
  1074. var unpack$j = utils.unpack;
  1075. var type$8 = utils.type;
  1076. Color_1.prototype.hsv = function() {
  1077. return rgb2hsv(this._rgb);
  1078. };
  1079. chroma_1.hsv = function () {
  1080. var args = [], len = arguments.length;
  1081. while ( len-- ) args[ len ] = arguments[ len ];
  1082. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsv']) ));
  1083. };
  1084. input.format.hsv = hsv2rgb_1;
  1085. input.autodetect.push({
  1086. p: 2,
  1087. test: function () {
  1088. var args = [], len = arguments.length;
  1089. while ( len-- ) args[ len ] = arguments[ len ];
  1090. args = unpack$j(args, 'hsv');
  1091. if (type$8(args) === 'array' && args.length === 3) {
  1092. return 'hsv';
  1093. }
  1094. }
  1095. });
  1096. var labConstants = {
  1097. // Corresponds roughly to RGB brighter/darker
  1098. Kn: 18,
  1099. // D65 standard referent
  1100. Xn: 0.950470,
  1101. Yn: 1,
  1102. Zn: 1.088830,
  1103. t0: 0.137931034, // 4 / 29
  1104. t1: 0.206896552, // 6 / 29
  1105. t2: 0.12841855, // 3 * t1 * t1
  1106. t3: 0.008856452, // t1 * t1 * t1
  1107. };
  1108. var unpack$k = utils.unpack;
  1109. var pow = Math.pow;
  1110. var rgb2lab = function () {
  1111. var args = [], len = arguments.length;
  1112. while ( len-- ) args[ len ] = arguments[ len ];
  1113. var ref = unpack$k(args, 'rgb');
  1114. var r = ref[0];
  1115. var g = ref[1];
  1116. var b = ref[2];
  1117. var ref$1 = rgb2xyz(r,g,b);
  1118. var x = ref$1[0];
  1119. var y = ref$1[1];
  1120. var z = ref$1[2];
  1121. var l = 116 * y - 16;
  1122. return [l < 0 ? 0 : l, 500 * (x - y), 200 * (y - z)];
  1123. };
  1124. var rgb_xyz = function (r) {
  1125. if ((r /= 255) <= 0.04045) { return r / 12.92; }
  1126. return pow((r + 0.055) / 1.055, 2.4);
  1127. };
  1128. var xyz_lab = function (t) {
  1129. if (t > labConstants.t3) { return pow(t, 1 / 3); }
  1130. return t / labConstants.t2 + labConstants.t0;
  1131. };
  1132. var rgb2xyz = function (r,g,b) {
  1133. r = rgb_xyz(r);
  1134. g = rgb_xyz(g);
  1135. b = rgb_xyz(b);
  1136. var x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / labConstants.Xn);
  1137. var y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / labConstants.Yn);
  1138. var z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / labConstants.Zn);
  1139. return [x,y,z];
  1140. };
  1141. var rgb2lab_1 = rgb2lab;
  1142. var unpack$l = utils.unpack;
  1143. var pow$1 = Math.pow;
  1144. /*
  1145. * L* [0..100]
  1146. * a [-100..100]
  1147. * b [-100..100]
  1148. */
  1149. var lab2rgb = function () {
  1150. var args = [], len = arguments.length;
  1151. while ( len-- ) args[ len ] = arguments[ len ];
  1152. args = unpack$l(args, 'lab');
  1153. var l = args[0];
  1154. var a = args[1];
  1155. var b = args[2];
  1156. var x,y,z, r,g,b_;
  1157. y = (l + 16) / 116;
  1158. x = isNaN(a) ? y : y + a / 500;
  1159. z = isNaN(b) ? y : y - b / 200;
  1160. y = labConstants.Yn * lab_xyz(y);
  1161. x = labConstants.Xn * lab_xyz(x);
  1162. z = labConstants.Zn * lab_xyz(z);
  1163. r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z); // D65 -> sRGB
  1164. g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
  1165. b_ = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
  1166. return [r,g,b_,args.length > 3 ? args[3] : 1];
  1167. };
  1168. var xyz_rgb = function (r) {
  1169. return 255 * (r <= 0.00304 ? 12.92 * r : 1.055 * pow$1(r, 1 / 2.4) - 0.055)
  1170. };
  1171. var lab_xyz = function (t) {
  1172. return t > labConstants.t1 ? t * t * t : labConstants.t2 * (t - labConstants.t0)
  1173. };
  1174. var lab2rgb_1 = lab2rgb;
  1175. var unpack$m = utils.unpack;
  1176. var type$9 = utils.type;
  1177. Color_1.prototype.lab = function() {
  1178. return rgb2lab_1(this._rgb);
  1179. };
  1180. chroma_1.lab = function () {
  1181. var args = [], len = arguments.length;
  1182. while ( len-- ) args[ len ] = arguments[ len ];
  1183. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['lab']) ));
  1184. };
  1185. input.format.lab = lab2rgb_1;
  1186. input.autodetect.push({
  1187. p: 2,
  1188. test: function () {
  1189. var args = [], len = arguments.length;
  1190. while ( len-- ) args[ len ] = arguments[ len ];
  1191. args = unpack$m(args, 'lab');
  1192. if (type$9(args) === 'array' && args.length === 3) {
  1193. return 'lab';
  1194. }
  1195. }
  1196. });
  1197. var unpack$n = utils.unpack;
  1198. var RAD2DEG = utils.RAD2DEG;
  1199. var sqrt$1 = Math.sqrt;
  1200. var atan2 = Math.atan2;
  1201. var round$4 = Math.round;
  1202. var lab2lch = function () {
  1203. var args = [], len = arguments.length;
  1204. while ( len-- ) args[ len ] = arguments[ len ];
  1205. var ref = unpack$n(args, 'lab');
  1206. var l = ref[0];
  1207. var a = ref[1];
  1208. var b = ref[2];
  1209. var c = sqrt$1(a * a + b * b);
  1210. var h = (atan2(b, a) * RAD2DEG + 360) % 360;
  1211. if (round$4(c*10000) === 0) { h = Number.NaN; }
  1212. return [l, c, h];
  1213. };
  1214. var lab2lch_1 = lab2lch;
  1215. var unpack$o = utils.unpack;
  1216. var rgb2lch = function () {
  1217. var args = [], len = arguments.length;
  1218. while ( len-- ) args[ len ] = arguments[ len ];
  1219. var ref = unpack$o(args, 'rgb');
  1220. var r = ref[0];
  1221. var g = ref[1];
  1222. var b = ref[2];
  1223. var ref$1 = rgb2lab_1(r,g,b);
  1224. var l = ref$1[0];
  1225. var a = ref$1[1];
  1226. var b_ = ref$1[2];
  1227. return lab2lch_1(l,a,b_);
  1228. };
  1229. var rgb2lch_1 = rgb2lch;
  1230. var unpack$p = utils.unpack;
  1231. var DEG2RAD = utils.DEG2RAD;
  1232. var sin = Math.sin;
  1233. var cos$1 = Math.cos;
  1234. var lch2lab = function () {
  1235. var args = [], len = arguments.length;
  1236. while ( len-- ) args[ len ] = arguments[ len ];
  1237. /*
  1238. Convert from a qualitative parameter h and a quantitative parameter l to a 24-bit pixel.
  1239. These formulas were invented by David Dalrymple to obtain maximum contrast without going
  1240. out of gamut if the parameters are in the range 0-1.
  1241. A saturation multiplier was added by Gregor Aisch
  1242. */
  1243. var ref = unpack$p(args, 'lch');
  1244. var l = ref[0];
  1245. var c = ref[1];
  1246. var h = ref[2];
  1247. if (isNaN(h)) { h = 0; }
  1248. h = h * DEG2RAD;
  1249. return [l, cos$1(h) * c, sin(h) * c]
  1250. };
  1251. var lch2lab_1 = lch2lab;
  1252. var unpack$q = utils.unpack;
  1253. var lch2rgb = function () {
  1254. var args = [], len = arguments.length;
  1255. while ( len-- ) args[ len ] = arguments[ len ];
  1256. args = unpack$q(args, 'lch');
  1257. var l = args[0];
  1258. var c = args[1];
  1259. var h = args[2];
  1260. var ref = lch2lab_1 (l,c,h);
  1261. var L = ref[0];
  1262. var a = ref[1];
  1263. var b_ = ref[2];
  1264. var ref$1 = lab2rgb_1 (L,a,b_);
  1265. var r = ref$1[0];
  1266. var g = ref$1[1];
  1267. var b = ref$1[2];
  1268. return [r, g, b, args.length > 3 ? args[3] : 1];
  1269. };
  1270. var lch2rgb_1 = lch2rgb;
  1271. var unpack$r = utils.unpack;
  1272. var hcl2rgb = function () {
  1273. var args = [], len = arguments.length;
  1274. while ( len-- ) args[ len ] = arguments[ len ];
  1275. var hcl = unpack$r(args, 'hcl').reverse();
  1276. return lch2rgb_1.apply(void 0, hcl);
  1277. };
  1278. var hcl2rgb_1 = hcl2rgb;
  1279. var unpack$s = utils.unpack;
  1280. var type$a = utils.type;
  1281. Color_1.prototype.lch = function() { return rgb2lch_1(this._rgb); };
  1282. Color_1.prototype.hcl = function() { return rgb2lch_1(this._rgb).reverse(); };
  1283. chroma_1.lch = function () {
  1284. var args = [], len = arguments.length;
  1285. while ( len-- ) args[ len ] = arguments[ len ];
  1286. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['lch']) ));
  1287. };
  1288. chroma_1.hcl = function () {
  1289. var args = [], len = arguments.length;
  1290. while ( len-- ) args[ len ] = arguments[ len ];
  1291. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hcl']) ));
  1292. };
  1293. input.format.lch = lch2rgb_1;
  1294. input.format.hcl = hcl2rgb_1;
  1295. ['lch','hcl'].forEach(function (m) { return input.autodetect.push({
  1296. p: 2,
  1297. test: function () {
  1298. var args = [], len = arguments.length;
  1299. while ( len-- ) args[ len ] = arguments[ len ];
  1300. args = unpack$s(args, m);
  1301. if (type$a(args) === 'array' && args.length === 3) {
  1302. return m;
  1303. }
  1304. }
  1305. }); });
  1306. /**
  1307. X11 color names
  1308. http://www.w3.org/TR/css3-color/#svg-color
  1309. */
  1310. var w3cx11 = {
  1311. aliceblue: '#f0f8ff',
  1312. antiquewhite: '#faebd7',
  1313. aqua: '#00ffff',
  1314. aquamarine: '#7fffd4',
  1315. azure: '#f0ffff',
  1316. beige: '#f5f5dc',
  1317. bisque: '#ffe4c4',
  1318. black: '#000000',
  1319. blanchedalmond: '#ffebcd',
  1320. blue: '#0000ff',
  1321. blueviolet: '#8a2be2',
  1322. brown: '#a52a2a',
  1323. burlywood: '#deb887',
  1324. cadetblue: '#5f9ea0',
  1325. chartreuse: '#7fff00',
  1326. chocolate: '#d2691e',
  1327. coral: '#ff7f50',
  1328. cornflower: '#6495ed',
  1329. cornflowerblue: '#6495ed',
  1330. cornsilk: '#fff8dc',
  1331. crimson: '#dc143c',
  1332. cyan: '#00ffff',
  1333. darkblue: '#00008b',
  1334. darkcyan: '#008b8b',
  1335. darkgoldenrod: '#b8860b',
  1336. darkgray: '#a9a9a9',
  1337. darkgreen: '#006400',
  1338. darkgrey: '#a9a9a9',
  1339. darkkhaki: '#bdb76b',
  1340. darkmagenta: '#8b008b',
  1341. darkolivegreen: '#556b2f',
  1342. darkorange: '#ff8c00',
  1343. darkorchid: '#9932cc',
  1344. darkred: '#8b0000',
  1345. darksalmon: '#e9967a',
  1346. darkseagreen: '#8fbc8f',
  1347. darkslateblue: '#483d8b',
  1348. darkslategray: '#2f4f4f',
  1349. darkslategrey: '#2f4f4f',
  1350. darkturquoise: '#00ced1',
  1351. darkviolet: '#9400d3',
  1352. deeppink: '#ff1493',
  1353. deepskyblue: '#00bfff',
  1354. dimgray: '#696969',
  1355. dimgrey: '#696969',
  1356. dodgerblue: '#1e90ff',
  1357. firebrick: '#b22222',
  1358. floralwhite: '#fffaf0',
  1359. forestgreen: '#228b22',
  1360. fuchsia: '#ff00ff',
  1361. gainsboro: '#dcdcdc',
  1362. ghostwhite: '#f8f8ff',
  1363. gold: '#ffd700',
  1364. goldenrod: '#daa520',
  1365. gray: '#808080',
  1366. green: '#008000',
  1367. greenyellow: '#adff2f',
  1368. grey: '#808080',
  1369. honeydew: '#f0fff0',
  1370. hotpink: '#ff69b4',
  1371. indianred: '#cd5c5c',
  1372. indigo: '#4b0082',
  1373. ivory: '#fffff0',
  1374. khaki: '#f0e68c',
  1375. laserlemon: '#ffff54',
  1376. lavender: '#e6e6fa',
  1377. lavenderblush: '#fff0f5',
  1378. lawngreen: '#7cfc00',
  1379. lemonchiffon: '#fffacd',
  1380. lightblue: '#add8e6',
  1381. lightcoral: '#f08080',
  1382. lightcyan: '#e0ffff',
  1383. lightgoldenrod: '#fafad2',
  1384. lightgoldenrodyellow: '#fafad2',
  1385. lightgray: '#d3d3d3',
  1386. lightgreen: '#90ee90',
  1387. lightgrey: '#d3d3d3',
  1388. lightpink: '#ffb6c1',
  1389. lightsalmon: '#ffa07a',
  1390. lightseagreen: '#20b2aa',
  1391. lightskyblue: '#87cefa',
  1392. lightslategray: '#778899',
  1393. lightslategrey: '#778899',
  1394. lightsteelblue: '#b0c4de',
  1395. lightyellow: '#ffffe0',
  1396. lime: '#00ff00',
  1397. limegreen: '#32cd32',
  1398. linen: '#faf0e6',
  1399. magenta: '#ff00ff',
  1400. maroon: '#800000',
  1401. maroon2: '#7f0000',
  1402. maroon3: '#b03060',
  1403. mediumaquamarine: '#66cdaa',
  1404. mediumblue: '#0000cd',
  1405. mediumorchid: '#ba55d3',
  1406. mediumpurple: '#9370db',
  1407. mediumseagreen: '#3cb371',
  1408. mediumslateblue: '#7b68ee',
  1409. mediumspringgreen: '#00fa9a',
  1410. mediumturquoise: '#48d1cc',
  1411. mediumvioletred: '#c71585',
  1412. midnightblue: '#191970',
  1413. mintcream: '#f5fffa',
  1414. mistyrose: '#ffe4e1',
  1415. moccasin: '#ffe4b5',
  1416. navajowhite: '#ffdead',
  1417. navy: '#000080',
  1418. oldlace: '#fdf5e6',
  1419. olive: '#808000',
  1420. olivedrab: '#6b8e23',
  1421. orange: '#ffa500',
  1422. orangered: '#ff4500',
  1423. orchid: '#da70d6',
  1424. palegoldenrod: '#eee8aa',
  1425. palegreen: '#98fb98',
  1426. paleturquoise: '#afeeee',
  1427. palevioletred: '#db7093',
  1428. papayawhip: '#ffefd5',
  1429. peachpuff: '#ffdab9',
  1430. peru: '#cd853f',
  1431. pink: '#ffc0cb',
  1432. plum: '#dda0dd',
  1433. powderblue: '#b0e0e6',
  1434. purple: '#800080',
  1435. purple2: '#7f007f',
  1436. purple3: '#a020f0',
  1437. rebeccapurple: '#663399',
  1438. red: '#ff0000',
  1439. rosybrown: '#bc8f8f',
  1440. royalblue: '#4169e1',
  1441. saddlebrown: '#8b4513',
  1442. salmon: '#fa8072',
  1443. sandybrown: '#f4a460',
  1444. seagreen: '#2e8b57',
  1445. seashell: '#fff5ee',
  1446. sienna: '#a0522d',
  1447. silver: '#c0c0c0',
  1448. skyblue: '#87ceeb',
  1449. slateblue: '#6a5acd',
  1450. slategray: '#708090',
  1451. slategrey: '#708090',
  1452. snow: '#fffafa',
  1453. springgreen: '#00ff7f',
  1454. steelblue: '#4682b4',
  1455. tan: '#d2b48c',
  1456. teal: '#008080',
  1457. thistle: '#d8bfd8',
  1458. tomato: '#ff6347',
  1459. turquoise: '#40e0d0',
  1460. violet: '#ee82ee',
  1461. wheat: '#f5deb3',
  1462. white: '#ffffff',
  1463. whitesmoke: '#f5f5f5',
  1464. yellow: '#ffff00',
  1465. yellowgreen: '#9acd32'
  1466. };
  1467. var w3cx11_1 = w3cx11;
  1468. var type$b = utils.type;
  1469. Color_1.prototype.name = function() {
  1470. var hex = rgb2hex_1(this._rgb, 'rgb');
  1471. for (var i = 0, list = Object.keys(w3cx11_1); i < list.length; i += 1) {
  1472. var n = list[i];
  1473. if (w3cx11_1[n] === hex) { return n.toLowerCase(); }
  1474. }
  1475. return hex;
  1476. };
  1477. input.format.named = function (name) {
  1478. name = name.toLowerCase();
  1479. if (w3cx11_1[name]) { return hex2rgb_1(w3cx11_1[name]); }
  1480. throw new Error('unknown color name: '+name);
  1481. };
  1482. input.autodetect.push({
  1483. p: 5,
  1484. test: function (h) {
  1485. var rest = [], len = arguments.length - 1;
  1486. while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ];
  1487. if (!rest.length && type$b(h) === 'string' && w3cx11_1[h.toLowerCase()]) {
  1488. return 'named';
  1489. }
  1490. }
  1491. });
  1492. var unpack$t = utils.unpack;
  1493. var rgb2num = function () {
  1494. var args = [], len = arguments.length;
  1495. while ( len-- ) args[ len ] = arguments[ len ];
  1496. var ref = unpack$t(args, 'rgb');
  1497. var r = ref[0];
  1498. var g = ref[1];
  1499. var b = ref[2];
  1500. return (r << 16) + (g << 8) + b;
  1501. };
  1502. var rgb2num_1 = rgb2num;
  1503. var type$c = utils.type;
  1504. var num2rgb = function (num) {
  1505. if (type$c(num) == "number" && num >= 0 && num <= 0xFFFFFF) {
  1506. var r = num >> 16;
  1507. var g = (num >> 8) & 0xFF;
  1508. var b = num & 0xFF;
  1509. return [r,g,b,1];
  1510. }
  1511. throw new Error("unknown num color: "+num);
  1512. };
  1513. var num2rgb_1 = num2rgb;
  1514. var type$d = utils.type;
  1515. Color_1.prototype.num = function() {
  1516. return rgb2num_1(this._rgb);
  1517. };
  1518. chroma_1.num = function () {
  1519. var args = [], len = arguments.length;
  1520. while ( len-- ) args[ len ] = arguments[ len ];
  1521. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['num']) ));
  1522. };
  1523. input.format.num = num2rgb_1;
  1524. input.autodetect.push({
  1525. p: 5,
  1526. test: function () {
  1527. var args = [], len = arguments.length;
  1528. while ( len-- ) args[ len ] = arguments[ len ];
  1529. if (args.length === 1 && type$d(args[0]) === 'number' && args[0] >= 0 && args[0] <= 0xFFFFFF) {
  1530. return 'num';
  1531. }
  1532. }
  1533. });
  1534. var unpack$u = utils.unpack;
  1535. var type$e = utils.type;
  1536. var round$5 = Math.round;
  1537. Color_1.prototype.rgb = function(rnd) {
  1538. if ( rnd === void 0 ) rnd=true;
  1539. if (rnd === false) { return this._rgb.slice(0,3); }
  1540. return this._rgb.slice(0,3).map(round$5);
  1541. };
  1542. Color_1.prototype.rgba = function(rnd) {
  1543. if ( rnd === void 0 ) rnd=true;
  1544. return this._rgb.slice(0,4).map(function (v,i) {
  1545. return i<3 ? (rnd === false ? v : round$5(v)) : v;
  1546. });
  1547. };
  1548. chroma_1.rgb = function () {
  1549. var args = [], len = arguments.length;
  1550. while ( len-- ) args[ len ] = arguments[ len ];
  1551. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['rgb']) ));
  1552. };
  1553. input.format.rgb = function () {
  1554. var args = [], len = arguments.length;
  1555. while ( len-- ) args[ len ] = arguments[ len ];
  1556. var rgba = unpack$u(args, 'rgba');
  1557. if (rgba[3] === undefined) { rgba[3] = 1; }
  1558. return rgba;
  1559. };
  1560. input.autodetect.push({
  1561. p: 3,
  1562. test: function () {
  1563. var args = [], len = arguments.length;
  1564. while ( len-- ) args[ len ] = arguments[ len ];
  1565. args = unpack$u(args, 'rgba');
  1566. if (type$e(args) === 'array' && (args.length === 3 ||
  1567. args.length === 4 && type$e(args[3]) == 'number' && args[3] >= 0 && args[3] <= 1)) {
  1568. return 'rgb';
  1569. }
  1570. }
  1571. });
  1572. /*
  1573. * Based on implementation by Neil Bartlett
  1574. * https://github.com/neilbartlett/color-temperature
  1575. */
  1576. var log = Math.log;
  1577. var temperature2rgb = function (kelvin) {
  1578. var temp = kelvin / 100;
  1579. var r,g,b;
  1580. if (temp < 66) {
  1581. r = 255;
  1582. g = -155.25485562709179 - 0.44596950469579133 * (g = temp-2) + 104.49216199393888 * log(g);
  1583. b = temp < 20 ? 0 : -254.76935184120902 + 0.8274096064007395 * (b = temp-10) + 115.67994401066147 * log(b);
  1584. } else {
  1585. r = 351.97690566805693 + 0.114206453784165 * (r = temp-55) - 40.25366309332127 * log(r);
  1586. g = 325.4494125711974 + 0.07943456536662342 * (g = temp-50) - 28.0852963507957 * log(g);
  1587. b = 255;
  1588. }
  1589. return [r,g,b,1];
  1590. };
  1591. var temperature2rgb_1 = temperature2rgb;
  1592. /*
  1593. * Based on implementation by Neil Bartlett
  1594. * https://github.com/neilbartlett/color-temperature
  1595. **/
  1596. var unpack$v = utils.unpack;
  1597. var round$6 = Math.round;
  1598. var rgb2temperature = function () {
  1599. var args = [], len = arguments.length;
  1600. while ( len-- ) args[ len ] = arguments[ len ];
  1601. var rgb = unpack$v(args, 'rgb');
  1602. var r = rgb[0], b = rgb[2];
  1603. var minTemp = 1000;
  1604. var maxTemp = 40000;
  1605. var eps = 0.4;
  1606. var temp;
  1607. while (maxTemp - minTemp > eps) {
  1608. temp = (maxTemp + minTemp) * 0.5;
  1609. var rgb$1 = temperature2rgb_1(temp);
  1610. if ((rgb$1[2] / rgb$1[0]) >= (b / r)) {
  1611. maxTemp = temp;
  1612. } else {
  1613. minTemp = temp;
  1614. }
  1615. }
  1616. return round$6(temp);
  1617. };
  1618. var rgb2temperature_1 = rgb2temperature;
  1619. Color_1.prototype.temp =
  1620. Color_1.prototype.kelvin =
  1621. Color_1.prototype.temperature = function() {
  1622. return rgb2temperature_1(this._rgb);
  1623. };
  1624. chroma_1.temp =
  1625. chroma_1.kelvin =
  1626. chroma_1.temperature = function () {
  1627. var args = [], len = arguments.length;
  1628. while ( len-- ) args[ len ] = arguments[ len ];
  1629. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['temp']) ));
  1630. };
  1631. input.format.temp =
  1632. input.format.kelvin =
  1633. input.format.temperature = temperature2rgb_1;
  1634. var type$f = utils.type;
  1635. Color_1.prototype.alpha = function(a, mutate) {
  1636. if ( mutate === void 0 ) mutate=false;
  1637. if (a !== undefined && type$f(a) === 'number') {
  1638. if (mutate) {
  1639. this._rgb[3] = a;
  1640. return this;
  1641. }
  1642. return new Color_1([this._rgb[0], this._rgb[1], this._rgb[2], a], 'rgb');
  1643. }
  1644. return this._rgb[3];
  1645. };
  1646. Color_1.prototype.clipped = function() {
  1647. return this._rgb._clipped || false;
  1648. };
  1649. Color_1.prototype.darken = function(amount) {
  1650. if ( amount === void 0 ) amount=1;
  1651. var me = this;
  1652. var lab = me.lab();
  1653. lab[0] -= labConstants.Kn * amount;
  1654. return new Color_1(lab, 'lab').alpha(me.alpha(), true);
  1655. };
  1656. Color_1.prototype.brighten = function(amount) {
  1657. if ( amount === void 0 ) amount=1;
  1658. return this.darken(-amount);
  1659. };
  1660. Color_1.prototype.darker = Color_1.prototype.darken;
  1661. Color_1.prototype.brighter = Color_1.prototype.brighten;
  1662. Color_1.prototype.get = function(mc) {
  1663. var ref = mc.split('.');
  1664. var mode = ref[0];
  1665. var channel = ref[1];
  1666. var src = this[mode]();
  1667. if (channel) {
  1668. var i = mode.indexOf(channel);
  1669. if (i > -1) { return src[i]; }
  1670. throw new Error(("unknown channel " + channel + " in mode " + mode));
  1671. } else {
  1672. return src;
  1673. }
  1674. };
  1675. var type$g = utils.type;
  1676. var pow$2 = Math.pow;
  1677. var EPS = 1e-7;
  1678. var MAX_ITER = 20;
  1679. Color_1.prototype.luminance = function(lum) {
  1680. if (lum !== undefined && type$g(lum) === 'number') {
  1681. if (lum === 0) {
  1682. // return pure black
  1683. return new Color_1([0,0,0,this._rgb[3]], 'rgb');
  1684. }
  1685. if (lum === 1) {
  1686. // return pure white
  1687. return new Color_1([255,255,255,this._rgb[3]], 'rgb');
  1688. }
  1689. // compute new color using...
  1690. var cur_lum = this.luminance();
  1691. var mode = 'rgb';
  1692. var max_iter = MAX_ITER;
  1693. var test = function (low, high) {
  1694. var mid = low.interpolate(high, 0.5, mode);
  1695. var lm = mid.luminance();
  1696. if (Math.abs(lum - lm) < EPS || !max_iter--) {
  1697. // close enough
  1698. return mid;
  1699. }
  1700. return lm > lum ? test(low, mid) : test(mid, high);
  1701. };
  1702. var rgb = (cur_lum > lum ? test(new Color_1([0,0,0]), this) : test(this, new Color_1([255,255,255]))).rgb();
  1703. return new Color_1(rgb.concat( [this._rgb[3]]));
  1704. }
  1705. return rgb2luminance.apply(void 0, (this._rgb).slice(0,3));
  1706. };
  1707. var rgb2luminance = function (r,g,b) {
  1708. // relative luminance
  1709. // see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  1710. r = luminance_x(r);
  1711. g = luminance_x(g);
  1712. b = luminance_x(b);
  1713. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  1714. };
  1715. var luminance_x = function (x) {
  1716. x /= 255;
  1717. return x <= 0.03928 ? x/12.92 : pow$2((x+0.055)/1.055, 2.4);
  1718. };
  1719. var interpolator = {};
  1720. var type$h = utils.type;
  1721. var mix = function (col1, col2, f) {
  1722. if ( f === void 0 ) f=0.5;
  1723. var rest = [], len = arguments.length - 3;
  1724. while ( len-- > 0 ) rest[ len ] = arguments[ len + 3 ];
  1725. var mode = rest[0] || 'lrgb';
  1726. if (!interpolator[mode] && !rest.length) {
  1727. // fall back to the first supported mode
  1728. mode = Object.keys(interpolator)[0];
  1729. }
  1730. if (!interpolator[mode]) {
  1731. throw new Error(("interpolation mode " + mode + " is not defined"));
  1732. }
  1733. if (type$h(col1) !== 'object') { col1 = new Color_1(col1); }
  1734. if (type$h(col2) !== 'object') { col2 = new Color_1(col2); }
  1735. return interpolator[mode](col1, col2, f)
  1736. .alpha(col1.alpha() + f * (col2.alpha() - col1.alpha()));
  1737. };
  1738. Color_1.prototype.mix =
  1739. Color_1.prototype.interpolate = function(col2, f) {
  1740. if ( f === void 0 ) f=0.5;
  1741. var rest = [], len = arguments.length - 2;
  1742. while ( len-- > 0 ) rest[ len ] = arguments[ len + 2 ];
  1743. return mix.apply(void 0, [ this, col2, f ].concat( rest ));
  1744. };
  1745. Color_1.prototype.premultiply = function(mutate) {
  1746. if ( mutate === void 0 ) mutate=false;
  1747. var rgb = this._rgb;
  1748. var a = rgb[3];
  1749. if (mutate) {
  1750. this._rgb = [rgb[0]*a, rgb[1]*a, rgb[2]*a, a];
  1751. return this;
  1752. } else {
  1753. return new Color_1([rgb[0]*a, rgb[1]*a, rgb[2]*a, a], 'rgb');
  1754. }
  1755. };
  1756. Color_1.prototype.saturate = function(amount) {
  1757. if ( amount === void 0 ) amount=1;
  1758. var me = this;
  1759. var lch = me.lch();
  1760. lch[1] += labConstants.Kn * amount;
  1761. if (lch[1] < 0) { lch[1] = 0; }
  1762. return new Color_1(lch, 'lch').alpha(me.alpha(), true);
  1763. };
  1764. Color_1.prototype.desaturate = function(amount) {
  1765. if ( amount === void 0 ) amount=1;
  1766. return this.saturate(-amount);
  1767. };
  1768. var type$i = utils.type;
  1769. Color_1.prototype.set = function(mc, value, mutate) {
  1770. if ( mutate === void 0 ) mutate=false;
  1771. var ref = mc.split('.');
  1772. var mode = ref[0];
  1773. var channel = ref[1];
  1774. var src = this[mode]();
  1775. if (channel) {
  1776. var i = mode.indexOf(channel);
  1777. if (i > -1) {
  1778. if (type$i(value) == 'string') {
  1779. switch(value.charAt(0)) {
  1780. case '+': src[i] += +value; break;
  1781. case '-': src[i] += +value; break;
  1782. case '*': src[i] *= +(value.substr(1)); break;
  1783. case '/': src[i] /= +(value.substr(1)); break;
  1784. default: src[i] = +value;
  1785. }
  1786. } else if (type$i(value) === 'number') {
  1787. src[i] = value;
  1788. } else {
  1789. throw new Error("unsupported value for Color.set");
  1790. }
  1791. var out = new Color_1(src, mode);
  1792. if (mutate) {
  1793. this._rgb = out._rgb;
  1794. return this;
  1795. }
  1796. return out;
  1797. }
  1798. throw new Error(("unknown channel " + channel + " in mode " + mode));
  1799. } else {
  1800. return src;
  1801. }
  1802. };
  1803. var rgb$1 = function (col1, col2, f) {
  1804. var xyz0 = col1._rgb;
  1805. var xyz1 = col2._rgb;
  1806. return new Color_1(
  1807. xyz0[0] + f * (xyz1[0]-xyz0[0]),
  1808. xyz0[1] + f * (xyz1[1]-xyz0[1]),
  1809. xyz0[2] + f * (xyz1[2]-xyz0[2]),
  1810. 'rgb'
  1811. )
  1812. };
  1813. // register interpolator
  1814. interpolator.rgb = rgb$1;
  1815. var sqrt$2 = Math.sqrt;
  1816. var pow$3 = Math.pow;
  1817. var lrgb = function (col1, col2, f) {
  1818. var ref = col1._rgb;
  1819. var x1 = ref[0];
  1820. var y1 = ref[1];
  1821. var z1 = ref[2];
  1822. var ref$1 = col2._rgb;
  1823. var x2 = ref$1[0];
  1824. var y2 = ref$1[1];
  1825. var z2 = ref$1[2];
  1826. return new Color_1(
  1827. sqrt$2(pow$3(x1,2) * (1-f) + pow$3(x2,2) * f),
  1828. sqrt$2(pow$3(y1,2) * (1-f) + pow$3(y2,2) * f),
  1829. sqrt$2(pow$3(z1,2) * (1-f) + pow$3(z2,2) * f),
  1830. 'rgb'
  1831. )
  1832. };
  1833. // register interpolator
  1834. interpolator.lrgb = lrgb;
  1835. var lab$1 = function (col1, col2, f) {
  1836. var xyz0 = col1.lab();
  1837. var xyz1 = col2.lab();
  1838. return new Color_1(
  1839. xyz0[0] + f * (xyz1[0]-xyz0[0]),
  1840. xyz0[1] + f * (xyz1[1]-xyz0[1]),
  1841. xyz0[2] + f * (xyz1[2]-xyz0[2]),
  1842. 'lab'
  1843. )
  1844. };
  1845. // register interpolator
  1846. interpolator.lab = lab$1;
  1847. var _hsx = function (col1, col2, f, m) {
  1848. var assign, assign$1;
  1849. var xyz0, xyz1;
  1850. if (m === 'hsl') {
  1851. xyz0 = col1.hsl();
  1852. xyz1 = col2.hsl();
  1853. } else if (m === 'hsv') {
  1854. xyz0 = col1.hsv();
  1855. xyz1 = col2.hsv();
  1856. } else if (m === 'hcg') {
  1857. xyz0 = col1.hcg();
  1858. xyz1 = col2.hcg();
  1859. } else if (m === 'hsi') {
  1860. xyz0 = col1.hsi();
  1861. xyz1 = col2.hsi();
  1862. } else if (m === 'lch' || m === 'hcl') {
  1863. m = 'hcl';
  1864. xyz0 = col1.hcl();
  1865. xyz1 = col2.hcl();
  1866. }
  1867. var hue0, hue1, sat0, sat1, lbv0, lbv1;
  1868. if (m.substr(0, 1) === 'h') {
  1869. (assign = xyz0, hue0 = assign[0], sat0 = assign[1], lbv0 = assign[2]);
  1870. (assign$1 = xyz1, hue1 = assign$1[0], sat1 = assign$1[1], lbv1 = assign$1[2]);
  1871. }
  1872. var sat, hue, lbv, dh;
  1873. if (!isNaN(hue0) && !isNaN(hue1)) {
  1874. // both colors have hue
  1875. if (hue1 > hue0 && hue1 - hue0 > 180) {
  1876. dh = hue1-(hue0+360);
  1877. } else if (hue1 < hue0 && hue0 - hue1 > 180) {
  1878. dh = hue1+360-hue0;
  1879. } else {
  1880. dh = hue1 - hue0;
  1881. }
  1882. hue = hue0 + f * dh;
  1883. } else if (!isNaN(hue0)) {
  1884. hue = hue0;
  1885. if ((lbv1 == 1 || lbv1 == 0) && m != 'hsv') { sat = sat0; }
  1886. } else if (!isNaN(hue1)) {
  1887. hue = hue1;
  1888. if ((lbv0 == 1 || lbv0 == 0) && m != 'hsv') { sat = sat1; }
  1889. } else {
  1890. hue = Number.NaN;
  1891. }
  1892. if (sat === undefined) { sat = sat0 + f * (sat1 - sat0); }
  1893. lbv = lbv0 + f * (lbv1-lbv0);
  1894. return new Color_1([hue, sat, lbv], m);
  1895. };
  1896. var lch$1 = function (col1, col2, f) {
  1897. return _hsx(col1, col2, f, 'lch');
  1898. };
  1899. // register interpolator
  1900. interpolator.lch = lch$1;
  1901. interpolator.hcl = lch$1;
  1902. var num$1 = function (col1, col2, f) {
  1903. var c1 = col1.num();
  1904. var c2 = col2.num();
  1905. return new Color_1(c1 + f * (c2-c1), 'num')
  1906. };
  1907. // register interpolator
  1908. interpolator.num = num$1;
  1909. var hcg$1 = function (col1, col2, f) {
  1910. return _hsx(col1, col2, f, 'hcg');
  1911. };
  1912. // register interpolator
  1913. interpolator.hcg = hcg$1;
  1914. var hsi$1 = function (col1, col2, f) {
  1915. return _hsx(col1, col2, f, 'hsi');
  1916. };
  1917. // register interpolator
  1918. interpolator.hsi = hsi$1;
  1919. var hsl$1 = function (col1, col2, f) {
  1920. return _hsx(col1, col2, f, 'hsl');
  1921. };
  1922. // register interpolator
  1923. interpolator.hsl = hsl$1;
  1924. var hsv$1 = function (col1, col2, f) {
  1925. return _hsx(col1, col2, f, 'hsv');
  1926. };
  1927. // register interpolator
  1928. interpolator.hsv = hsv$1;
  1929. var clip_rgb$2 = utils.clip_rgb;
  1930. var pow$4 = Math.pow;
  1931. var sqrt$3 = Math.sqrt;
  1932. var PI$1 = Math.PI;
  1933. var cos$2 = Math.cos;
  1934. var sin$1 = Math.sin;
  1935. var atan2$1 = Math.atan2;
  1936. var average = function (colors, mode, weights) {
  1937. if ( mode === void 0 ) mode='lrgb';
  1938. if ( weights === void 0 ) weights=null;
  1939. var l = colors.length;
  1940. if (!weights) { weights = Array.from(new Array(l)).map(function () { return 1; }); }
  1941. // normalize weights
  1942. var k = l / weights.reduce(function(a, b) { return a + b; });
  1943. weights.forEach(function (w,i) { weights[i] *= k; });
  1944. // convert colors to Color objects
  1945. colors = colors.map(function (c) { return new Color_1(c); });
  1946. if (mode === 'lrgb') {
  1947. return _average_lrgb(colors, weights)
  1948. }
  1949. var first = colors.shift();
  1950. var xyz = first.get(mode);
  1951. var cnt = [];
  1952. var dx = 0;
  1953. var dy = 0;
  1954. // initial color
  1955. for (var i=0; i<xyz.length; i++) {
  1956. xyz[i] = (xyz[i] || 0) * weights[0];
  1957. cnt.push(isNaN(xyz[i]) ? 0 : weights[0]);
  1958. if (mode.charAt(i) === 'h' && !isNaN(xyz[i])) {
  1959. var A = xyz[i] / 180 * PI$1;
  1960. dx += cos$2(A) * weights[0];
  1961. dy += sin$1(A) * weights[0];
  1962. }
  1963. }
  1964. var alpha = first.alpha() * weights[0];
  1965. colors.forEach(function (c,ci) {
  1966. var xyz2 = c.get(mode);
  1967. alpha += c.alpha() * weights[ci+1];
  1968. for (var i=0; i<xyz.length; i++) {
  1969. if (!isNaN(xyz2[i])) {
  1970. cnt[i] += weights[ci+1];
  1971. if (mode.charAt(i) === 'h') {
  1972. var A = xyz2[i] / 180 * PI$1;
  1973. dx += cos$2(A) * weights[ci+1];
  1974. dy += sin$1(A) * weights[ci+1];
  1975. } else {
  1976. xyz[i] += xyz2[i] * weights[ci+1];
  1977. }
  1978. }
  1979. }
  1980. });
  1981. for (var i$1=0; i$1<xyz.length; i$1++) {
  1982. if (mode.charAt(i$1) === 'h') {
  1983. var A$1 = atan2$1(dy / cnt[i$1], dx / cnt[i$1]) / PI$1 * 180;
  1984. while (A$1 < 0) { A$1 += 360; }
  1985. while (A$1 >= 360) { A$1 -= 360; }
  1986. xyz[i$1] = A$1;
  1987. } else {
  1988. xyz[i$1] = xyz[i$1]/cnt[i$1];
  1989. }
  1990. }
  1991. alpha /= l;
  1992. return (new Color_1(xyz, mode)).alpha(alpha > 0.99999 ? 1 : alpha, true);
  1993. };
  1994. var _average_lrgb = function (colors, weights) {
  1995. var l = colors.length;
  1996. var xyz = [0,0,0,0];
  1997. for (var i=0; i < colors.length; i++) {
  1998. var col = colors[i];
  1999. var f = weights[i] / l;
  2000. var rgb = col._rgb;
  2001. xyz[0] += pow$4(rgb[0],2) * f;
  2002. xyz[1] += pow$4(rgb[1],2) * f;
  2003. xyz[2] += pow$4(rgb[2],2) * f;
  2004. xyz[3] += rgb[3] * f;
  2005. }
  2006. xyz[0] = sqrt$3(xyz[0]);
  2007. xyz[1] = sqrt$3(xyz[1]);
  2008. xyz[2] = sqrt$3(xyz[2]);
  2009. if (xyz[3] > 0.9999999) { xyz[3] = 1; }
  2010. return new Color_1(clip_rgb$2(xyz));
  2011. };
  2012. // minimal multi-purpose interface
  2013. // @requires utils color analyze
  2014. var type$j = utils.type;
  2015. var pow$5 = Math.pow;
  2016. var scale = function(colors) {
  2017. // constructor
  2018. var _mode = 'rgb';
  2019. var _nacol = chroma_1('#ccc');
  2020. var _spread = 0;
  2021. // const _fixed = false;
  2022. var _domain = [0, 1];
  2023. var _pos = [];
  2024. var _padding = [0,0];
  2025. var _classes = false;
  2026. var _colors = [];
  2027. var _out = false;
  2028. var _min = 0;
  2029. var _max = 1;
  2030. var _correctLightness = false;
  2031. var _colorCache = {};
  2032. var _useCache = true;
  2033. var _gamma = 1;
  2034. // private methods
  2035. var setColors = function(colors) {
  2036. colors = colors || ['#fff', '#000'];
  2037. if (colors && type$j(colors) === 'string' && chroma_1.brewer &&
  2038. chroma_1.brewer[colors.toLowerCase()]) {
  2039. colors = chroma_1.brewer[colors.toLowerCase()];
  2040. }
  2041. if (type$j(colors) === 'array') {
  2042. // handle single color
  2043. if (colors.length === 1) {
  2044. colors = [colors[0], colors[0]];
  2045. }
  2046. // make a copy of the colors
  2047. colors = colors.slice(0);
  2048. // convert to chroma classes
  2049. for (var c=0; c<colors.length; c++) {
  2050. colors[c] = chroma_1(colors[c]);
  2051. }
  2052. // auto-fill color position
  2053. _pos.length = 0;
  2054. for (var c$1=0; c$1<colors.length; c$1++) {
  2055. _pos.push(c$1/(colors.length-1));
  2056. }
  2057. }
  2058. resetCache();
  2059. return _colors = colors;
  2060. };
  2061. var getClass = function(value) {
  2062. if (_classes != null) {
  2063. var n = _classes.length-1;
  2064. var i = 0;
  2065. while (i < n && value >= _classes[i]) {
  2066. i++;
  2067. }
  2068. return i-1;
  2069. }
  2070. return 0;
  2071. };
  2072. var tMapLightness = function (t) { return t; };
  2073. var tMapDomain = function (t) { return t; };
  2074. // const classifyValue = function(value) {
  2075. // let val = value;
  2076. // if (_classes.length > 2) {
  2077. // const n = _classes.length-1;
  2078. // const i = getClass(value);
  2079. // const minc = _classes[0] + ((_classes[1]-_classes[0]) * (0 + (_spread * 0.5))); // center of 1st class
  2080. // const maxc = _classes[n-1] + ((_classes[n]-_classes[n-1]) * (1 - (_spread * 0.5))); // center of last class
  2081. // val = _min + ((((_classes[i] + ((_classes[i+1] - _classes[i]) * 0.5)) - minc) / (maxc-minc)) * (_max - _min));
  2082. // }
  2083. // return val;
  2084. // };
  2085. var getColor = function(val, bypassMap) {
  2086. var col, t;
  2087. if (bypassMap == null) { bypassMap = false; }
  2088. if (isNaN(val) || (val === null)) { return _nacol; }
  2089. if (!bypassMap) {
  2090. if (_classes && (_classes.length > 2)) {
  2091. // find the class
  2092. var c = getClass(val);
  2093. t = c / (_classes.length-2);
  2094. } else if (_max !== _min) {
  2095. // just interpolate between min/max
  2096. t = (val - _min) / (_max - _min);
  2097. } else {
  2098. t = 1;
  2099. }
  2100. } else {
  2101. t = val;
  2102. }
  2103. // domain map
  2104. t = tMapDomain(t);
  2105. if (!bypassMap) {
  2106. t = tMapLightness(t); // lightness correction
  2107. }
  2108. if (_gamma !== 1) { t = pow$5(t, _gamma); }
  2109. t = _padding[0] + (t * (1 - _padding[0] - _padding[1]));
  2110. t = Math.min(1, Math.max(0, t));
  2111. var k = Math.floor(t * 10000);
  2112. if (_useCache && _colorCache[k]) {
  2113. col = _colorCache[k];
  2114. } else {
  2115. if (type$j(_colors) === 'array') {
  2116. //for i in [0.._pos.length-1]
  2117. for (var i=0; i<_pos.length; i++) {
  2118. var p = _pos[i];
  2119. if (t <= p) {
  2120. col = _colors[i];
  2121. break;
  2122. }
  2123. if ((t >= p) && (i === (_pos.length-1))) {
  2124. col = _colors[i];
  2125. break;
  2126. }
  2127. if (t > p && t < _pos[i+1]) {
  2128. t = (t-p)/(_pos[i+1]-p);
  2129. col = chroma_1.interpolate(_colors[i], _colors[i+1], t, _mode);
  2130. break;
  2131. }
  2132. }
  2133. } else if (type$j(_colors) === 'function') {
  2134. col = _colors(t);
  2135. }
  2136. if (_useCache) { _colorCache[k] = col; }
  2137. }
  2138. return col;
  2139. };
  2140. var resetCache = function () { return _colorCache = {}; };
  2141. setColors(colors);
  2142. // public interface
  2143. var f = function(v) {
  2144. var c = chroma_1(getColor(v));
  2145. if (_out && c[_out]) { return c[_out](); } else { return c; }
  2146. };
  2147. f.classes = function(classes) {
  2148. if (classes != null) {
  2149. if (type$j(classes) === 'array') {
  2150. _classes = classes;
  2151. _domain = [classes[0], classes[classes.length-1]];
  2152. } else {
  2153. var d = chroma_1.analyze(_domain);
  2154. if (classes === 0) {
  2155. _classes = [d.min, d.max];
  2156. } else {
  2157. _classes = chroma_1.limits(d, 'e', classes);
  2158. }
  2159. }
  2160. return f;
  2161. }
  2162. return _classes;
  2163. };
  2164. f.domain = function(domain) {
  2165. if (!arguments.length) {
  2166. return _domain;
  2167. }
  2168. _min = domain[0];
  2169. _max = domain[domain.length-1];
  2170. _pos = [];
  2171. var k = _colors.length;
  2172. if ((domain.length === k) && (_min !== _max)) {
  2173. // update positions
  2174. for (var i = 0, list = Array.from(domain); i < list.length; i += 1) {
  2175. var d = list[i];
  2176. _pos.push((d-_min) / (_max-_min));
  2177. }
  2178. } else {
  2179. for (var c=0; c<k; c++) {
  2180. _pos.push(c/(k-1));
  2181. }
  2182. if (domain.length > 2) {
  2183. // set domain map
  2184. var tOut = domain.map(function (d,i) { return i/(domain.length-1); });
  2185. var tBreaks = domain.map(function (d) { return (d - _min) / (_max - _min); });
  2186. if (!tBreaks.every(function (val, i) { return tOut[i] === val; })) {
  2187. tMapDomain = function (t) {
  2188. if (t <= 0 || t >= 1) { return t; }
  2189. var i = 0;
  2190. while (t >= tBreaks[i+1]) { i++; }
  2191. var f = (t - tBreaks[i]) / (tBreaks[i+1] - tBreaks[i]);
  2192. var out = tOut[i] + f * (tOut[i+1] - tOut[i]);
  2193. return out;
  2194. };
  2195. }
  2196. }
  2197. }
  2198. _domain = [_min, _max];
  2199. return f;
  2200. };
  2201. f.mode = function(_m) {
  2202. if (!arguments.length) {
  2203. return _mode;
  2204. }
  2205. _mode = _m;
  2206. resetCache();
  2207. return f;
  2208. };
  2209. f.range = function(colors, _pos) {
  2210. setColors(colors);
  2211. return f;
  2212. };
  2213. f.out = function(_o) {
  2214. _out = _o;
  2215. return f;
  2216. };
  2217. f.spread = function(val) {
  2218. if (!arguments.length) {
  2219. return _spread;
  2220. }
  2221. _spread = val;
  2222. return f;
  2223. };
  2224. f.correctLightness = function(v) {
  2225. if (v == null) { v = true; }
  2226. _correctLightness = v;
  2227. resetCache();
  2228. if (_correctLightness) {
  2229. tMapLightness = function(t) {
  2230. var L0 = getColor(0, true).lab()[0];
  2231. var L1 = getColor(1, true).lab()[0];
  2232. var pol = L0 > L1;
  2233. var L_actual = getColor(t, true).lab()[0];
  2234. var L_ideal = L0 + ((L1 - L0) * t);
  2235. var L_diff = L_actual - L_ideal;
  2236. var t0 = 0;
  2237. var t1 = 1;
  2238. var max_iter = 20;
  2239. while ((Math.abs(L_diff) > 1e-2) && (max_iter-- > 0)) {
  2240. (function() {
  2241. if (pol) { L_diff *= -1; }
  2242. if (L_diff < 0) {
  2243. t0 = t;
  2244. t += (t1 - t) * 0.5;
  2245. } else {
  2246. t1 = t;
  2247. t += (t0 - t) * 0.5;
  2248. }
  2249. L_actual = getColor(t, true).lab()[0];
  2250. return L_diff = L_actual - L_ideal;
  2251. })();
  2252. }
  2253. return t;
  2254. };
  2255. } else {
  2256. tMapLightness = function (t) { return t; };
  2257. }
  2258. return f;
  2259. };
  2260. f.padding = function(p) {
  2261. if (p != null) {
  2262. if (type$j(p) === 'number') {
  2263. p = [p,p];
  2264. }
  2265. _padding = p;
  2266. return f;
  2267. } else {
  2268. return _padding;
  2269. }
  2270. };
  2271. f.colors = function(numColors, out) {
  2272. // If no arguments are given, return the original colors that were provided
  2273. if (arguments.length < 2) { out = 'hex'; }
  2274. var result = [];
  2275. if (arguments.length === 0) {
  2276. result = _colors.slice(0);
  2277. } else if (numColors === 1) {
  2278. result = [f(0.5)];
  2279. } else if (numColors > 1) {
  2280. var dm = _domain[0];
  2281. var dd = _domain[1] - dm;
  2282. result = __range__(0, numColors, false).map(function (i) { return f( dm + ((i/(numColors-1)) * dd) ); });
  2283. } else { // returns all colors based on the defined classes
  2284. colors = [];
  2285. var samples = [];
  2286. if (_classes && (_classes.length > 2)) {
  2287. for (var i = 1, end = _classes.length, asc = 1 <= end; asc ? i < end : i > end; asc ? i++ : i--) {
  2288. samples.push((_classes[i-1]+_classes[i])*0.5);
  2289. }
  2290. } else {
  2291. samples = _domain;
  2292. }
  2293. result = samples.map(function (v) { return f(v); });
  2294. }
  2295. if (chroma_1[out]) {
  2296. result = result.map(function (c) { return c[out](); });
  2297. }
  2298. return result;
  2299. };
  2300. f.cache = function(c) {
  2301. if (c != null) {
  2302. _useCache = c;
  2303. return f;
  2304. } else {
  2305. return _useCache;
  2306. }
  2307. };
  2308. f.gamma = function(g) {
  2309. if (g != null) {
  2310. _gamma = g;
  2311. return f;
  2312. } else {
  2313. return _gamma;
  2314. }
  2315. };
  2316. f.nodata = function(d) {
  2317. if (d != null) {
  2318. _nacol = chroma_1(d);
  2319. return f;
  2320. } else {
  2321. return _nacol;
  2322. }
  2323. };
  2324. return f;
  2325. };
  2326. function __range__(left, right, inclusive) {
  2327. var range = [];
  2328. var ascending = left < right;
  2329. var end = !inclusive ? right : ascending ? right + 1 : right - 1;
  2330. for (var i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
  2331. range.push(i);
  2332. }
  2333. return range;
  2334. }
  2335. //
  2336. // interpolates between a set of colors uzing a bezier spline
  2337. //
  2338. // @requires utils lab
  2339. var bezier = function(colors) {
  2340. var assign, assign$1, assign$2;
  2341. var I, lab0, lab1, lab2;
  2342. colors = colors.map(function (c) { return new Color_1(c); });
  2343. if (colors.length === 2) {
  2344. // linear interpolation
  2345. (assign = colors.map(function (c) { return c.lab(); }), lab0 = assign[0], lab1 = assign[1]);
  2346. I = function(t) {
  2347. var lab = ([0, 1, 2].map(function (i) { return lab0[i] + (t * (lab1[i] - lab0[i])); }));
  2348. return new Color_1(lab, 'lab');
  2349. };
  2350. } else if (colors.length === 3) {
  2351. // quadratic bezier interpolation
  2352. (assign$1 = colors.map(function (c) { return c.lab(); }), lab0 = assign$1[0], lab1 = assign$1[1], lab2 = assign$1[2]);
  2353. I = function(t) {
  2354. var lab = ([0, 1, 2].map(function (i) { return ((1-t)*(1-t) * lab0[i]) + (2 * (1-t) * t * lab1[i]) + (t * t * lab2[i]); }));
  2355. return new Color_1(lab, 'lab');
  2356. };
  2357. } else if (colors.length === 4) {
  2358. // cubic bezier interpolation
  2359. var lab3;
  2360. (assign$2 = colors.map(function (c) { return c.lab(); }), lab0 = assign$2[0], lab1 = assign$2[1], lab2 = assign$2[2], lab3 = assign$2[3]);
  2361. I = function(t) {
  2362. var lab = ([0, 1, 2].map(function (i) { return ((1-t)*(1-t)*(1-t) * lab0[i]) + (3 * (1-t) * (1-t) * t * lab1[i]) + (3 * (1-t) * t * t * lab2[i]) + (t*t*t * lab3[i]); }));
  2363. return new Color_1(lab, 'lab');
  2364. };
  2365. } else if (colors.length === 5) {
  2366. var I0 = bezier(colors.slice(0, 3));
  2367. var I1 = bezier(colors.slice(2, 5));
  2368. I = function(t) {
  2369. if (t < 0.5) {
  2370. return I0(t*2);
  2371. } else {
  2372. return I1((t-0.5)*2);
  2373. }
  2374. };
  2375. }
  2376. return I;
  2377. };
  2378. var bezier_1 = function (colors) {
  2379. var f = bezier(colors);
  2380. f.scale = function () { return scale(f); };
  2381. return f;
  2382. };
  2383. /*
  2384. * interpolates between a set of colors uzing a bezier spline
  2385. * blend mode formulas taken from http://www.venture-ware.com/kevin/coding/lets-learn-math-photoshop-blend-modes/
  2386. */
  2387. var blend = function (bottom, top, mode) {
  2388. if (!blend[mode]) {
  2389. throw new Error('unknown blend mode ' + mode);
  2390. }
  2391. return blend[mode](bottom, top);
  2392. };
  2393. var blend_f = function (f) { return function (bottom,top) {
  2394. var c0 = chroma_1(top).rgb();
  2395. var c1 = chroma_1(bottom).rgb();
  2396. return chroma_1.rgb(f(c0, c1));
  2397. }; };
  2398. var each = function (f) { return function (c0, c1) {
  2399. var out = [];
  2400. out[0] = f(c0[0], c1[0]);
  2401. out[1] = f(c0[1], c1[1]);
  2402. out[2] = f(c0[2], c1[2]);
  2403. return out;
  2404. }; };
  2405. var normal = function (a) { return a; };
  2406. var multiply = function (a,b) { return a * b / 255; };
  2407. var darken$1 = function (a,b) { return a > b ? b : a; };
  2408. var lighten = function (a,b) { return a > b ? a : b; };
  2409. var screen = function (a,b) { return 255 * (1 - (1-a/255) * (1-b/255)); };
  2410. var overlay = function (a,b) { return b < 128 ? 2 * a * b / 255 : 255 * (1 - 2 * (1 - a / 255 ) * ( 1 - b / 255 )); };
  2411. var burn = function (a,b) { return 255 * (1 - (1 - b / 255) / (a/255)); };
  2412. var dodge = function (a,b) {
  2413. if (a === 255) { return 255; }
  2414. a = 255 * (b / 255) / (1 - a / 255);
  2415. return a > 255 ? 255 : a
  2416. };
  2417. // # add = (a,b) ->
  2418. // # if (a + b > 255) then 255 else a + b
  2419. blend.normal = blend_f(each(normal));
  2420. blend.multiply = blend_f(each(multiply));
  2421. blend.screen = blend_f(each(screen));
  2422. blend.overlay = blend_f(each(overlay));
  2423. blend.darken = blend_f(each(darken$1));
  2424. blend.lighten = blend_f(each(lighten));
  2425. blend.dodge = blend_f(each(dodge));
  2426. blend.burn = blend_f(each(burn));
  2427. // blend.add = blend_f(each(add));
  2428. var blend_1 = blend;
  2429. // cubehelix interpolation
  2430. // based on D.A. Green "A colour scheme for the display of astronomical intensity images"
  2431. // http://astron-soc.in/bulletin/11June/289392011.pdf
  2432. var type$k = utils.type;
  2433. var clip_rgb$3 = utils.clip_rgb;
  2434. var TWOPI$2 = utils.TWOPI;
  2435. var pow$6 = Math.pow;
  2436. var sin$2 = Math.sin;
  2437. var cos$3 = Math.cos;
  2438. var cubehelix = function(start, rotations, hue, gamma, lightness) {
  2439. if ( start === void 0 ) start=300;
  2440. if ( rotations === void 0 ) rotations=-1.5;
  2441. if ( hue === void 0 ) hue=1;
  2442. if ( gamma === void 0 ) gamma=1;
  2443. if ( lightness === void 0 ) lightness=[0,1];
  2444. var dh = 0, dl;
  2445. if (type$k(lightness) === 'array') {
  2446. dl = lightness[1] - lightness[0];
  2447. } else {
  2448. dl = 0;
  2449. lightness = [lightness, lightness];
  2450. }
  2451. var f = function(fract) {
  2452. var a = TWOPI$2 * (((start+120)/360) + (rotations * fract));
  2453. var l = pow$6(lightness[0] + (dl * fract), gamma);
  2454. var h = dh !== 0 ? hue[0] + (fract * dh) : hue;
  2455. var amp = (h * l * (1-l)) / 2;
  2456. var cos_a = cos$3(a);
  2457. var sin_a = sin$2(a);
  2458. var r = l + (amp * ((-0.14861 * cos_a) + (1.78277* sin_a)));
  2459. var g = l + (amp * ((-0.29227 * cos_a) - (0.90649* sin_a)));
  2460. var b = l + (amp * (+1.97294 * cos_a));
  2461. return chroma_1(clip_rgb$3([r*255,g*255,b*255,1]));
  2462. };
  2463. f.start = function(s) {
  2464. if ((s == null)) { return start; }
  2465. start = s;
  2466. return f;
  2467. };
  2468. f.rotations = function(r) {
  2469. if ((r == null)) { return rotations; }
  2470. rotations = r;
  2471. return f;
  2472. };
  2473. f.gamma = function(g) {
  2474. if ((g == null)) { return gamma; }
  2475. gamma = g;
  2476. return f;
  2477. };
  2478. f.hue = function(h) {
  2479. if ((h == null)) { return hue; }
  2480. hue = h;
  2481. if (type$k(hue) === 'array') {
  2482. dh = hue[1] - hue[0];
  2483. if (dh === 0) { hue = hue[1]; }
  2484. } else {
  2485. dh = 0;
  2486. }
  2487. return f;
  2488. };
  2489. f.lightness = function(h) {
  2490. if ((h == null)) { return lightness; }
  2491. if (type$k(h) === 'array') {
  2492. lightness = h;
  2493. dl = h[1] - h[0];
  2494. } else {
  2495. lightness = [h,h];
  2496. dl = 0;
  2497. }
  2498. return f;
  2499. };
  2500. f.scale = function () { return chroma_1.scale(f); };
  2501. f.hue(hue);
  2502. return f;
  2503. };
  2504. var digits = '0123456789abcdef';
  2505. var floor$2 = Math.floor;
  2506. var random = Math.random;
  2507. var random_1 = function () {
  2508. var code = '#';
  2509. for (var i=0; i<6; i++) {
  2510. code += digits.charAt(floor$2(random() * 16));
  2511. }
  2512. return new Color_1(code, 'hex');
  2513. };
  2514. var log$1 = Math.log;
  2515. var pow$7 = Math.pow;
  2516. var floor$3 = Math.floor;
  2517. var abs = Math.abs;
  2518. var analyze = function (data, key) {
  2519. if ( key === void 0 ) key=null;
  2520. var r = {
  2521. min: Number.MAX_VALUE,
  2522. max: Number.MAX_VALUE*-1,
  2523. sum: 0,
  2524. values: [],
  2525. count: 0
  2526. };
  2527. if (type(data) === 'object') {
  2528. data = Object.values(data);
  2529. }
  2530. data.forEach(function (val) {
  2531. if (key && type(val) === 'object') { val = val[key]; }
  2532. if (val !== undefined && val !== null && !isNaN(val)) {
  2533. r.values.push(val);
  2534. r.sum += val;
  2535. if (val < r.min) { r.min = val; }
  2536. if (val > r.max) { r.max = val; }
  2537. r.count += 1;
  2538. }
  2539. });
  2540. r.domain = [r.min, r.max];
  2541. r.limits = function (mode, num) { return limits(r, mode, num); };
  2542. return r;
  2543. };
  2544. var limits = function (data, mode, num) {
  2545. if ( mode === void 0 ) mode='equal';
  2546. if ( num === void 0 ) num=7;
  2547. if (type(data) == 'array') {
  2548. data = analyze(data);
  2549. }
  2550. var min = data.min;
  2551. var max = data.max;
  2552. var values = data.values.sort(function (a,b) { return a-b; });
  2553. if (num === 1) { return [min,max]; }
  2554. var limits = [];
  2555. if (mode.substr(0,1) === 'c') { // continuous
  2556. limits.push(min);
  2557. limits.push(max);
  2558. }
  2559. if (mode.substr(0,1) === 'e') { // equal interval
  2560. limits.push(min);
  2561. for (var i=1; i<num; i++) {
  2562. limits.push(min+((i/num)*(max-min)));
  2563. }
  2564. limits.push(max);
  2565. }
  2566. else if (mode.substr(0,1) === 'l') { // log scale
  2567. if (min <= 0) {
  2568. throw new Error('Logarithmic scales are only possible for values > 0');
  2569. }
  2570. var min_log = Math.LOG10E * log$1(min);
  2571. var max_log = Math.LOG10E * log$1(max);
  2572. limits.push(min);
  2573. for (var i$1=1; i$1<num; i$1++) {
  2574. limits.push(pow$7(10, min_log + ((i$1/num) * (max_log - min_log))));
  2575. }
  2576. limits.push(max);
  2577. }
  2578. else if (mode.substr(0,1) === 'q') { // quantile scale
  2579. limits.push(min);
  2580. for (var i$2=1; i$2<num; i$2++) {
  2581. var p = ((values.length-1) * i$2)/num;
  2582. var pb = floor$3(p);
  2583. if (pb === p) {
  2584. limits.push(values[pb]);
  2585. } else { // p > pb
  2586. var pr = p - pb;
  2587. limits.push((values[pb]*(1-pr)) + (values[pb+1]*pr));
  2588. }
  2589. }
  2590. limits.push(max);
  2591. }
  2592. else if (mode.substr(0,1) === 'k') { // k-means clustering
  2593. /*
  2594. implementation based on
  2595. http://code.google.com/p/figue/source/browse/trunk/figue.js#336
  2596. simplified for 1-d input values
  2597. */
  2598. var cluster;
  2599. var n = values.length;
  2600. var assignments = new Array(n);
  2601. var clusterSizes = new Array(num);
  2602. var repeat = true;
  2603. var nb_iters = 0;
  2604. var centroids = null;
  2605. // get seed values
  2606. centroids = [];
  2607. centroids.push(min);
  2608. for (var i$3=1; i$3<num; i$3++) {
  2609. centroids.push(min + ((i$3/num) * (max-min)));
  2610. }
  2611. centroids.push(max);
  2612. while (repeat) {
  2613. // assignment step
  2614. for (var j=0; j<num; j++) {
  2615. clusterSizes[j] = 0;
  2616. }
  2617. for (var i$4=0; i$4<n; i$4++) {
  2618. var value = values[i$4];
  2619. var mindist = Number.MAX_VALUE;
  2620. var best = (void 0);
  2621. for (var j$1=0; j$1<num; j$1++) {
  2622. var dist = abs(centroids[j$1]-value);
  2623. if (dist < mindist) {
  2624. mindist = dist;
  2625. best = j$1;
  2626. }
  2627. clusterSizes[best]++;
  2628. assignments[i$4] = best;
  2629. }
  2630. }
  2631. // update centroids step
  2632. var newCentroids = new Array(num);
  2633. for (var j$2=0; j$2<num; j$2++) {
  2634. newCentroids[j$2] = null;
  2635. }
  2636. for (var i$5=0; i$5<n; i$5++) {
  2637. cluster = assignments[i$5];
  2638. if (newCentroids[cluster] === null) {
  2639. newCentroids[cluster] = values[i$5];
  2640. } else {
  2641. newCentroids[cluster] += values[i$5];
  2642. }
  2643. }
  2644. for (var j$3=0; j$3<num; j$3++) {
  2645. newCentroids[j$3] *= 1/clusterSizes[j$3];
  2646. }
  2647. // check convergence
  2648. repeat = false;
  2649. for (var j$4=0; j$4<num; j$4++) {
  2650. if (newCentroids[j$4] !== centroids[j$4]) {
  2651. repeat = true;
  2652. break;
  2653. }
  2654. }
  2655. centroids = newCentroids;
  2656. nb_iters++;
  2657. if (nb_iters > 200) {
  2658. repeat = false;
  2659. }
  2660. }
  2661. // finished k-means clustering
  2662. // the next part is borrowed from gabrielflor.it
  2663. var kClusters = {};
  2664. for (var j$5=0; j$5<num; j$5++) {
  2665. kClusters[j$5] = [];
  2666. }
  2667. for (var i$6=0; i$6<n; i$6++) {
  2668. cluster = assignments[i$6];
  2669. kClusters[cluster].push(values[i$6]);
  2670. }
  2671. var tmpKMeansBreaks = [];
  2672. for (var j$6=0; j$6<num; j$6++) {
  2673. tmpKMeansBreaks.push(kClusters[j$6][0]);
  2674. tmpKMeansBreaks.push(kClusters[j$6][kClusters[j$6].length-1]);
  2675. }
  2676. tmpKMeansBreaks = tmpKMeansBreaks.sort(function (a,b){ return a-b; });
  2677. limits.push(tmpKMeansBreaks[0]);
  2678. for (var i$7=1; i$7 < tmpKMeansBreaks.length; i$7+= 2) {
  2679. var v = tmpKMeansBreaks[i$7];
  2680. if (!isNaN(v) && (limits.indexOf(v) === -1)) {
  2681. limits.push(v);
  2682. }
  2683. }
  2684. }
  2685. return limits;
  2686. };
  2687. var analyze_1 = {analyze: analyze, limits: limits};
  2688. var contrast = function (a, b) {
  2689. // WCAG contrast ratio
  2690. // see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
  2691. a = new Color_1(a);
  2692. b = new Color_1(b);
  2693. var l1 = a.luminance();
  2694. var l2 = b.luminance();
  2695. return l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05);
  2696. };
  2697. var sqrt$4 = Math.sqrt;
  2698. var atan2$2 = Math.atan2;
  2699. var abs$1 = Math.abs;
  2700. var cos$4 = Math.cos;
  2701. var PI$2 = Math.PI;
  2702. var deltaE = function(a, b, L, C) {
  2703. if ( L === void 0 ) L=1;
  2704. if ( C === void 0 ) C=1;
  2705. // Delta E (CMC)
  2706. // see http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CMC.html
  2707. a = new Color_1(a);
  2708. b = new Color_1(b);
  2709. var ref = Array.from(a.lab());
  2710. var L1 = ref[0];
  2711. var a1 = ref[1];
  2712. var b1 = ref[2];
  2713. var ref$1 = Array.from(b.lab());
  2714. var L2 = ref$1[0];
  2715. var a2 = ref$1[1];
  2716. var b2 = ref$1[2];
  2717. var c1 = sqrt$4((a1 * a1) + (b1 * b1));
  2718. var c2 = sqrt$4((a2 * a2) + (b2 * b2));
  2719. var sl = L1 < 16.0 ? 0.511 : (0.040975 * L1) / (1.0 + (0.01765 * L1));
  2720. var sc = ((0.0638 * c1) / (1.0 + (0.0131 * c1))) + 0.638;
  2721. var h1 = c1 < 0.000001 ? 0.0 : (atan2$2(b1, a1) * 180.0) / PI$2;
  2722. while (h1 < 0) { h1 += 360; }
  2723. while (h1 >= 360) { h1 -= 360; }
  2724. var t = (h1 >= 164.0) && (h1 <= 345.0) ? (0.56 + abs$1(0.2 * cos$4((PI$2 * (h1 + 168.0)) / 180.0))) : (0.36 + abs$1(0.4 * cos$4((PI$2 * (h1 + 35.0)) / 180.0)));
  2725. var c4 = c1 * c1 * c1 * c1;
  2726. var f = sqrt$4(c4 / (c4 + 1900.0));
  2727. var sh = sc * (((f * t) + 1.0) - f);
  2728. var delL = L1 - L2;
  2729. var delC = c1 - c2;
  2730. var delA = a1 - a2;
  2731. var delB = b1 - b2;
  2732. var dH2 = ((delA * delA) + (delB * delB)) - (delC * delC);
  2733. var v1 = delL / (L * sl);
  2734. var v2 = delC / (C * sc);
  2735. var v3 = sh;
  2736. return sqrt$4((v1 * v1) + (v2 * v2) + (dH2 / (v3 * v3)));
  2737. };
  2738. // simple Euclidean distance
  2739. var distance = function(a, b, mode) {
  2740. if ( mode === void 0 ) mode='lab';
  2741. // Delta E (CIE 1976)
  2742. // see http://www.brucelindbloom.com/index.html?Equations.html
  2743. a = new Color_1(a);
  2744. b = new Color_1(b);
  2745. var l1 = a.get(mode);
  2746. var l2 = b.get(mode);
  2747. var sum_sq = 0;
  2748. for (var i in l1) {
  2749. var d = (l1[i] || 0) - (l2[i] || 0);
  2750. sum_sq += d*d;
  2751. }
  2752. return Math.sqrt(sum_sq);
  2753. };
  2754. var valid = function () {
  2755. var args = [], len = arguments.length;
  2756. while ( len-- ) args[ len ] = arguments[ len ];
  2757. try {
  2758. new (Function.prototype.bind.apply( Color_1, [ null ].concat( args) ));
  2759. return true;
  2760. } catch (e) {
  2761. return false;
  2762. }
  2763. };
  2764. // some pre-defined color scales:
  2765. var scales = {
  2766. cool: function cool() { return scale([chroma_1.hsl(180,1,.9), chroma_1.hsl(250,.7,.4)]) },
  2767. hot: function hot() { return scale(['#000','#f00','#ff0','#fff']).mode('rgb') }
  2768. };
  2769. /**
  2770. ColorBrewer colors for chroma.js
  2771. Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The
  2772. Pennsylvania State University.
  2773. Licensed under the Apache License, Version 2.0 (the "License");
  2774. you may not use this file except in compliance with the License.
  2775. You may obtain a copy of the License at
  2776. http://www.apache.org/licenses/LICENSE-2.0
  2777. Unless required by applicable law or agreed to in writing, software distributed
  2778. under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  2779. CONDITIONS OF ANY KIND, either express or implied. See the License for the
  2780. specific language governing permissions and limitations under the License.
  2781. */
  2782. var colorbrewer = {
  2783. // sequential
  2784. OrRd: ['#fff7ec', '#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'],
  2785. PuBu: ['#fff7fb', '#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858'],
  2786. BuPu: ['#f7fcfd', '#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#810f7c', '#4d004b'],
  2787. Oranges: ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704'],
  2788. BuGn: ['#f7fcfd', '#e5f5f9', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76', '#238b45', '#006d2c', '#00441b'],
  2789. YlOrBr: ['#ffffe5', '#fff7bc', '#fee391', '#fec44f', '#fe9929', '#ec7014', '#cc4c02', '#993404', '#662506'],
  2790. YlGn: ['#ffffe5', '#f7fcb9', '#d9f0a3', '#addd8e', '#78c679', '#41ab5d', '#238443', '#006837', '#004529'],
  2791. Reds: ['#fff5f0', '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', '#ef3b2c', '#cb181d', '#a50f15', '#67000d'],
  2792. RdPu: ['#fff7f3', '#fde0dd', '#fcc5c0', '#fa9fb5', '#f768a1', '#dd3497', '#ae017e', '#7a0177', '#49006a'],
  2793. Greens: ['#f7fcf5', '#e5f5e0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#006d2c', '#00441b'],
  2794. YlGnBu: ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58'],
  2795. Purples: ['#fcfbfd', '#efedf5', '#dadaeb', '#bcbddc', '#9e9ac8', '#807dba', '#6a51a3', '#54278f', '#3f007d'],
  2796. GnBu: ['#f7fcf0', '#e0f3db', '#ccebc5', '#a8ddb5', '#7bccc4', '#4eb3d3', '#2b8cbe', '#0868ac', '#084081'],
  2797. Greys: ['#ffffff', '#f0f0f0', '#d9d9d9', '#bdbdbd', '#969696', '#737373', '#525252', '#252525', '#000000'],
  2798. YlOrRd: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026'],
  2799. PuRd: ['#f7f4f9', '#e7e1ef', '#d4b9da', '#c994c7', '#df65b0', '#e7298a', '#ce1256', '#980043', '#67001f'],
  2800. Blues: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],
  2801. PuBuGn: ['#fff7fb', '#ece2f0', '#d0d1e6', '#a6bddb', '#67a9cf', '#3690c0', '#02818a', '#016c59', '#014636'],
  2802. Viridis: ['#440154', '#482777', '#3f4a8a', '#31678e', '#26838f', '#1f9d8a', '#6cce5a', '#b6de2b', '#fee825'],
  2803. // diverging
  2804. Spectral: ['#9e0142', '#d53e4f', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#e6f598', '#abdda4', '#66c2a5', '#3288bd', '#5e4fa2'],
  2805. RdYlGn: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850', '#006837'],
  2806. RdBu: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#f7f7f7', '#d1e5f0', '#92c5de', '#4393c3', '#2166ac', '#053061'],
  2807. PiYG: ['#8e0152', '#c51b7d', '#de77ae', '#f1b6da', '#fde0ef', '#f7f7f7', '#e6f5d0', '#b8e186', '#7fbc41', '#4d9221', '#276419'],
  2808. PRGn: ['#40004b', '#762a83', '#9970ab', '#c2a5cf', '#e7d4e8', '#f7f7f7', '#d9f0d3', '#a6dba0', '#5aae61', '#1b7837', '#00441b'],
  2809. RdYlBu: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'],
  2810. BrBG: ['#543005', '#8c510a', '#bf812d', '#dfc27d', '#f6e8c3', '#f5f5f5', '#c7eae5', '#80cdc1', '#35978f', '#01665e', '#003c30'],
  2811. RdGy: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#ffffff', '#e0e0e0', '#bababa', '#878787', '#4d4d4d', '#1a1a1a'],
  2812. PuOr: ['#7f3b08', '#b35806', '#e08214', '#fdb863', '#fee0b6', '#f7f7f7', '#d8daeb', '#b2abd2', '#8073ac', '#542788', '#2d004b'],
  2813. // qualitative
  2814. Set2: ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3'],
  2815. Accent: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666'],
  2816. Set1: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'],
  2817. Set3: ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f'],
  2818. Dark2: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'],
  2819. Paired: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],
  2820. Pastel2: ['#b3e2cd', '#fdcdac', '#cbd5e8', '#f4cae4', '#e6f5c9', '#fff2ae', '#f1e2cc', '#cccccc'],
  2821. Pastel1: ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2'],
  2822. };
  2823. // add lowercase aliases for case-insensitive matches
  2824. for (var i$1 = 0, list$1 = Object.keys(colorbrewer); i$1 < list$1.length; i$1 += 1) {
  2825. var key = list$1[i$1];
  2826. colorbrewer[key.toLowerCase()] = colorbrewer[key];
  2827. }
  2828. var colorbrewer_1 = colorbrewer;
  2829. // feel free to comment out anything to rollup
  2830. // a smaller chroma.js built
  2831. // io --> convert colors
  2832. // operators --> modify existing Colors
  2833. // interpolators
  2834. // generators -- > create new colors
  2835. chroma_1.average = average;
  2836. chroma_1.bezier = bezier_1;
  2837. chroma_1.blend = blend_1;
  2838. chroma_1.cubehelix = cubehelix;
  2839. chroma_1.mix = chroma_1.interpolate = mix;
  2840. chroma_1.random = random_1;
  2841. chroma_1.scale = scale;
  2842. // other utility methods
  2843. chroma_1.analyze = analyze_1.analyze;
  2844. chroma_1.contrast = contrast;
  2845. chroma_1.deltaE = deltaE;
  2846. chroma_1.distance = distance;
  2847. chroma_1.limits = analyze_1.limits;
  2848. chroma_1.valid = valid;
  2849. // scale
  2850. chroma_1.scales = scales;
  2851. // colors
  2852. chroma_1.colors = w3cx11_1;
  2853. chroma_1.brewer = colorbrewer_1;
  2854. var chroma_js = chroma_1;
  2855. return chroma_js;
  2856. })));
  2857. });
  2858. function generateColorVariables(key, format, colorStr, opacity, altFormats = []) {
  2859. const parsedColor = chroma(colorStr);
  2860. const alts = altFormats.reduce((a, alt) => {
  2861. a.push(...generateColorVariables(alt.id, alt.format, colorStr, opacity));
  2862. return a;
  2863. }, []);
  2864. switch (format) {
  2865. case 'hex':
  2866. return [{ key, value: colorStr }, ...alts];
  2867. case 'hsl':
  2868. return [
  2869. {
  2870. key,
  2871. value: parsedColor.css('hsl'),
  2872. },
  2873. ...alts,
  2874. ];
  2875. case 'hsl-values': {
  2876. const hsl = parsedColor.hsl();
  2877. const alpha = opacity ? `,${parsedColor.alpha()}` : '';
  2878. const h = isNaN(hsl[0]) ? 0 : hsl[0];
  2879. return [
  2880. {
  2881. key,
  2882. value: `${h},${hsl[1] * 100}%,${hsl[2] * 100}%${alpha}`,
  2883. },
  2884. ...alts,
  2885. ];
  2886. }
  2887. case 'hsl-split': {
  2888. const hsl = parsedColor.hsl();
  2889. const h = isNaN(hsl[0]) ? 0 : hsl[0];
  2890. const out = [
  2891. {
  2892. key: `${key}-h`,
  2893. value: h.toString(),
  2894. },
  2895. {
  2896. key: `${key}-s`,
  2897. value: (hsl[1] * 100).toString() + '%',
  2898. },
  2899. {
  2900. key: `${key}-l`,
  2901. value: (hsl[2] * 100).toString() + '%',
  2902. },
  2903. ...alts,
  2904. ];
  2905. if (opacity)
  2906. out.push({
  2907. key: `${key}-a`,
  2908. value: parsedColor.alpha().toString(),
  2909. });
  2910. return out;
  2911. }
  2912. case 'hsl-split-decimal': {
  2913. const hsl = parsedColor.hsl();
  2914. const h = isNaN(hsl[0]) ? 0 : hsl[0];
  2915. const out = [
  2916. {
  2917. key: `${key}-h`,
  2918. value: h.toString(),
  2919. },
  2920. {
  2921. key: `${key}-s`,
  2922. value: hsl[1].toString(),
  2923. },
  2924. {
  2925. key: `${key}-l`,
  2926. value: hsl[2].toString(),
  2927. },
  2928. ...alts,
  2929. ];
  2930. if (opacity)
  2931. out.push({
  2932. key: `${key}-a`,
  2933. value: parsedColor.alpha().toString(),
  2934. });
  2935. return out;
  2936. }
  2937. case 'rgb':
  2938. return [
  2939. {
  2940. key,
  2941. value: parsedColor.css(),
  2942. },
  2943. ...alts,
  2944. ];
  2945. case 'rgb-values': {
  2946. const rgb = parsedColor.rgb();
  2947. const alpha = opacity ? `,${parsedColor.alpha()}` : '';
  2948. return [
  2949. {
  2950. key,
  2951. value: `${rgb[0]},${rgb[1]},${rgb[2]}${alpha}`,
  2952. },
  2953. ...alts,
  2954. ];
  2955. }
  2956. case 'rgb-split': {
  2957. const rgb = parsedColor.rgb();
  2958. const out = [
  2959. {
  2960. key: `${key}-r`,
  2961. value: rgb[0].toString(),
  2962. },
  2963. {
  2964. key: `${key}-g`,
  2965. value: rgb[1].toString(),
  2966. },
  2967. {
  2968. key: `${key}-b`,
  2969. value: rgb[2].toString(),
  2970. },
  2971. ...alts,
  2972. ];
  2973. if (opacity)
  2974. out.push({
  2975. key: `${key}-a`,
  2976. value: parsedColor.alpha().toString(),
  2977. });
  2978. return out;
  2979. }
  2980. }
  2981. }
  2982. function pushColors(arr, id, from, to, format, step, pad) {
  2983. const scale = chroma.scale([from.trim(), to.trim()]).domain([0, 100]);
  2984. for (let i = 0; i <= 100; i++) {
  2985. if (i % step === 0) {
  2986. const c = scale(i);
  2987. arr.push(...generateColorVariables(`${id}-${i.toString().padStart(pad, '0')}`, format, c.css(), c.alpha() !== 1));
  2988. }
  2989. }
  2990. }
  2991. function getCSSVariables(settings, config, gradients, settingsManager) {
  2992. const vars = [];
  2993. const themedLight = [];
  2994. const themedDark = [];
  2995. const gradientCandidates = {};
  2996. const gradientCandidatesLight = {};
  2997. const gradientCandidatesDark = {};
  2998. const seenGradientSections = new Set();
  2999. for (const key in settings) {
  3000. const [sectionId, settingId, modifier] = key.split('@@');
  3001. const section = config[sectionId];
  3002. if (!section)
  3003. continue;
  3004. const setting = config[sectionId][settingId];
  3005. if (!setting)
  3006. continue;
  3007. const value = settings[key];
  3008. switch (setting.type) {
  3009. case SettingType.VARIABLE_NUMBER:
  3010. case SettingType.VARIABLE_NUMBER_SLIDER: {
  3011. const format = setting
  3012. .format;
  3013. const val = value !== undefined
  3014. ? value
  3015. : setting.default;
  3016. vars.push({
  3017. key: setting.id,
  3018. value: `${val}${format || ''}`,
  3019. });
  3020. continue;
  3021. }
  3022. case SettingType.VARIABLE_TEXT:
  3023. case SettingType.VARIABLE_SELECT: {
  3024. const format_text = setting;
  3025. let text = value !== undefined
  3026. ? value.toString()
  3027. : format_text.default.toString();
  3028. if (format_text.quotes) {
  3029. if (text !== `""`) {
  3030. text = `'${text}'`;
  3031. }
  3032. else {
  3033. text = ``;
  3034. }
  3035. }
  3036. vars.push({
  3037. key: setting.id,
  3038. value: text,
  3039. });
  3040. continue;
  3041. }
  3042. case SettingType.VARIABLE_COLOR: {
  3043. if (!seenGradientSections.has(sectionId))
  3044. seenGradientSections.add(sectionId);
  3045. const colorSetting = setting;
  3046. const color = value !== undefined ? value.toString() : colorSetting.default;
  3047. vars.push(...generateColorVariables(setting.id, colorSetting.format, color, colorSetting.opacity, colorSetting['alt-format']));
  3048. generateColorVariables(setting.id, 'rgb', color, colorSetting.opacity).forEach((kv) => {
  3049. gradientCandidates[kv.key] = kv.value;
  3050. });
  3051. continue;
  3052. }
  3053. case SettingType.VARIABLE_THEMED_COLOR: {
  3054. if (!seenGradientSections.has(sectionId))
  3055. seenGradientSections.add(sectionId);
  3056. const colorSetting = setting;
  3057. const colorKey = modifier === 'light' ? 'default-light' : 'default-dark';
  3058. const color = value !== undefined ? value.toString() : colorSetting[colorKey];
  3059. (modifier === 'light' ? themedLight : themedDark).push(...generateColorVariables(setting.id, colorSetting.format, color, colorSetting.opacity, colorSetting['alt-format']));
  3060. generateColorVariables(setting.id, 'rgb', color, colorSetting.opacity).forEach((kv) => {
  3061. if (modifier === 'light') {
  3062. gradientCandidatesLight[kv.key] = kv.value;
  3063. }
  3064. else {
  3065. gradientCandidatesDark[kv.key] = kv.value;
  3066. }
  3067. });
  3068. continue;
  3069. }
  3070. }
  3071. }
  3072. seenGradientSections.forEach((sectionId) => {
  3073. const g = gradients[sectionId];
  3074. if (!g)
  3075. return;
  3076. g.forEach((def) => {
  3077. var _a, _b, _c;
  3078. const { from, to, format, step, id, pad = 0 } = def;
  3079. if (gradientCandidatesLight[from]) {
  3080. const fromColor = gradientCandidatesLight[from];
  3081. const toColor = gradientCandidatesLight[to] ||
  3082. ((_a = settingsManager.plugin.getCSSVar(to).light) === null || _a === void 0 ? void 0 : _a.trim());
  3083. if (toColor) {
  3084. pushColors(themedLight, id, fromColor, toColor, format, step, pad);
  3085. }
  3086. }
  3087. if (gradientCandidatesDark[from]) {
  3088. const fromColor = gradientCandidatesDark[from];
  3089. const toColor = gradientCandidatesDark[to] ||
  3090. ((_b = settingsManager.plugin.getCSSVar(to).dark) === null || _b === void 0 ? void 0 : _b.trim());
  3091. if (toColor) {
  3092. pushColors(themedDark, id, fromColor, toColor, format, step, pad);
  3093. }
  3094. }
  3095. if (gradientCandidates[from]) {
  3096. const fromColor = gradientCandidates[from];
  3097. const toColor = gradientCandidates[to] ||
  3098. ((_c = settingsManager.plugin.getCSSVar(to).current) === null || _c === void 0 ? void 0 : _c.trim());
  3099. if (toColor) {
  3100. pushColors(vars, id, fromColor, toColor, format, step, pad);
  3101. }
  3102. }
  3103. });
  3104. });
  3105. return [vars, themedLight, themedDark];
  3106. }
  3107. class CSSSettingsManager {
  3108. constructor(plugin) {
  3109. this.config = {};
  3110. this.gradients = {};
  3111. this.plugin = plugin;
  3112. this.settings = {};
  3113. this.styleTag = document.createElement('style');
  3114. this.styleTag.id = 'css-settings-manager';
  3115. document.getElementsByTagName('head')[0].appendChild(this.styleTag);
  3116. }
  3117. cleanup() {
  3118. this.styleTag.remove();
  3119. this.removeClasses();
  3120. }
  3121. save() {
  3122. return __awaiter(this, void 0, void 0, function* () {
  3123. yield this.plugin.saveData(this.settings);
  3124. this.setCSSVariables();
  3125. });
  3126. }
  3127. load() {
  3128. return __awaiter(this, void 0, void 0, function* () {
  3129. this.settings = Object.assign({}, yield this.plugin.loadData());
  3130. });
  3131. }
  3132. initClasses() {
  3133. Object.keys(this.config).forEach((section) => {
  3134. const config = this.config[section];
  3135. Object.keys(config).forEach((settingId) => {
  3136. const setting = config[settingId];
  3137. if (setting.type === SettingType.CLASS_TOGGLE) {
  3138. const classToggle = setting;
  3139. const value = this.getSetting(section, settingId);
  3140. if (value === true ||
  3141. (value === undefined && classToggle.default === true)) {
  3142. document.body.classList.add(setting.id);
  3143. }
  3144. }
  3145. else if (setting.type === SettingType.CLASS_SELECT) {
  3146. const multiToggle = setting;
  3147. let value = this.getSetting(section, settingId);
  3148. if (value === undefined && !!multiToggle.default) {
  3149. value = multiToggle.default;
  3150. }
  3151. else if (value === undefined) {
  3152. value = 'none';
  3153. }
  3154. if (value !== 'none') {
  3155. document.body.classList.add(value);
  3156. }
  3157. }
  3158. });
  3159. });
  3160. }
  3161. removeClasses() {
  3162. Object.keys(this.config).forEach((section) => {
  3163. const config = this.config[section];
  3164. Object.keys(config).forEach((settingId) => {
  3165. const setting = config[settingId];
  3166. if (setting.type === SettingType.CLASS_TOGGLE) {
  3167. document.body.classList.remove(setting.id);
  3168. }
  3169. else if (setting.type === SettingType.CLASS_SELECT) {
  3170. const multiToggle = setting;
  3171. multiToggle.options.forEach((v) => {
  3172. if (typeof v === 'string') {
  3173. document.body.classList.remove(v);
  3174. }
  3175. else {
  3176. document.body.classList.remove(v.value);
  3177. }
  3178. });
  3179. }
  3180. });
  3181. });
  3182. }
  3183. setCSSVariables() {
  3184. const [vars, themedLight, themedDark] = getCSSVariables(this.settings, this.config, this.gradients, this);
  3185. this.styleTag.innerText = `
  3186. body.css-settings-manager {
  3187. ${vars.reduce((combined, current) => {
  3188. return combined + `--${current.key}: ${current.value}; `;
  3189. }, '')}
  3190. }
  3191. body.theme-light.css-settings-manager {
  3192. ${themedLight.reduce((combined, current) => {
  3193. return combined + `--${current.key}: ${current.value}; `;
  3194. }, '')}
  3195. }
  3196. body.theme-dark.css-settings-manager {
  3197. ${themedDark.reduce((combined, current) => {
  3198. return combined + `--${current.key}: ${current.value}; `;
  3199. }, '')}
  3200. }
  3201. `
  3202. .trim()
  3203. .replace(/[\r\n\s]+/g, ' ');
  3204. this.plugin.app.workspace.trigger('css-change', {
  3205. source: 'style-settings',
  3206. });
  3207. }
  3208. setConfig(settings) {
  3209. this.config = {};
  3210. this.gradients = {};
  3211. settings.forEach((s) => {
  3212. this.config[s.id] = {};
  3213. s.settings.forEach((setting) => {
  3214. this.config[s.id][setting.id] = setting;
  3215. if (setting.type === SettingType.COLOR_GRADIENT) {
  3216. if (!this.gradients[s.id])
  3217. this.gradients[s.id] = [];
  3218. this.gradients[s.id].push(setting);
  3219. }
  3220. });
  3221. });
  3222. let pruned = false;
  3223. for (const key in this.settings) {
  3224. const [sectionId, settingId] = key.split('@@');
  3225. if (this.config[sectionId] && !this.config[sectionId][settingId]) {
  3226. delete this.settings[key];
  3227. pruned = true;
  3228. }
  3229. }
  3230. if (pruned) {
  3231. this.save();
  3232. }
  3233. else {
  3234. this.setCSSVariables();
  3235. }
  3236. }
  3237. getSetting(sectionId, settingId) {
  3238. return this.settings[`${sectionId}@@${settingId}`];
  3239. }
  3240. getSettings(sectionId, ids) {
  3241. return ids.reduce((settings, id) => {
  3242. const fullId = `${sectionId}@@${id}`;
  3243. const alts = ['dark', 'light'];
  3244. if (this.settings[fullId]) {
  3245. settings[fullId] = this.settings[fullId];
  3246. }
  3247. alts.forEach((alt) => {
  3248. const id = `${fullId}@@${alt}`;
  3249. if (this.settings[id]) {
  3250. settings[id] = this.settings[id];
  3251. }
  3252. });
  3253. return settings;
  3254. }, {});
  3255. }
  3256. setSetting(sectionId, settingId, value) {
  3257. this.settings[`${sectionId}@@${settingId}`] = value;
  3258. this.save();
  3259. this.removeClasses();
  3260. this.initClasses();
  3261. }
  3262. setSettings(settings) {
  3263. Object.keys(settings).forEach((id) => {
  3264. this.settings[id] = settings[id];
  3265. });
  3266. this.removeClasses();
  3267. this.initClasses();
  3268. return this.save();
  3269. }
  3270. clearSetting(sectionId, settingId) {
  3271. delete this.settings[`${sectionId}@@${settingId}`];
  3272. this.save();
  3273. this.removeClasses();
  3274. this.initClasses();
  3275. }
  3276. clearSection(sectionId) {
  3277. Object.keys(this.settings).forEach((key) => {
  3278. const [section] = key.split('@@');
  3279. if (section === sectionId) {
  3280. delete this.settings[key];
  3281. }
  3282. });
  3283. this.save();
  3284. this.removeClasses();
  3285. this.initClasses();
  3286. }
  3287. export(section, config) {
  3288. new ExportModal(this.plugin.app, this.plugin, section, config).open();
  3289. }
  3290. import() {
  3291. new ImportModal(this.plugin.app, this.plugin).open();
  3292. }
  3293. }
  3294. const ar = {};
  3295. const cz = {};
  3296. const da = {};
  3297. const de = {
  3298. 'Default:': 'Standard:',
  3299. 'Error:': 'Fehler:',
  3300. 'missing default light value, or value is not in a valid color format': 'Fehlender heller standard Wert oder Wert ist in keinem validen Farb-Format',
  3301. 'missing default dark value, or value is not in a valid color format': 'Fehlender dunkler standard Wert oder Wert ist in keinem validen Farb-Format',
  3302. 'missing default value, or value is not in a valid color format': 'Fehlender standard Wert oder Wert ist in keinem validen Farb-Format',
  3303. 'missing default value': 'Fehlender standard Wert',
  3304. };
  3305. const en = {
  3306. 'Default:': 'Default:',
  3307. 'Error:': 'Error:',
  3308. 'missing default light value, or value is not in a valid color format': 'missing default light value, or value is not in a valid color format',
  3309. 'missing default dark value, or value is not in a valid color format': 'missing default dark value, or value is not in a valid color format',
  3310. 'missing default value, or value is not in a valid color format': 'missing default value, or value is not in a valid color format',
  3311. 'missing default value': 'missing default value',
  3312. };
  3313. const es = {};
  3314. const fr = {};
  3315. const hi = {};
  3316. const id = {};
  3317. const it = {};
  3318. const ja = {};
  3319. const ko = {};
  3320. const nl = {
  3321. 'Default:': 'Standaard:',
  3322. 'Error:': 'Error:',
  3323. 'missing default light value, or value is not in a valid color format': 'Geen standaard waarde voor het lichte thema, of de waarde is niet in het goede formaat',
  3324. 'missing default dark value, or value is not in a valid color format': 'Geen standaard waarde voor het donkere thema, of de waarde is niet in het goede formaat',
  3325. 'missing default value, or value is not in a valid color format': 'Geen standaard waarde, of de waarde is niet in het goede formaat',
  3326. 'missing default value': 'Geen standaard waarde',
  3327. };
  3328. const no = {};
  3329. const pl = {};
  3330. const pt = {};
  3331. const ptBr = {};
  3332. const ro = {};
  3333. const ru = {};
  3334. const sq = {};
  3335. const tr = {};
  3336. const uk = {};
  3337. const zh = {
  3338. 'Default:': '默认:',
  3339. 'Error:': '错误:',
  3340. 'missing default light value, or value is not in a valid color format': '缺少默认的浅色模式色值,或该色值没有采用一个有效的颜色格式',
  3341. 'missing default dark value, or value is not in a valid color format': '缺少默认的深色模式色值,或该色值没有采用一个有效的颜色格式',
  3342. 'missing default value, or value is not in a valid color format': '缺少默认色值,或该色值没有采用一个有效的颜色格式',
  3343. 'missing default value': '缺少默认色值',
  3344. };
  3345. const zhTw = {};
  3346. const lang = window.localStorage.getItem('language');
  3347. const localeMap = {
  3348. ar,
  3349. cz,
  3350. da,
  3351. de,
  3352. en,
  3353. es,
  3354. fr,
  3355. hi,
  3356. id,
  3357. it,
  3358. ja,
  3359. ko,
  3360. nl,
  3361. no,
  3362. pl,
  3363. 'pt-BR': ptBr,
  3364. pt,
  3365. ro,
  3366. ru,
  3367. sq,
  3368. tr,
  3369. uk,
  3370. 'zh-TW': zhTw,
  3371. zh,
  3372. };
  3373. const locale = localeMap[lang || 'en'];
  3374. function t(str) {
  3375. if (!locale) {
  3376. console.error('Error: Style Settings locale not found', lang);
  3377. }
  3378. return (locale && locale[str]) || en[str];
  3379. }
  3380. const settingRegExp = /\/\*!?\s*@settings[\r\n]+?([\s\S]+?)\*\//g;
  3381. const nameRegExp = /^name:\s*(.+)$/m;
  3382. function getTitle(config) {
  3383. if (lang) {
  3384. return config[`title.${lang}`] || config.title;
  3385. }
  3386. return config.title;
  3387. }
  3388. function getDescription(config) {
  3389. if (lang) {
  3390. return (config[`description.${lang}`] ||
  3391. config.description);
  3392. }
  3393. return config.description;
  3394. }
  3395. function isValidDefaultColor(color) {
  3396. return /^(#|rgb|hsl)/.test(color);
  3397. }
  3398. function getPickrSettings(opts) {
  3399. const { el, isView, containerEl, swatches, opacity, defaultColor } = opts;
  3400. return {
  3401. el,
  3402. container: isView ? document.body : containerEl,
  3403. theme: 'nano',
  3404. swatches,
  3405. lockOpacity: !opacity,
  3406. default: defaultColor,
  3407. position: 'left-middle',
  3408. components: {
  3409. preview: true,
  3410. hue: true,
  3411. opacity: !!opacity,
  3412. interaction: {
  3413. hex: true,
  3414. rgba: true,
  3415. hsla: true,
  3416. input: true,
  3417. cancel: true,
  3418. save: true,
  3419. },
  3420. },
  3421. };
  3422. }
  3423. function onPickrCancel(instance) {
  3424. instance.hide();
  3425. }
  3426. function sanitizeText(str) {
  3427. if (str === '') {
  3428. return `""`;
  3429. }
  3430. return str.replace(/[;<>]/g, '');
  3431. }
  3432. function createDescription(description, def, defLabel) {
  3433. const fragment = createFragment();
  3434. if (description) {
  3435. fragment.appendChild(document.createTextNode(description));
  3436. }
  3437. if (def) {
  3438. const small = createEl('small');
  3439. small.appendChild(createEl('strong', { text: `${t('Default:')} ` }));
  3440. small.appendChild(document.createTextNode(defLabel || def));
  3441. const div = createEl('div');
  3442. div.appendChild(small);
  3443. fragment.appendChild(div);
  3444. }
  3445. return fragment;
  3446. }
  3447. var fuzzysort = createCommonjsModule(function (module) {
  3448. ((root, UMD) => {
  3449. if(module.exports) module.exports = UMD();
  3450. else root['fuzzysort'] = UMD();
  3451. })(commonjsGlobal, _ => {
  3452. var single = (search, target) => { if(search=='farzher')return {target:"farzher was here (^-^*)/",score:0,_indexes:[0]}
  3453. if(!search || !target) return NULL
  3454. var preparedSearch = getPreparedSearch(search);
  3455. if(!isObj(target)) target = getPrepared(target);
  3456. var searchBitflags = preparedSearch.bitflags;
  3457. if((searchBitflags & target._bitflags) !== searchBitflags) return NULL
  3458. return algorithm(preparedSearch, target)
  3459. };
  3460. var go = (search, targets, options) => { if(search=='farzher')return [{target:"farzher was here (^-^*)/",score:0,_indexes:[0],obj:targets?targets[0]:NULL}]
  3461. if(!search) return options&&options.all ? all(search, targets, options) : noResults
  3462. var preparedSearch = getPreparedSearch(search);
  3463. var searchBitflags = preparedSearch.bitflags;
  3464. preparedSearch.containsSpace;
  3465. var threshold = options&&options.threshold || INT_MIN;
  3466. var limit = options&&options['limit'] || INT_MAX; // for some reason only limit breaks when minified
  3467. var resultsLen = 0; var limitedCount = 0;
  3468. var targetsLen = targets.length;
  3469. // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys]
  3470. // options.key
  3471. if(options && options.key) {
  3472. var key = options.key;
  3473. for(var i = 0; i < targetsLen; ++i) { var obj = targets[i];
  3474. var target = getValue(obj, key);
  3475. if(!target) continue
  3476. if(!isObj(target)) target = getPrepared(target);
  3477. if((searchBitflags & target._bitflags) !== searchBitflags) continue
  3478. var result = algorithm(preparedSearch, target);
  3479. if(result === NULL) continue
  3480. if(result.score < threshold) continue
  3481. // have to clone result so duplicate targets from different obj can each reference the correct obj
  3482. result = {target:result.target, _targetLower:'', _targetLowerCodes:NULL, _nextBeginningIndexes:NULL, _bitflags:0, score:result.score, _indexes:result._indexes, obj:obj}; // hidden
  3483. if(resultsLen < limit) { q.add(result); ++resultsLen; }
  3484. else {
  3485. ++limitedCount;
  3486. if(result.score > q.peek().score) q.replaceTop(result);
  3487. }
  3488. }
  3489. // options.keys
  3490. } else if(options && options.keys) {
  3491. var scoreFn = options['scoreFn'] || defaultScoreFn;
  3492. var keys = options.keys;
  3493. var keysLen = keys.length;
  3494. for(var i = 0; i < targetsLen; ++i) { var obj = targets[i];
  3495. var objResults = new Array(keysLen);
  3496. for (var keyI = 0; keyI < keysLen; ++keyI) {
  3497. var key = keys[keyI];
  3498. var target = getValue(obj, key);
  3499. if(!target) { objResults[keyI] = NULL; continue }
  3500. if(!isObj(target)) target = getPrepared(target);
  3501. if((searchBitflags & target._bitflags) !== searchBitflags) objResults[keyI] = NULL;
  3502. else objResults[keyI] = algorithm(preparedSearch, target);
  3503. }
  3504. objResults.obj = obj; // before scoreFn so scoreFn can use it
  3505. var score = scoreFn(objResults);
  3506. if(score === NULL) continue
  3507. if(score < threshold) continue
  3508. objResults.score = score;
  3509. if(resultsLen < limit) { q.add(objResults); ++resultsLen; }
  3510. else {
  3511. ++limitedCount;
  3512. if(score > q.peek().score) q.replaceTop(objResults);
  3513. }
  3514. }
  3515. // no keys
  3516. } else {
  3517. for(var i = 0; i < targetsLen; ++i) { var target = targets[i];
  3518. if(!target) continue
  3519. if(!isObj(target)) target = getPrepared(target);
  3520. if((searchBitflags & target._bitflags) !== searchBitflags) continue
  3521. var result = algorithm(preparedSearch, target);
  3522. if(result === NULL) continue
  3523. if(result.score < threshold) continue
  3524. if(resultsLen < limit) { q.add(result); ++resultsLen; }
  3525. else {
  3526. ++limitedCount;
  3527. if(result.score > q.peek().score) q.replaceTop(result);
  3528. }
  3529. }
  3530. }
  3531. if(resultsLen === 0) return noResults
  3532. var results = new Array(resultsLen);
  3533. for(var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll();
  3534. results.total = resultsLen + limitedCount;
  3535. return results
  3536. };
  3537. var highlight = (result, hOpen, hClose) => {
  3538. if(typeof hOpen === 'function') return highlightCallback(result, hOpen)
  3539. if(result === NULL) return NULL
  3540. if(hOpen === undefined) hOpen = '<b>';
  3541. if(hClose === undefined) hClose = '</b>';
  3542. var highlighted = '';
  3543. var matchesIndex = 0;
  3544. var opened = false;
  3545. var target = result.target;
  3546. var targetLen = target.length;
  3547. var indexes = result._indexes;
  3548. indexes = indexes.slice(0, indexes.len).sort((a,b)=>a-b);
  3549. for(var i = 0; i < targetLen; ++i) { var char = target[i];
  3550. if(indexes[matchesIndex] === i) {
  3551. ++matchesIndex;
  3552. if(!opened) { opened = true;
  3553. highlighted += hOpen;
  3554. }
  3555. if(matchesIndex === indexes.length) {
  3556. highlighted += char + hClose + target.substr(i+1);
  3557. break
  3558. }
  3559. } else {
  3560. if(opened) { opened = false;
  3561. highlighted += hClose;
  3562. }
  3563. }
  3564. highlighted += char;
  3565. }
  3566. return highlighted
  3567. };
  3568. var highlightCallback = (result, cb) => {
  3569. if(result === NULL) return NULL
  3570. var target = result.target;
  3571. var targetLen = target.length;
  3572. var indexes = result._indexes;
  3573. indexes = indexes.slice(0, indexes.len).sort((a,b)=>a-b);
  3574. var highlighted = '';
  3575. var matchI = 0;
  3576. var indexesI = 0;
  3577. var opened = false;
  3578. var result = [];
  3579. for(var i = 0; i < targetLen; ++i) { var char = target[i];
  3580. if(indexes[indexesI] === i) {
  3581. ++indexesI;
  3582. if(!opened) { opened = true;
  3583. result.push(highlighted); highlighted = '';
  3584. }
  3585. if(indexesI === indexes.length) {
  3586. highlighted += char;
  3587. result.push(cb(highlighted, matchI++)); highlighted = '';
  3588. result.push(target.substr(i+1));
  3589. break
  3590. }
  3591. } else {
  3592. if(opened) { opened = false;
  3593. result.push(cb(highlighted, matchI++)); highlighted = '';
  3594. }
  3595. }
  3596. highlighted += char;
  3597. }
  3598. return result
  3599. };
  3600. var indexes = result => result._indexes.slice(0, result._indexes.len).sort((a,b)=>a-b);
  3601. var prepare = (target) => {
  3602. if(typeof target !== 'string') target = '';
  3603. var info = prepareLowerInfo(target);
  3604. return {'target':target, _targetLower:info._lower, _targetLowerCodes:info.lowerCodes, _nextBeginningIndexes:NULL, _bitflags:info.bitflags, 'score':NULL, _indexes:[0], 'obj':NULL} // hidden
  3605. };
  3606. // Below this point is only internal code
  3607. // Below this point is only internal code
  3608. // Below this point is only internal code
  3609. // Below this point is only internal code
  3610. var prepareSearch = (search) => {
  3611. if(typeof search !== 'string') search = '';
  3612. search = search.trim();
  3613. var info = prepareLowerInfo(search);
  3614. var spaceSearches = [];
  3615. if(info.containsSpace) {
  3616. var searches = search.split(/\s+/);
  3617. searches = [...new Set(searches)]; // distinct
  3618. for(var i=0; i<searches.length; i++) {
  3619. if(searches[i] === '') continue
  3620. var _info = prepareLowerInfo(searches[i]);
  3621. spaceSearches.push({lowerCodes:_info.lowerCodes, _lower:searches[i].toLowerCase(), containsSpace:false});
  3622. }
  3623. }
  3624. return {lowerCodes: info.lowerCodes, bitflags: info.bitflags, containsSpace: info.containsSpace, _lower: info._lower, spaceSearches: spaceSearches}
  3625. };
  3626. var getPrepared = (target) => {
  3627. if(target.length > 999) return prepare(target) // don't cache huge targets
  3628. var targetPrepared = preparedCache.get(target);
  3629. if(targetPrepared !== undefined) return targetPrepared
  3630. targetPrepared = prepare(target);
  3631. preparedCache.set(target, targetPrepared);
  3632. return targetPrepared
  3633. };
  3634. var getPreparedSearch = (search) => {
  3635. if(search.length > 999) return prepareSearch(search) // don't cache huge searches
  3636. var searchPrepared = preparedSearchCache.get(search);
  3637. if(searchPrepared !== undefined) return searchPrepared
  3638. searchPrepared = prepareSearch(search);
  3639. preparedSearchCache.set(search, searchPrepared);
  3640. return searchPrepared
  3641. };
  3642. var all = (search, targets, options) => {
  3643. var results = []; results.total = targets.length;
  3644. var limit = options && options.limit || INT_MAX;
  3645. if(options && options.key) {
  3646. for(var i=0;i<targets.length;i++) { var obj = targets[i];
  3647. var target = getValue(obj, options.key);
  3648. if(!target) continue
  3649. if(!isObj(target)) target = getPrepared(target);
  3650. target.score = INT_MIN;
  3651. target._indexes.len = 0;
  3652. var result = target;
  3653. result = {target:result.target, _targetLower:'', _targetLowerCodes:NULL, _nextBeginningIndexes:NULL, _bitflags:0, score:target.score, _indexes:NULL, obj:obj}; // hidden
  3654. results.push(result); if(results.length >= limit) return results
  3655. }
  3656. } else if(options && options.keys) {
  3657. for(var i=0;i<targets.length;i++) { var obj = targets[i];
  3658. var objResults = new Array(options.keys.length);
  3659. for (var keyI = options.keys.length - 1; keyI >= 0; --keyI) {
  3660. var target = getValue(obj, options.keys[keyI]);
  3661. if(!target) { objResults[keyI] = NULL; continue }
  3662. if(!isObj(target)) target = getPrepared(target);
  3663. target.score = INT_MIN;
  3664. target._indexes.len = 0;
  3665. objResults[keyI] = target;
  3666. }
  3667. objResults.obj = obj;
  3668. objResults.score = INT_MIN;
  3669. results.push(objResults); if(results.length >= limit) return results
  3670. }
  3671. } else {
  3672. for(var i=0;i<targets.length;i++) { var target = targets[i];
  3673. if(!target) continue
  3674. if(!isObj(target)) target = getPrepared(target);
  3675. target.score = INT_MIN;
  3676. target._indexes.len = 0;
  3677. results.push(target); if(results.length >= limit) return results
  3678. }
  3679. }
  3680. return results
  3681. };
  3682. var algorithm = (preparedSearch, prepared, allowSpaces=false) => {
  3683. if(allowSpaces===false && preparedSearch.containsSpace) return algorithmSpaces(preparedSearch, prepared)
  3684. var searchLower = preparedSearch._lower;
  3685. var searchLowerCodes = preparedSearch.lowerCodes;
  3686. var searchLowerCode = searchLowerCodes[0];
  3687. var targetLowerCodes = prepared._targetLowerCodes;
  3688. var searchLen = searchLowerCodes.length;
  3689. var targetLen = targetLowerCodes.length;
  3690. var searchI = 0; // where we at
  3691. var targetI = 0; // where you at
  3692. var matchesSimpleLen = 0;
  3693. // very basic fuzzy match; to remove non-matching targets ASAP!
  3694. // walk through target. find sequential matches.
  3695. // if all chars aren't found then exit
  3696. for(;;) {
  3697. var isMatch = searchLowerCode === targetLowerCodes[targetI];
  3698. if(isMatch) {
  3699. matchesSimple[matchesSimpleLen++] = targetI;
  3700. ++searchI; if(searchI === searchLen) break
  3701. searchLowerCode = searchLowerCodes[searchI];
  3702. }
  3703. ++targetI; if(targetI >= targetLen) return NULL // Failed to find searchI
  3704. }
  3705. var searchI = 0;
  3706. var successStrict = false;
  3707. var matchesStrictLen = 0;
  3708. var nextBeginningIndexes = prepared._nextBeginningIndexes;
  3709. if(nextBeginningIndexes === NULL) nextBeginningIndexes = prepared._nextBeginningIndexes = prepareNextBeginningIndexes(prepared.target);
  3710. targetI = matchesSimple[0]===0 ? 0 : nextBeginningIndexes[matchesSimple[0]-1];
  3711. // Our target string successfully matched all characters in sequence!
  3712. // Let's try a more advanced and strict test to improve the score
  3713. // only count it as a match if it's consecutive or a beginning character!
  3714. var backtrackCount = 0;
  3715. if(targetI !== targetLen) for(;;) {
  3716. if(targetI >= targetLen) {
  3717. // We failed to find a good spot for this search char, go back to the previous search char and force it forward
  3718. if(searchI <= 0) break // We failed to push chars forward for a better match
  3719. ++backtrackCount; if(backtrackCount > 200) break // exponential backtracking is taking too long, just give up and return a bad match
  3720. --searchI;
  3721. var lastMatch = matchesStrict[--matchesStrictLen];
  3722. targetI = nextBeginningIndexes[lastMatch];
  3723. } else {
  3724. var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI];
  3725. if(isMatch) {
  3726. matchesStrict[matchesStrictLen++] = targetI;
  3727. ++searchI; if(searchI === searchLen) { successStrict = true; break }
  3728. ++targetI;
  3729. } else {
  3730. targetI = nextBeginningIndexes[targetI];
  3731. }
  3732. }
  3733. }
  3734. // check if it's a substring match
  3735. var substringIndex = prepared._targetLower.indexOf(searchLower, matchesSimple[0]); // perf: this is slow
  3736. var isSubstring = ~substringIndex;
  3737. if(isSubstring && !successStrict) { // rewrite the indexes from basic to the substring
  3738. for(var i=0; i<matchesSimpleLen; ++i) matchesSimple[i] = substringIndex+i;
  3739. }
  3740. var isSubstringBeginning = false;
  3741. if(isSubstring) {
  3742. isSubstringBeginning = prepared._nextBeginningIndexes[substringIndex-1] === substringIndex;
  3743. }
  3744. { // tally up the score & keep track of matches for highlighting later
  3745. if(successStrict) { var matchesBest = matchesStrict; var matchesBestLen = matchesStrictLen; }
  3746. else { var matchesBest = matchesSimple; var matchesBestLen = matchesSimpleLen; }
  3747. var score = 0;
  3748. var extraMatchGroupCount = 0;
  3749. for(var i = 1; i < searchLen; ++i) {
  3750. if(matchesBest[i] - matchesBest[i-1] !== 1) {score -= matchesBest[i]; ++extraMatchGroupCount;}
  3751. }
  3752. var unmatchedDistance = matchesBest[searchLen-1] - matchesBest[0] - (searchLen-1);
  3753. score -= (12+unmatchedDistance) * extraMatchGroupCount; // penality for more groups
  3754. if(matchesBest[0] !== 0) score -= matchesBest[0]*matchesBest[0]*.2; // penality for not starting near the beginning
  3755. if(!successStrict) {
  3756. score *= 1000;
  3757. } else {
  3758. // successStrict on a target with too many beginning indexes loses points for being a bad target
  3759. var uniqueBeginningIndexes = 1;
  3760. for(var i = nextBeginningIndexes[0]; i < targetLen; i=nextBeginningIndexes[i]) ++uniqueBeginningIndexes;
  3761. if(uniqueBeginningIndexes > 24) score *= (uniqueBeginningIndexes-24)*10; // quite arbitrary numbers here ...
  3762. }
  3763. if(isSubstring) score /= 1+searchLen*searchLen*1; // bonus for being a full substring
  3764. if(isSubstringBeginning) score /= 1+searchLen*searchLen*1; // bonus for substring starting on a beginningIndex
  3765. score -= targetLen - searchLen; // penality for longer targets
  3766. prepared.score = score;
  3767. for(var i = 0; i < matchesBestLen; ++i) prepared._indexes[i] = matchesBest[i];
  3768. prepared._indexes.len = matchesBestLen;
  3769. return prepared
  3770. }
  3771. };
  3772. var algorithmSpaces = (preparedSearch, target) => {
  3773. var seen_indexes = new Set();
  3774. var score = 0;
  3775. var result = NULL;
  3776. var first_seen_index_last_search = 0;
  3777. var searches = preparedSearch.spaceSearches;
  3778. for(var i=0; i<searches.length; ++i) {
  3779. var search = searches[i];
  3780. result = algorithm(search, target);
  3781. if(result === NULL) return NULL
  3782. score += result.score;
  3783. // dock points based on order otherwise "c man" returns Manifest.cpp instead of CheatManager.h
  3784. if(result._indexes[0] < first_seen_index_last_search) {
  3785. score -= first_seen_index_last_search - result._indexes[0];
  3786. }
  3787. first_seen_index_last_search = result._indexes[0];
  3788. for(var j=0; j<result._indexes.len; ++j) seen_indexes.add(result._indexes[j]);
  3789. }
  3790. // allows a search with spaces that's an exact substring to score well
  3791. var allowSpacesResult = algorithm(preparedSearch, target, /*allowSpaces=*/true);
  3792. if(allowSpacesResult !== NULL && allowSpacesResult.score > score) {
  3793. return allowSpacesResult
  3794. }
  3795. result.score = score;
  3796. var i = 0;
  3797. for (let index of seen_indexes) result._indexes[i++] = index;
  3798. result._indexes.len = i;
  3799. return result
  3800. };
  3801. var prepareLowerInfo = (str) => {
  3802. var strLen = str.length;
  3803. var lower = str.toLowerCase();
  3804. var lowerCodes = []; // new Array(strLen) sparse array is too slow
  3805. var bitflags = 0;
  3806. var containsSpace = false; // space isn't stored in bitflags because of how searching with a space works
  3807. for(var i = 0; i < strLen; ++i) {
  3808. var lowerCode = lowerCodes[i] = lower.charCodeAt(i);
  3809. if(lowerCode === 32) {
  3810. containsSpace = true;
  3811. continue // it's important that we don't set any bitflags for space
  3812. }
  3813. var bit = lowerCode>=97&&lowerCode<=122 ? lowerCode-97 // alphabet
  3814. : lowerCode>=48&&lowerCode<=57 ? 26 // numbers
  3815. // 3 bits available
  3816. : lowerCode<=127 ? 30 // other ascii
  3817. : 31; // other utf8
  3818. bitflags |= 1<<bit;
  3819. }
  3820. return {lowerCodes:lowerCodes, bitflags:bitflags, containsSpace:containsSpace, _lower:lower}
  3821. };
  3822. var prepareBeginningIndexes = (target) => {
  3823. var targetLen = target.length;
  3824. var beginningIndexes = []; var beginningIndexesLen = 0;
  3825. var wasUpper = false;
  3826. var wasAlphanum = false;
  3827. for(var i = 0; i < targetLen; ++i) {
  3828. var targetCode = target.charCodeAt(i);
  3829. var isUpper = targetCode>=65&&targetCode<=90;
  3830. var isAlphanum = isUpper || targetCode>=97&&targetCode<=122 || targetCode>=48&&targetCode<=57;
  3831. var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum;
  3832. wasUpper = isUpper;
  3833. wasAlphanum = isAlphanum;
  3834. if(isBeginning) beginningIndexes[beginningIndexesLen++] = i;
  3835. }
  3836. return beginningIndexes
  3837. };
  3838. var prepareNextBeginningIndexes = (target) => {
  3839. var targetLen = target.length;
  3840. var beginningIndexes = prepareBeginningIndexes(target);
  3841. var nextBeginningIndexes = []; // new Array(targetLen) sparse array is too slow
  3842. var lastIsBeginning = beginningIndexes[0];
  3843. var lastIsBeginningI = 0;
  3844. for(var i = 0; i < targetLen; ++i) {
  3845. if(lastIsBeginning > i) {
  3846. nextBeginningIndexes[i] = lastIsBeginning;
  3847. } else {
  3848. lastIsBeginning = beginningIndexes[++lastIsBeginningI];
  3849. nextBeginningIndexes[i] = lastIsBeginning===undefined ? targetLen : lastIsBeginning;
  3850. }
  3851. }
  3852. return nextBeginningIndexes
  3853. };
  3854. var cleanup = () => { preparedCache.clear(); preparedSearchCache.clear(); matchesSimple = []; matchesStrict = []; };
  3855. var preparedCache = new Map();
  3856. var preparedSearchCache = new Map();
  3857. var matchesSimple = []; var matchesStrict = [];
  3858. // for use with keys. just returns the maximum score
  3859. var defaultScoreFn = (a) => {
  3860. var max = INT_MIN;
  3861. var len = a.length;
  3862. for (var i = 0; i < len; ++i) {
  3863. var result = a[i]; if(result === NULL) continue
  3864. var score = result.score;
  3865. if(score > max) max = score;
  3866. }
  3867. if(max === INT_MIN) return NULL
  3868. return max
  3869. };
  3870. // prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop]
  3871. // prop = 'key1.key2' 10ms
  3872. // prop = ['key1', 'key2'] 27ms
  3873. var getValue = (obj, prop) => {
  3874. var tmp = obj[prop]; if(tmp !== undefined) return tmp
  3875. var segs = prop;
  3876. if(!Array.isArray(prop)) segs = prop.split('.');
  3877. var len = segs.length;
  3878. var i = -1;
  3879. while (obj && (++i < len)) obj = obj[segs[i]];
  3880. return obj
  3881. };
  3882. var isObj = (x) => { return typeof x === 'object' }; // faster as a function
  3883. // var INT_MAX = 9007199254740991; var INT_MIN = -INT_MAX
  3884. var INT_MAX = Infinity; var INT_MIN = -INT_MAX;
  3885. var noResults = []; noResults.total = 0;
  3886. var NULL = null;
  3887. // Hacked version of https://github.com/lemire/FastPriorityQueue.js
  3888. var fastpriorityqueue=r=>{var e=[],o=0,a={},v=r=>{for(var a=0,v=e[a],c=1;c<o;){var s=c+1;a=c,s<o&&e[s].score<e[c].score&&(a=s),e[a-1>>1]=e[a],c=1+(a<<1);}for(var f=a-1>>1;a>0&&v.score<e[f].score;f=(a=f)-1>>1)e[a]=e[f];e[a]=v;};return a.add=(r=>{var a=o;e[o++]=r;for(var v=a-1>>1;a>0&&r.score<e[v].score;v=(a=v)-1>>1)e[a]=e[v];e[a]=r;}),a.poll=(r=>{if(0!==o){var a=e[0];return e[0]=e[--o],v(),a}}),a.peek=(r=>{if(0!==o)return e[0]}),a.replaceTop=(r=>{e[0]=r,v();}),a};
  3889. var q = fastpriorityqueue(); // reuse this
  3890. // fuzzysort is written this way for minification. all names are mangeled unless quoted
  3891. return {'single':single, 'go':go, 'highlight':highlight, 'prepare':prepare, 'indexes':indexes, 'cleanup':cleanup}
  3892. }); // UMD
  3893. // TODO: (feature) frecency
  3894. // TODO: (perf) use different sorting algo depending on the # of results?
  3895. // TODO: (perf) preparedCache is a memory leak
  3896. // TODO: (like sublime) backslash === forwardslash
  3897. // TODO: (perf) prepareSearch seems slow
  3898. });
  3899. class AbstractSettingComponent extends obsidian.Component {
  3900. constructor(parent, sectionId, sectionName, setting, settingsManager, isView) {
  3901. super();
  3902. this.childEl = null;
  3903. this.parent = parent;
  3904. this.sectionId = sectionId;
  3905. this.sectionName = sectionName;
  3906. this.setting = setting;
  3907. this.settingsManager = settingsManager;
  3908. this.isView = isView;
  3909. }
  3910. get containerEl() {
  3911. return this.parent instanceof HTMLElement
  3912. ? this.parent
  3913. : this.parent.childEl;
  3914. }
  3915. onload() {
  3916. this.render();
  3917. }
  3918. onunload() {
  3919. this.destroy();
  3920. }
  3921. /**
  3922. * Matches the Component against `str`. A perfect match returns 0, no match returns negative infinity.
  3923. *
  3924. * @param str the string to match this Component against.
  3925. */
  3926. match(str) {
  3927. var _a, _b, _c, _d;
  3928. if (!str) {
  3929. return Number.NEGATIVE_INFINITY;
  3930. }
  3931. return Math.max((_b = (_a = fuzzysort.single(str, getTitle(this.setting))) === null || _a === void 0 ? void 0 : _a.score) !== null && _b !== void 0 ? _b : Number.NEGATIVE_INFINITY, (_d = (_c = fuzzysort.single(str, getDescription(this.setting))) === null || _c === void 0 ? void 0 : _c.score) !== null && _d !== void 0 ? _d : Number.NEGATIVE_INFINITY);
  3932. }
  3933. /**
  3934. * Matches the Component against `str`. A match returns true, no match or a bad match returns false.
  3935. *
  3936. * @param str the string to match this Component against.
  3937. */
  3938. decisiveMatch(str) {
  3939. return this.match(str) > -100000;
  3940. }
  3941. }
  3942. const resetTooltip = 'Restore default';
  3943. class ClassMultiToggleSettingComponent extends AbstractSettingComponent {
  3944. render() {
  3945. const title = getTitle(this.setting);
  3946. const description = getDescription(this.setting);
  3947. if (typeof this.setting.default !== 'string') {
  3948. return console.error(`${t('Error:')} ${title} ${t('missing default value')}`);
  3949. }
  3950. let prevValue = this.getPreviousValue();
  3951. const defaultLabel = this.getDefaultOptionLabel();
  3952. this.settingEl = new obsidian.Setting(this.containerEl);
  3953. this.settingEl.setName(title);
  3954. this.settingEl.setDesc(createDescription(description, this.setting.default, defaultLabel));
  3955. this.settingEl.addDropdown((dropdown) => {
  3956. if (this.setting.allowEmpty) {
  3957. dropdown.addOption('none', '');
  3958. }
  3959. for (const o of this.setting.options) {
  3960. if (typeof o === 'string') {
  3961. dropdown.addOption(o, o);
  3962. }
  3963. else {
  3964. dropdown.addOption(o.value, o.label);
  3965. }
  3966. }
  3967. dropdown.setValue(prevValue);
  3968. dropdown.onChange((value) => {
  3969. this.settingsManager.setSetting(this.sectionId, this.setting.id, value);
  3970. prevValue = value;
  3971. });
  3972. this.dropdownComponent = dropdown;
  3973. });
  3974. this.settingEl.addExtraButton((b) => {
  3975. b.setIcon('reset');
  3976. b.onClick(() => {
  3977. this.dropdownComponent.setValue(this.setting.default || 'none');
  3978. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  3979. });
  3980. b.setTooltip(resetTooltip);
  3981. });
  3982. this.settingEl.settingEl.dataset.id = this.setting.id;
  3983. }
  3984. destroy() {
  3985. var _a;
  3986. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  3987. }
  3988. getDefaultOption() {
  3989. if (this.setting.default) {
  3990. return this.setting.options.find((o) => {
  3991. if (typeof o === 'string') {
  3992. return o === this.setting.default;
  3993. }
  3994. return o.value === this.setting.default;
  3995. });
  3996. }
  3997. return undefined;
  3998. }
  3999. getDefaultOptionLabel() {
  4000. const defaultOption = this.getDefaultOption();
  4001. if (defaultOption) {
  4002. if (typeof defaultOption === 'string') {
  4003. return defaultOption;
  4004. }
  4005. return defaultOption.label;
  4006. }
  4007. return undefined;
  4008. }
  4009. getPreviousValue() {
  4010. const prevValue = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4011. if (prevValue === undefined) {
  4012. if (this.setting.default) {
  4013. return this.setting.default;
  4014. }
  4015. return 'none';
  4016. }
  4017. return prevValue;
  4018. }
  4019. }
  4020. class ClassToggleSettingComponent extends AbstractSettingComponent {
  4021. render() {
  4022. const title = getTitle(this.setting);
  4023. const description = getDescription(this.setting);
  4024. this.settingEl = new obsidian.Setting(this.containerEl);
  4025. this.settingEl.setName(title);
  4026. this.settingEl.setDesc(description !== null && description !== void 0 ? description : '');
  4027. this.settingEl.addToggle((toggle) => {
  4028. const value = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4029. toggle.setValue(value !== undefined ? !!value : !!this.setting.default);
  4030. toggle.onChange((value) => {
  4031. this.settingsManager.setSetting(this.sectionId, this.setting.id, value);
  4032. });
  4033. this.toggleComponent = toggle;
  4034. });
  4035. this.settingEl.addExtraButton((b) => {
  4036. b.setIcon('reset');
  4037. b.onClick(() => {
  4038. const value = !!this.setting.default;
  4039. this.toggleComponent.setValue(value);
  4040. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  4041. });
  4042. b.setTooltip(resetTooltip);
  4043. });
  4044. this.settingEl.settingEl.dataset.id = this.setting.id;
  4045. }
  4046. destroy() {
  4047. var _a;
  4048. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4049. }
  4050. }
  4051. class InfoTextSettingComponent extends AbstractSettingComponent {
  4052. render() {
  4053. const title = getTitle(this.setting);
  4054. const description = getDescription(this.setting);
  4055. this.settingEl = new obsidian.Setting(this.containerEl);
  4056. this.settingEl.setClass('style-settings-info-text');
  4057. if (title) {
  4058. this.settingEl.setName(title);
  4059. }
  4060. if (description) {
  4061. if (this.setting.markdown) {
  4062. obsidian.MarkdownRenderer.renderMarkdown(description, this.settingEl.descEl, '', this);
  4063. this.settingEl.descEl.addClass('style-settings-markdown');
  4064. }
  4065. else {
  4066. this.settingEl.setDesc(description);
  4067. }
  4068. }
  4069. this.settingEl.settingEl.dataset.id = this.setting.id;
  4070. }
  4071. destroy() {
  4072. var _a;
  4073. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4074. }
  4075. }
  4076. var pickr_min = createCommonjsModule(function (module, exports) {
  4077. /*! Pickr 1.8.4 MIT | https://github.com/Simonwep/pickr */
  4078. !function(t,e){module.exports=e();}(self,(function(){return (()=>{var t={d:(e,o)=>{for(var n in o)t.o(o,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:o[n]});},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0});}},e={};t.d(e,{default:()=>x});var o={};function n(t,e,o,n){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};e instanceof HTMLCollection||e instanceof NodeList?e=Array.from(e):Array.isArray(e)||(e=[e]),Array.isArray(o)||(o=[o]);for(const s of e)for(const e of o)s[t](e,n,{capture:!1,...i});return Array.prototype.slice.call(arguments,1)}t.r(o),t.d(o,{adjustableInputNumbers:()=>p,createElementFromString:()=>r,createFromTemplate:()=>a,eventPath:()=>l,off:()=>s,on:()=>i,resolveElement:()=>c});const i=n.bind(null,"addEventListener"),s=n.bind(null,"removeEventListener");function r(t){const e=document.createElement("div");return e.innerHTML=t.trim(),e.firstElementChild}function a(t){const e=(t,e)=>{const o=t.getAttribute(e);return t.removeAttribute(e),o},o=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=e(t,":obj"),s=e(t,":ref"),r=i?n[i]={}:n;s&&(n[s]=t);for(const n of Array.from(t.children)){const t=e(n,":arr"),i=o(n,t?{}:r);t&&(r[t]||(r[t]=[])).push(Object.keys(i).length?i:n);}return n};return o(r(t))}function l(t){let e=t.path||t.composedPath&&t.composedPath();if(e)return e;let o=t.target.parentElement;for(e=[t.target,o];o=o.parentElement;)e.push(o);return e.push(document,window),e}function c(t){return t instanceof Element?t:"string"==typeof t?t.split(/>>/g).reduce(((t,e,o,n)=>(t=t.querySelector(e),o<n.length-1?t.shadowRoot:t)),document):null}function p(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t=>t;function o(o){const n=[.001,.01,.1][Number(o.shiftKey||2*o.ctrlKey)]*(o.deltaY<0?1:-1);let i=0,s=t.selectionStart;t.value=t.value.replace(/[\d.]+/g,((t,o)=>o<=s&&o+t.length>=s?(s=o,e(Number(t),n,i)):(i++,t))),t.focus(),t.setSelectionRange(s,s),o.preventDefault(),t.dispatchEvent(new Event("input"));}i(t,"focus",(()=>i(window,"wheel",o,{passive:!1}))),i(t,"blur",(()=>s(window,"wheel",o)));}const{min:h,max:u,floor:d,round:v}=Math;function m(t,e,o){e/=100,o/=100;const n=d(t=t/360*6),i=t-n,s=o*(1-e),r=o*(1-i*e),a=o*(1-(1-i)*e),l=n%6;return [255*[o,r,s,s,a,o][l],255*[a,o,o,r,s,s][l],255*[s,s,a,o,o,r][l]]}function f(t,e,o){return m(t,e,o).map((t=>v(t).toString(16).padStart(2,"0")))}function g(t,e,o){const n=m(t,e,o),i=n[0]/255,s=n[1]/255,r=n[2]/255,a=h(1-i,1-s,1-r);return [100*(1===a?0:(1-i-a)/(1-a)),100*(1===a?0:(1-s-a)/(1-a)),100*(1===a?0:(1-r-a)/(1-a)),100*a]}function b(t,e,o){const n=(2-(e/=100))*(o/=100)/2;return 0!==n&&(e=1===n?0:n<.5?e*o/(2*n):e*o/(2-2*n)),[t,100*e,100*n]}function y(t,e,o){const n=h(t/=255,e/=255,o/=255),i=u(t,e,o),s=i-n;let r,a;if(0===s)r=a=0;else {a=s/i;const n=((i-t)/6+s/2)/s,l=((i-e)/6+s/2)/s,c=((i-o)/6+s/2)/s;t===i?r=c-l:e===i?r=1/3+n-c:o===i&&(r=2/3+l-n),r<0?r+=1:r>1&&(r-=1);}return [360*r,100*a,100*i]}function _(t,e,o,n){e/=100,o/=100;return [...y(255*(1-h(1,(t/=100)*(1-(n/=100))+n)),255*(1-h(1,e*(1-n)+n)),255*(1-h(1,o*(1-n)+n)))]}function w(t,e,o){e/=100;const n=2*(e*=(o/=100)<.5?o:1-o)/(o+e)*100,i=100*(o+e);return [t,isNaN(n)?0:n,i]}function A(t){return y(...t.match(/.{2}/g).map((t=>parseInt(t,16))))}function C(t){t=t.match(/^[a-zA-Z]+$/)?function(t){if("black"===t.toLowerCase())return "#000";const e=document.createElement("canvas").getContext("2d");return e.fillStyle=t,"#000"===e.fillStyle?null:e.fillStyle}(t):t;const e={cmyk:/^cmyk[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)/i,rgba:/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsla:/^((hsla)|hsl)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsva:/^((hsva)|hsv)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hexa:/^#?(([\dA-Fa-f]{3,4})|([\dA-Fa-f]{6})|([\dA-Fa-f]{8}))$/i},o=t=>t.map((t=>/^(|\d+)\.\d+|\d+$/.test(t)?Number(t):void 0));let n;t:for(const i in e){if(!(n=e[i].exec(t)))continue;const s=t=>!!n[2]==("number"==typeof t);switch(i){case"cmyk":{const[,t,e,s,r]=o(n);if(t>100||e>100||s>100||r>100)break t;return {values:_(t,e,s,r),type:i}}case"rgba":{const[,,,t,e,r,a]=o(n);if(t>255||e>255||r>255||a<0||a>1||!s(a))break t;return {values:[...y(t,e,r),a],a,type:i}}case"hexa":{let[,t]=n;4!==t.length&&3!==t.length||(t=t.split("").map((t=>t+t)).join(""));const e=t.substring(0,6);let o=t.substring(6);return o=o?parseInt(o,16)/255:void 0,{values:[...A(e),o],a:o,type:i}}case"hsla":{const[,,,t,e,r,a]=o(n);if(t>360||e>100||r>100||a<0||a>1||!s(a))break t;return {values:[...w(t,e,r),a],a,type:i}}case"hsva":{const[,,,t,e,r,a]=o(n);if(t>360||e>100||r>100||a<0||a>1||!s(a))break t;return {values:[t,e,r,a],a,type:i}}}}return {values:null,type:null}}function $(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;const i=(t,e)=>function(){let o=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;return e(~o?t.map((t=>Number(t.toFixed(o)))):t)},s={h:t,s:e,v:o,a:n,toHSVA(){const t=[s.h,s.s,s.v,s.a];return t.toString=i(t,(t=>`hsva(${t[0]}, ${t[1]}%, ${t[2]}%, ${s.a})`)),t},toHSLA(){const t=[...b(s.h,s.s,s.v),s.a];return t.toString=i(t,(t=>`hsla(${t[0]}, ${t[1]}%, ${t[2]}%, ${s.a})`)),t},toRGBA(){const t=[...m(s.h,s.s,s.v),s.a];return t.toString=i(t,(t=>`rgba(${t[0]}, ${t[1]}, ${t[2]}, ${s.a})`)),t},toCMYK(){const t=g(s.h,s.s,s.v);return t.toString=i(t,(t=>`cmyk(${t[0]}%, ${t[1]}%, ${t[2]}%, ${t[3]}%)`)),t},toHEXA(){const t=f(s.h,s.s,s.v),e=s.a>=1?"":Number((255*s.a).toFixed(0)).toString(16).toUpperCase().padStart(2,"0");return e&&t.push(e),t.toString=()=>`#${t.join("").toUpperCase()}`,t},clone:()=>$(s.h,s.s,s.v,s.a)};return s}const k=t=>Math.max(Math.min(t,1),0);function S(t){const e={options:Object.assign({lock:null,onchange:()=>0,onstop:()=>0},t),_keyboard(t){const{options:o}=e,{type:n,key:i}=t;if(document.activeElement===o.wrapper){const{lock:o}=e.options,s="ArrowUp"===i,r="ArrowRight"===i,a="ArrowDown"===i,l="ArrowLeft"===i;if("keydown"===n&&(s||r||a||l)){let n=0,i=0;"v"===o?n=s||r?1:-1:"h"===o?n=s||r?-1:1:(i=s?-1:a?1:0,n=l?-1:r?1:0),e.update(k(e.cache.x+.01*n),k(e.cache.y+.01*i)),t.preventDefault();}else i.startsWith("Arrow")&&(e.options.onstop(),t.preventDefault());}},_tapstart(t){i(document,["mouseup","touchend","touchcancel"],e._tapstop),i(document,["mousemove","touchmove"],e._tapmove),t.cancelable&&t.preventDefault(),e._tapmove(t);},_tapmove(t){const{options:o,cache:n}=e,{lock:i,element:s,wrapper:r}=o,a=r.getBoundingClientRect();let l=0,c=0;if(t){const e=t&&t.touches&&t.touches[0];l=t?(e||t).clientX:0,c=t?(e||t).clientY:0,l<a.left?l=a.left:l>a.left+a.width&&(l=a.left+a.width),c<a.top?c=a.top:c>a.top+a.height&&(c=a.top+a.height),l-=a.left,c-=a.top;}else n&&(l=n.x*a.width,c=n.y*a.height);"h"!==i&&(s.style.left=`calc(${l/a.width*100}% - ${s.offsetWidth/2}px)`),"v"!==i&&(s.style.top=`calc(${c/a.height*100}% - ${s.offsetHeight/2}px)`),e.cache={x:l/a.width,y:c/a.height};const p=k(l/a.width),h=k(c/a.height);switch(i){case"v":return o.onchange(p);case"h":return o.onchange(h);default:return o.onchange(p,h)}},_tapstop(){e.options.onstop(),s(document,["mouseup","touchend","touchcancel"],e._tapstop),s(document,["mousemove","touchmove"],e._tapmove);},trigger(){e._tapmove();},update(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const{left:n,top:i,width:s,height:r}=e.options.wrapper.getBoundingClientRect();"h"===e.options.lock&&(o=t),e._tapmove({clientX:n+s*t,clientY:i+r*o});},destroy(){const{options:t,_tapstart:o,_keyboard:n}=e;s(document,["keydown","keyup"],n),s([t.wrapper,t.element],"mousedown",o),s([t.wrapper,t.element],"touchstart",o,{passive:!1});}},{options:o,_tapstart:n,_keyboard:r}=e;return i([o.wrapper,o.element],"mousedown",n),i([o.wrapper,o.element],"touchstart",n,{passive:!1}),i(document,["keydown","keyup"],r),e}function O(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t=Object.assign({onchange:()=>0,className:"",elements:[]},t);const e=i(t.elements,"click",(e=>{t.elements.forEach((o=>o.classList[e.target===o?"add":"remove"](t.className))),t.onchange(e),e.stopPropagation();}));return {destroy:()=>s(...e)}}const E={variantFlipOrder:{start:"sme",middle:"mse",end:"ems"},positionFlipOrder:{top:"tbrl",right:"rltb",bottom:"btrl",left:"lrbt"},position:"bottom",margin:8},L=(t,e,o)=>{const{container:n,margin:i,position:s,variantFlipOrder:r,positionFlipOrder:a}={container:document.documentElement.getBoundingClientRect(),...E,...o},{left:l,top:c}=e.style;e.style.left="0",e.style.top="0";const p=t.getBoundingClientRect(),h=e.getBoundingClientRect(),u={t:p.top-h.height-i,b:p.bottom+i,r:p.right+i,l:p.left-h.width-i},d={vs:p.left,vm:p.left+p.width/2+-h.width/2,ve:p.left+p.width-h.width,hs:p.top,hm:p.bottom-p.height/2-h.height/2,he:p.bottom-h.height},[v,m="middle"]=s.split("-"),f=a[v],g=r[m],{top:b,left:y,bottom:_,right:w}=n;for(const t of f){const o="t"===t||"b"===t,n=u[t],[i,s]=o?["top","left"]:["left","top"],[r,a]=o?[h.height,h.width]:[h.width,h.height],[l,c]=o?[_,w]:[w,_],[p,v]=o?[b,y]:[y,b];if(!(n<p||n+r>l))for(const r of g){const l=d[(o?"v":"h")+r];if(!(l<v||l+a>c))return e.style[s]=l-h[s]+"px",e.style[i]=n-h[i]+"px",t+r}}return e.style.left=l,e.style.top=c,null};function P(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class x{constructor(t){P(this,"_initializingActive",!0),P(this,"_recalc",!0),P(this,"_nanopop",null),P(this,"_root",null),P(this,"_color",$()),P(this,"_lastColor",$()),P(this,"_swatchColors",[]),P(this,"_setupAnimationFrame",null),P(this,"_eventListener",{init:[],save:[],hide:[],show:[],clear:[],change:[],changestop:[],cancel:[],swatchselect:[]}),this.options=t=Object.assign({...x.DEFAULT_OPTIONS},t);const{swatches:e,components:o,theme:n,sliders:i,lockOpacity:s,padding:r}=t;["nano","monolith"].includes(n)&&!i&&(t.sliders="h"),o.interaction||(o.interaction={});const{preview:a,opacity:l,hue:c,palette:p}=o;o.opacity=!s&&l,o.palette=p||a||l||c,this._preBuild(),this._buildComponents(),this._bindEvents(),this._finalBuild(),e&&e.length&&e.forEach((t=>this.addSwatch(t)));const{button:h,app:u}=this._root;this._nanopop=((t,e,o)=>{const n="object"!=typeof t||t instanceof HTMLElement?{reference:t,popper:e,...o}:t;return {update(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n;const{reference:e,popper:o}=Object.assign(n,t);if(!o||!e)throw new Error("Popper- or reference-element missing.");return L(e,o,n)}}})(h,u,{margin:r}),h.setAttribute("role","button"),h.setAttribute("aria-label",this._t("btn:toggle"));const d=this;this._setupAnimationFrame=requestAnimationFrame((function e(){if(!u.offsetWidth)return d._setupAnimationFrame=requestAnimationFrame(e);d.setColor(t.default),d._rePositioningPicker(),t.defaultRepresentation&&(d._representation=t.defaultRepresentation,d.setColorRepresentation(d._representation)),t.showAlways&&d.show(),d._initializingActive=!1,d._emit("init");}));}_preBuild(){const{options:t}=this;for(const e of ["el","container"])t[e]=c(t[e]);this._root=(t=>{const{components:e,useAsButton:o,inline:n,appClass:i,theme:s,lockOpacity:r}=t.options,l=t=>t?"":'style="display:none" hidden',c=e=>t._t(e),p=a(`\n <div :ref="root" class="pickr">\n\n ${o?"":'<button type="button" :ref="button" class="pcr-button"></button>'}\n\n <div :ref="app" class="pcr-app ${i||""}" data-theme="${s}" ${n?'style="position: unset"':""} aria-label="${c("ui:dialog")}" role="window">\n <div class="pcr-selection" ${l(e.palette)}>\n <div :obj="preview" class="pcr-color-preview" ${l(e.preview)}>\n <button type="button" :ref="lastColor" class="pcr-last-color" aria-label="${c("btn:last-color")}"></button>\n <div :ref="currentColor" class="pcr-current-color"></div>\n </div>\n\n <div :obj="palette" class="pcr-color-palette">\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="palette" class="pcr-palette" tabindex="0" aria-label="${c("aria:palette")}" role="listbox"></div>\n </div>\n\n <div :obj="hue" class="pcr-color-chooser" ${l(e.hue)}>\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="slider" class="pcr-hue pcr-slider" tabindex="0" aria-label="${c("aria:hue")}" role="slider"></div>\n </div>\n\n <div :obj="opacity" class="pcr-color-opacity" ${l(e.opacity)}>\n <div :ref="picker" class="pcr-picker"></div>\n <div :ref="slider" class="pcr-opacity pcr-slider" tabindex="0" aria-label="${c("aria:opacity")}" role="slider"></div>\n </div>\n </div>\n\n <div class="pcr-swatches ${e.palette?"":"pcr-last"}" :ref="swatches"></div>\n\n <div :obj="interaction" class="pcr-interaction" ${l(Object.keys(e.interaction).length)}>\n <input :ref="result" class="pcr-result" type="text" spellcheck="false" ${l(e.interaction.input)} aria-label="${c("aria:input")}">\n\n <input :arr="options" class="pcr-type" data-type="HEXA" value="${r?"HEX":"HEXA"}" type="button" ${l(e.interaction.hex)}>\n <input :arr="options" class="pcr-type" data-type="RGBA" value="${r?"RGB":"RGBA"}" type="button" ${l(e.interaction.rgba)}>\n <input :arr="options" class="pcr-type" data-type="HSLA" value="${r?"HSL":"HSLA"}" type="button" ${l(e.interaction.hsla)}>\n <input :arr="options" class="pcr-type" data-type="HSVA" value="${r?"HSV":"HSVA"}" type="button" ${l(e.interaction.hsva)}>\n <input :arr="options" class="pcr-type" data-type="CMYK" value="CMYK" type="button" ${l(e.interaction.cmyk)}>\n\n <input :ref="save" class="pcr-save" value="${c("btn:save")}" type="button" ${l(e.interaction.save)} aria-label="${c("aria:btn:save")}">\n <input :ref="cancel" class="pcr-cancel" value="${c("btn:cancel")}" type="button" ${l(e.interaction.cancel)} aria-label="${c("aria:btn:cancel")}">\n <input :ref="clear" class="pcr-clear" value="${c("btn:clear")}" type="button" ${l(e.interaction.clear)} aria-label="${c("aria:btn:clear")}">\n </div>\n </div>\n </div>\n `),h=p.interaction;return h.options.find((t=>!t.hidden&&!t.classList.add("active"))),h.type=()=>h.options.find((t=>t.classList.contains("active"))),p})(this),t.useAsButton&&(this._root.button=t.el),t.container.appendChild(this._root.root);}_finalBuild(){const t=this.options,e=this._root;if(t.container.removeChild(e.root),t.inline){const o=t.el.parentElement;t.el.nextSibling?o.insertBefore(e.app,t.el.nextSibling):o.appendChild(e.app);}else t.container.appendChild(e.app);t.useAsButton?t.inline&&t.el.remove():t.el.parentNode.replaceChild(e.root,t.el),t.disabled&&this.disable(),t.comparison||(e.button.style.transition="none",t.useAsButton||(e.preview.lastColor.style.transition="none")),this.hide();}_buildComponents(){const t=this,e=this.options.components,o=(t.options.sliders||"v").repeat(2),[n,i]=o.match(/^[vh]+$/g)?o:[],s=()=>this._color||(this._color=this._lastColor.clone()),r={palette:S({element:t._root.palette.picker,wrapper:t._root.palette.palette,onstop:()=>t._emit("changestop","slider",t),onchange(o,n){if(!e.palette)return;const i=s(),{_root:r,options:a}=t,{lastColor:l,currentColor:c}=r.preview;t._recalc&&(i.s=100*o,i.v=100-100*n,i.v<0&&(i.v=0),t._updateOutput("slider"));const p=i.toRGBA().toString(0);this.element.style.background=p,this.wrapper.style.background=`\n linear-gradient(to top, rgba(0, 0, 0, ${i.a}), transparent),\n linear-gradient(to left, hsla(${i.h}, 100%, 50%, ${i.a}), rgba(255, 255, 255, ${i.a}))\n `,a.comparison?a.useAsButton||t._lastColor||l.style.setProperty("--pcr-color",p):(r.button.style.setProperty("--pcr-color",p),r.button.classList.remove("clear"));const h=i.toHEXA().toString();for(const{el:e,color:o}of t._swatchColors)e.classList[h===o.toHEXA().toString()?"add":"remove"]("pcr-active");c.style.setProperty("--pcr-color",p);}}),hue:S({lock:"v"===i?"h":"v",element:t._root.hue.picker,wrapper:t._root.hue.slider,onstop:()=>t._emit("changestop","slider",t),onchange(o){if(!e.hue||!e.palette)return;const n=s();t._recalc&&(n.h=360*o),this.element.style.backgroundColor=`hsl(${n.h}, 100%, 50%)`,r.palette.trigger();}}),opacity:S({lock:"v"===n?"h":"v",element:t._root.opacity.picker,wrapper:t._root.opacity.slider,onstop:()=>t._emit("changestop","slider",t),onchange(o){if(!e.opacity||!e.palette)return;const n=s();t._recalc&&(n.a=Math.round(100*o)/100),this.element.style.background=`rgba(0, 0, 0, ${n.a})`,r.palette.trigger();}}),selectable:O({elements:t._root.interaction.options,className:"active",onchange(e){t._representation=e.target.getAttribute("data-type").toUpperCase(),t._recalc&&t._updateOutput("swatch");}})};this._components=r;}_bindEvents(){const{_root:t,options:e}=this,o=[i(t.interaction.clear,"click",(()=>this._clearColor())),i([t.interaction.cancel,t.preview.lastColor],"click",(()=>{this.setHSVA(...(this._lastColor||this._color).toHSVA(),!0),this._emit("cancel");})),i(t.interaction.save,"click",(()=>{!this.applyColor()&&!e.showAlways&&this.hide();})),i(t.interaction.result,["keyup","input"],(t=>{this.setColor(t.target.value,!0)&&!this._initializingActive&&(this._emit("change",this._color,"input",this),this._emit("changestop","input",this)),t.stopImmediatePropagation();})),i(t.interaction.result,["focus","blur"],(t=>{this._recalc="blur"===t.type,this._recalc&&this._updateOutput(null);})),i([t.palette.palette,t.palette.picker,t.hue.slider,t.hue.picker,t.opacity.slider,t.opacity.picker],["mousedown","touchstart"],(()=>this._recalc=!0),{passive:!0})];if(!e.showAlways){const n=e.closeWithKey;o.push(i(t.button,"click",(()=>this.isOpen()?this.hide():this.show())),i(document,"keyup",(t=>this.isOpen()&&(t.key===n||t.code===n)&&this.hide())),i(document,["touchstart","mousedown"],(e=>{this.isOpen()&&!l(e).some((e=>e===t.app||e===t.button))&&this.hide();}),{capture:!0}));}if(e.adjustableNumbers){const e={rgba:[255,255,255,1],hsva:[360,100,100,1],hsla:[360,100,100,1],cmyk:[100,100,100,100]};p(t.interaction.result,((t,o,n)=>{const i=e[this.getColorRepresentation().toLowerCase()];if(i){const e=i[n],s=t+(e>=100?1e3*o:o);return s<=0?0:Number((s<e?s:e).toPrecision(3))}return t}));}if(e.autoReposition&&!e.inline){let t=null;const n=this;o.push(i(window,["scroll","resize"],(()=>{n.isOpen()&&(e.closeOnScroll&&n.hide(),null===t?(t=setTimeout((()=>t=null),100),requestAnimationFrame((function e(){n._rePositioningPicker(),null!==t&&requestAnimationFrame(e);}))):(clearTimeout(t),t=setTimeout((()=>t=null),100)));}),{capture:!0}));}this._eventBindings=o;}_rePositioningPicker(){const{options:t}=this;if(!t.inline){if(!this._nanopop.update({container:document.body.getBoundingClientRect(),position:t.position})){const t=this._root.app,e=t.getBoundingClientRect();t.style.top=(window.innerHeight-e.height)/2+"px",t.style.left=(window.innerWidth-e.width)/2+"px";}}}_updateOutput(t){const{_root:e,_color:o,options:n}=this;if(e.interaction.type()){const t=`to${e.interaction.type().getAttribute("data-type")}`;e.interaction.result.value="function"==typeof o[t]?o[t]().toString(n.outputPrecision):"";}!this._initializingActive&&this._recalc&&this._emit("change",o,t,this);}_clearColor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const{_root:e,options:o}=this;o.useAsButton||e.button.style.setProperty("--pcr-color","rgba(0, 0, 0, 0.15)"),e.button.classList.add("clear"),o.showAlways||this.hide(),this._lastColor=null,this._initializingActive||t||(this._emit("save",null),this._emit("clear"));}_parseLocalColor(t){const{values:e,type:o,a:n}=C(t),{lockOpacity:i}=this.options,s=void 0!==n&&1!==n;return e&&3===e.length&&(e[3]=void 0),{values:!e||i&&s?null:e,type:o}}_t(t){return this.options.i18n[t]||x.I18N_DEFAULTS[t]}_emit(t){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;n<e;n++)o[n-1]=arguments[n];this._eventListener[t].forEach((t=>t(...o,this)));}on(t,e){return this._eventListener[t].push(e),this}off(t,e){const o=this._eventListener[t]||[],n=o.indexOf(e);return ~n&&o.splice(n,1),this}addSwatch(t){const{values:e}=this._parseLocalColor(t);if(e){const{_swatchColors:t,_root:o}=this,n=$(...e),s=r(`<button type="button" style="--pcr-color: ${n.toRGBA().toString(0)}" aria-label="${this._t("btn:swatch")}"/>`);return o.swatches.appendChild(s),t.push({el:s,color:n}),this._eventBindings.push(i(s,"click",(()=>{this.setHSVA(...n.toHSVA(),!0),this._emit("swatchselect",n),this._emit("change",n,"swatch",this);}))),!0}return !1}removeSwatch(t){const e=this._swatchColors[t];if(e){const{el:o}=e;return this._root.swatches.removeChild(o),this._swatchColors.splice(t,1),!0}return !1}applyColor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const{preview:e,button:o}=this._root,n=this._color.toRGBA().toString(0);return e.lastColor.style.setProperty("--pcr-color",n),this.options.useAsButton||o.style.setProperty("--pcr-color",n),o.classList.remove("clear"),this._lastColor=this._color.clone(),this._initializingActive||t||this._emit("save",this._color),this}destroy(){cancelAnimationFrame(this._setupAnimationFrame),this._eventBindings.forEach((t=>s(...t))),Object.keys(this._components).forEach((t=>this._components[t].destroy()));}destroyAndRemove(){this.destroy();const{root:t,app:e}=this._root;t.parentElement&&t.parentElement.removeChild(t),e.parentElement.removeChild(e),Object.keys(this).forEach((t=>this[t]=null));}hide(){return !!this.isOpen()&&(this._root.app.classList.remove("visible"),this._emit("hide"),!0)}show(){return !this.options.disabled&&!this.isOpen()&&(this._root.app.classList.add("visible"),this._rePositioningPicker(),this._emit("show",this._color),this)}isOpen(){return this._root.app.classList.contains("visible")}setHSVA(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:360,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const s=this._recalc;if(this._recalc=!1,t<0||t>360||e<0||e>100||o<0||o>100||n<0||n>1)return !1;this._color=$(t,e,o,n);const{hue:r,opacity:a,palette:l}=this._components;return r.update(t/360),a.update(n),l.update(e/100,1-o/100),i||this.applyColor(),s&&this._updateOutput(),this._recalc=s,!0}setColor(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(null===t)return this._clearColor(e),!0;const{values:o,type:n}=this._parseLocalColor(t);if(o){const t=n.toUpperCase(),{options:i}=this._root.interaction,s=i.find((e=>e.getAttribute("data-type")===t));if(s&&!s.hidden)for(const t of i)t.classList[t===s?"add":"remove"]("active");return !!this.setHSVA(...o,e)&&this.setColorRepresentation(t)}return !1}setColorRepresentation(t){return t=t.toUpperCase(),!!this._root.interaction.options.find((e=>e.getAttribute("data-type").startsWith(t)&&!e.click()))}getColorRepresentation(){return this._representation}getColor(){return this._color}getSelectedColor(){return this._lastColor}getRoot(){return this._root}disable(){return this.hide(),this.options.disabled=!0,this._root.button.classList.add("disabled"),this}enable(){return this.options.disabled=!1,this._root.button.classList.remove("disabled"),this}}return P(x,"utils",o),P(x,"version","1.8.4"),P(x,"I18N_DEFAULTS",{"ui:dialog":"color picker dialog","btn:toggle":"toggle color picker dialog","btn:swatch":"color swatch","btn:last-color":"use previous color","btn:save":"Save","btn:cancel":"Cancel","btn:clear":"Clear","aria:btn:save":"save and close","aria:btn:cancel":"cancel and close","aria:btn:clear":"clear and close","aria:input":"color input field","aria:palette":"color selection area","aria:hue":"hue selection slider","aria:opacity":"selection slider"}),P(x,"DEFAULT_OPTIONS",{appClass:null,theme:"classic",useAsButton:!1,padding:8,disabled:!1,comparison:!0,closeOnScroll:!1,outputPrecision:0,lockOpacity:!1,autoReposition:!0,container:"body",components:{interaction:{}},i18n:{},swatches:null,inline:!1,sliders:null,default:"#42445a",defaultRepresentation:null,position:"bottom-middle",adjustableNumbers:!0,showAlways:!1,closeWithKey:"Escape"}),P(x,"create",(t=>new x(t))),e=e.default})()}));
  4079. });
  4080. var Pickr = /*@__PURE__*/getDefaultExportFromCjs(pickr_min);
  4081. class VariableColorSettingComponent extends AbstractSettingComponent {
  4082. render() {
  4083. var _a;
  4084. const title = getTitle(this.setting);
  4085. const description = getDescription(this.setting);
  4086. if (typeof this.setting.default !== 'string' ||
  4087. !isValidDefaultColor(this.setting.default)) {
  4088. this.setting.default = (_a = this.settingsManager.plugin
  4089. .getCSSVar(this.setting.id)
  4090. .current) === null || _a === void 0 ? void 0 : _a.trim();
  4091. }
  4092. if (typeof this.setting.default !== 'string' ||
  4093. !isValidDefaultColor(this.setting.default)) {
  4094. return console.error(`${t('Error:')} ${title} ${t('missing default value, or value is not in a valid color format')}`);
  4095. }
  4096. const value = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4097. const swatches = [];
  4098. if (this.setting.default) {
  4099. swatches.push(this.setting.default);
  4100. }
  4101. if (value !== undefined) {
  4102. swatches.push(value);
  4103. }
  4104. this.settingEl = new obsidian.Setting(this.containerEl);
  4105. this.settingEl.setName(title);
  4106. this.settingEl.setDesc(createDescription(description, this.setting.default));
  4107. // fix, so that the color is correctly shown before the color picker has been opened
  4108. const defaultColor = value !== undefined ? value : this.setting.default;
  4109. this.containerEl.style.setProperty('--pcr-color', defaultColor);
  4110. this.pickr = Pickr.create(getPickrSettings({
  4111. isView: this.isView,
  4112. el: this.settingEl.controlEl.createDiv({ cls: 'picker' }),
  4113. containerEl: this.containerEl,
  4114. swatches: swatches,
  4115. opacity: this.setting.opacity,
  4116. defaultColor: defaultColor,
  4117. }));
  4118. this.pickr.on('save', (color, instance) => {
  4119. if (!color)
  4120. return;
  4121. this.settingsManager.setSetting(this.sectionId, this.setting.id, color.toHEXA().toString());
  4122. instance.hide();
  4123. instance.addSwatch(color.toHEXA().toString());
  4124. });
  4125. this.pickr.on('show', () => {
  4126. const { result } = this.pickr.getRoot().interaction;
  4127. activeWindow.requestAnimationFrame(() => {
  4128. activeWindow.requestAnimationFrame(() => result.select());
  4129. });
  4130. });
  4131. this.pickr.on('cancel', onPickrCancel);
  4132. this.settingEl.addExtraButton((b) => {
  4133. b.setIcon('reset');
  4134. b.onClick(() => {
  4135. this.pickr.setColor(this.setting.default);
  4136. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  4137. });
  4138. b.setTooltip(resetTooltip);
  4139. });
  4140. this.settingEl.settingEl.dataset.id = this.setting.id;
  4141. }
  4142. destroy() {
  4143. var _a, _b;
  4144. (_a = this.pickr) === null || _a === void 0 ? void 0 : _a.destroyAndRemove();
  4145. this.pickr = undefined;
  4146. (_b = this.settingEl) === null || _b === void 0 ? void 0 : _b.settingEl.remove();
  4147. }
  4148. }
  4149. class VariableNumberSettingComponent extends AbstractSettingComponent {
  4150. render() {
  4151. const title = getTitle(this.setting);
  4152. const description = getDescription(this.setting);
  4153. if (typeof this.setting.default !== 'number') {
  4154. return console.error(`${t('Error:')} ${title} ${t('missing default value')}`);
  4155. }
  4156. this.settingEl = new obsidian.Setting(this.containerEl);
  4157. this.settingEl.setName(title);
  4158. this.settingEl.setDesc(createDescription(description, this.setting.default.toString(10)));
  4159. this.settingEl.addText((text) => {
  4160. const value = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4161. const onChange = obsidian.debounce((value) => {
  4162. const isFloat = /\./.test(value);
  4163. this.settingsManager.setSetting(this.sectionId, this.setting.id, isFloat ? parseFloat(value) : parseInt(value, 10));
  4164. }, 250, true);
  4165. text.setValue(value !== undefined ? value.toString() : this.setting.default.toString());
  4166. text.onChange(onChange);
  4167. this.textComponent = text;
  4168. });
  4169. this.settingEl.addExtraButton((b) => {
  4170. b.setIcon('reset');
  4171. b.onClick(() => {
  4172. this.textComponent.setValue(this.setting.default.toString());
  4173. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  4174. });
  4175. b.setTooltip(resetTooltip);
  4176. });
  4177. this.settingEl.settingEl.dataset.id = this.setting.id;
  4178. }
  4179. destroy() {
  4180. var _a;
  4181. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4182. }
  4183. }
  4184. class VariableNumberSliderSettingComponent extends AbstractSettingComponent {
  4185. render() {
  4186. const title = getTitle(this.setting);
  4187. const description = getDescription(this.setting);
  4188. if (typeof this.setting.default !== 'number') {
  4189. return console.error(`${t('Error:')} ${title} ${t('missing default value')}`);
  4190. }
  4191. this.settingEl = new obsidian.Setting(this.containerEl);
  4192. this.settingEl.setName(title);
  4193. this.settingEl.setDesc(createDescription(description, this.setting.default.toString(10)));
  4194. this.settingEl.addSlider((slider) => {
  4195. const value = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4196. const onChange = obsidian.debounce((value) => {
  4197. this.settingsManager.setSetting(this.sectionId, this.setting.id, value);
  4198. }, 250, true);
  4199. slider.setDynamicTooltip();
  4200. slider.setLimits(this.setting.min, this.setting.max, this.setting.step);
  4201. slider.setValue(value !== undefined ? value : this.setting.default);
  4202. slider.onChange(onChange);
  4203. this.sliderComponent = slider;
  4204. });
  4205. this.settingEl.addExtraButton((b) => {
  4206. b.setIcon('reset');
  4207. b.onClick(() => {
  4208. this.sliderComponent.setValue(this.setting.default);
  4209. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  4210. });
  4211. b.setTooltip(resetTooltip);
  4212. });
  4213. this.settingEl.settingEl.dataset.id = this.setting.id;
  4214. }
  4215. destroy() {
  4216. var _a;
  4217. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4218. }
  4219. }
  4220. class VariableSelectSettingComponent extends AbstractSettingComponent {
  4221. render() {
  4222. const title = getTitle(this.setting);
  4223. const description = getDescription(this.setting);
  4224. if (typeof this.setting.default !== 'string') {
  4225. return console.error(`${t('Error:')} ${title} ${t('missing default value')}`);
  4226. }
  4227. const defaultLabel = this.getDefaultOptionLabel();
  4228. this.settingEl = new obsidian.Setting(this.containerEl);
  4229. this.settingEl.setName(title);
  4230. this.settingEl.setDesc(createDescription(description, this.setting.default, defaultLabel));
  4231. this.settingEl.addDropdown((dropdown) => {
  4232. const value = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4233. for (const o of this.setting.options) {
  4234. if (typeof o === 'string') {
  4235. dropdown.addOption(o, o);
  4236. }
  4237. else {
  4238. dropdown.addOption(o.value, o.label);
  4239. }
  4240. }
  4241. dropdown.setValue(value !== undefined ? value : this.setting.default);
  4242. dropdown.onChange((value) => {
  4243. this.settingsManager.setSetting(this.sectionId, this.setting.id, value);
  4244. });
  4245. this.dropdownComponent = dropdown;
  4246. });
  4247. this.settingEl.addExtraButton((b) => {
  4248. b.setIcon('reset');
  4249. b.onClick(() => {
  4250. this.dropdownComponent.setValue(this.setting.default);
  4251. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  4252. });
  4253. b.setTooltip(resetTooltip);
  4254. });
  4255. this.settingEl.settingEl.dataset.id = this.setting.id;
  4256. }
  4257. destroy() {
  4258. var _a;
  4259. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4260. }
  4261. getDefaultOption() {
  4262. if (this.setting.default) {
  4263. return this.setting.options.find((o) => {
  4264. if (typeof o === 'string') {
  4265. return o === this.setting.default;
  4266. }
  4267. return o.value === this.setting.default;
  4268. });
  4269. }
  4270. return undefined;
  4271. }
  4272. getDefaultOptionLabel() {
  4273. const defaultOption = this.getDefaultOption();
  4274. if (defaultOption) {
  4275. if (typeof defaultOption === 'string') {
  4276. return defaultOption;
  4277. }
  4278. return defaultOption.label;
  4279. }
  4280. return undefined;
  4281. }
  4282. }
  4283. class VariableTextSettingComponent extends AbstractSettingComponent {
  4284. render() {
  4285. const title = getTitle(this.setting);
  4286. const description = getDescription(this.setting);
  4287. if (typeof this.setting.default !== 'string') {
  4288. return console.error(`${t('Error:')} ${title} ${t('missing default value')}`);
  4289. }
  4290. this.settingEl = new obsidian.Setting(this.containerEl);
  4291. this.settingEl.setName(title);
  4292. this.settingEl.setDesc(createDescription(description, this.setting.default));
  4293. this.settingEl.addText((text) => {
  4294. let value = this.settingsManager.getSetting(this.sectionId, this.setting.id);
  4295. const onChange = obsidian.debounce((value) => {
  4296. this.settingsManager.setSetting(this.sectionId, this.setting.id, sanitizeText(value));
  4297. }, 250, true);
  4298. if (this.setting.quotes && value === `""`) {
  4299. value = ``;
  4300. }
  4301. text.setValue(value ? value.toString() : this.setting.default);
  4302. text.onChange(onChange);
  4303. this.textComponent = text;
  4304. });
  4305. this.settingEl.addExtraButton((b) => {
  4306. b.setIcon('reset');
  4307. b.onClick(() => {
  4308. this.textComponent.setValue(this.setting.default);
  4309. this.settingsManager.clearSetting(this.sectionId, this.setting.id);
  4310. });
  4311. b.setTooltip(resetTooltip);
  4312. });
  4313. this.settingEl.settingEl.dataset.id = this.setting.id;
  4314. }
  4315. destroy() {
  4316. var _a;
  4317. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4318. }
  4319. }
  4320. class VariableThemedColorSettingComponent extends AbstractSettingComponent {
  4321. render() {
  4322. const title = getTitle(this.setting);
  4323. const description = getDescription(this.setting);
  4324. if (typeof this.setting['default-light'] !== 'string' ||
  4325. !isValidDefaultColor(this.setting['default-light'])) {
  4326. return console.error(`${t('Error:')} ${title} ${t('missing default light value, or value is not in a valid color format')}`);
  4327. }
  4328. if (typeof this.setting['default-dark'] !== 'string' ||
  4329. !isValidDefaultColor(this.setting['default-dark'])) {
  4330. return console.error(`${t('Error:')} ${title} ${t('missing default dark value, or value is not in a valid color format')}`);
  4331. }
  4332. const idLight = `${this.setting.id}@@light`;
  4333. const idDark = `${this.setting.id}@@dark`;
  4334. const valueLight = this.settingsManager.getSetting(this.sectionId, idLight);
  4335. const valueDark = this.settingsManager.getSetting(this.sectionId, idDark);
  4336. const swatchesLight = [];
  4337. const swatchesDark = [];
  4338. if (this.setting['default-light']) {
  4339. swatchesLight.push(this.setting['default-light']);
  4340. }
  4341. if (valueLight !== undefined) {
  4342. swatchesLight.push(valueLight);
  4343. }
  4344. if (this.setting['default-dark']) {
  4345. swatchesDark.push(this.setting['default-dark']);
  4346. }
  4347. if (valueDark !== undefined) {
  4348. swatchesDark.push(valueDark);
  4349. }
  4350. this.settingEl = new obsidian.Setting(this.containerEl);
  4351. this.settingEl.setName(title);
  4352. // Construct description
  4353. this.settingEl.descEl.createSpan({}, (span) => {
  4354. if (description) {
  4355. span.appendChild(document.createTextNode(description));
  4356. }
  4357. });
  4358. this.settingEl.descEl.createDiv({}, (div) => {
  4359. div.createEl('small', {}, (sm) => {
  4360. sm.appendChild(createEl('strong', { text: 'Default (light): ' }));
  4361. sm.appendChild(document.createTextNode(this.setting['default-light']));
  4362. });
  4363. div.createEl('br');
  4364. div.createEl('small', {}, (sm) => {
  4365. sm.appendChild(createEl('strong', { text: 'Default (dark): ' }));
  4366. sm.appendChild(document.createTextNode(this.setting['default-dark']));
  4367. });
  4368. });
  4369. const wrapper = this.settingEl.controlEl.createDiv({
  4370. cls: 'themed-color-wrapper',
  4371. });
  4372. // Create light color picker
  4373. this.createColorPickerLight(wrapper, this.containerEl, swatchesLight, valueLight, idLight);
  4374. // Create dark color picker
  4375. this.createColorPickerDark(wrapper, this.containerEl, swatchesDark, valueDark, idDark);
  4376. this.settingEl.settingEl.dataset.id = this.setting.id;
  4377. }
  4378. destroy() {
  4379. var _a, _b, _c;
  4380. (_a = this.pickrLight) === null || _a === void 0 ? void 0 : _a.destroyAndRemove();
  4381. (_b = this.pickrDark) === null || _b === void 0 ? void 0 : _b.destroyAndRemove();
  4382. this.pickrLight = undefined;
  4383. this.pickrDark = undefined;
  4384. (_c = this.settingEl) === null || _c === void 0 ? void 0 : _c.settingEl.remove();
  4385. }
  4386. createColorPickerLight(wrapper, containerEl, swatchesLight, valueLight, idLight) {
  4387. const themeLightWrapper = wrapper.createDiv({ cls: 'theme-light' });
  4388. // fix, so that the color is correctly shown before the color picker has been opened
  4389. const defaultColor = valueLight !== undefined
  4390. ? valueLight
  4391. : this.setting['default-light'];
  4392. themeLightWrapper.style.setProperty('--pcr-color', defaultColor);
  4393. this.pickrLight = Pickr.create(getPickrSettings({
  4394. isView: this.isView,
  4395. el: themeLightWrapper.createDiv({ cls: 'picker' }),
  4396. containerEl,
  4397. swatches: swatchesLight,
  4398. opacity: this.setting.opacity,
  4399. defaultColor: defaultColor,
  4400. }));
  4401. this.pickrLight.on('show', () => {
  4402. const { result } = this.pickrLight.getRoot().interaction;
  4403. activeWindow.requestAnimationFrame(() => activeWindow.requestAnimationFrame(() => result.select()));
  4404. });
  4405. this.pickrLight.on('save', (color, instance) => this.onSave(idLight, color, instance));
  4406. this.pickrLight.on('cancel', onPickrCancel);
  4407. const themeLightReset = new obsidian.ButtonComponent(themeLightWrapper.createDiv({ cls: 'pickr-reset' }));
  4408. themeLightReset.setIcon('reset');
  4409. themeLightReset.onClick(() => {
  4410. this.pickrLight.setColor(this.setting['default-light']);
  4411. this.settingsManager.clearSetting(this.sectionId, idLight);
  4412. });
  4413. themeLightReset.setTooltip(resetTooltip);
  4414. }
  4415. createColorPickerDark(wrapper, containerEl, swatchesDark, valueDark, idDark) {
  4416. const themeDarkWrapper = wrapper.createDiv({ cls: 'theme-dark' });
  4417. // fix, so that the color is correctly shown before the color picker has been opened
  4418. const defaultColor = valueDark !== undefined
  4419. ? valueDark
  4420. : this.setting['default-dark'];
  4421. themeDarkWrapper.style.setProperty('--pcr-color', defaultColor);
  4422. this.pickrDark = Pickr.create(getPickrSettings({
  4423. isView: this.isView,
  4424. el: themeDarkWrapper.createDiv({ cls: 'picker' }),
  4425. containerEl,
  4426. swatches: swatchesDark,
  4427. opacity: this.setting.opacity,
  4428. defaultColor: defaultColor,
  4429. }));
  4430. this.pickrDark.on('show', () => {
  4431. const { result } = this.pickrDark.getRoot().interaction;
  4432. activeWindow.requestAnimationFrame(() => activeWindow.requestAnimationFrame(() => result.select()));
  4433. });
  4434. this.pickrDark.on('save', (color, instance) => this.onSave(idDark, color, instance));
  4435. this.pickrDark.on('cancel', onPickrCancel);
  4436. const themeDarkReset = new obsidian.ButtonComponent(themeDarkWrapper.createDiv({ cls: 'pickr-reset' }));
  4437. themeDarkReset.setIcon('reset');
  4438. themeDarkReset.onClick(() => {
  4439. this.pickrDark.setColor(this.setting['default-dark']);
  4440. this.settingsManager.clearSetting(this.sectionId, idDark);
  4441. });
  4442. themeDarkReset.setTooltip(resetTooltip);
  4443. }
  4444. onSave(id, color, instance) {
  4445. if (!color)
  4446. return;
  4447. this.settingsManager.setSetting(this.sectionId, id, color.toHEXA().toString());
  4448. instance.hide();
  4449. instance.addSwatch(color.toHEXA().toString());
  4450. }
  4451. }
  4452. function createSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView) {
  4453. if (setting.type === SettingType.HEADING) {
  4454. return new HeadingSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4455. }
  4456. else if (setting.type === SettingType.INFO_TEXT) {
  4457. return new InfoTextSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4458. }
  4459. else if (setting.type === SettingType.CLASS_TOGGLE) {
  4460. return new ClassToggleSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4461. }
  4462. else if (setting.type === SettingType.CLASS_SELECT) {
  4463. return new ClassMultiToggleSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4464. }
  4465. else if (setting.type === SettingType.VARIABLE_TEXT) {
  4466. return new VariableTextSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4467. }
  4468. else if (setting.type === SettingType.VARIABLE_NUMBER) {
  4469. return new VariableNumberSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4470. }
  4471. else if (setting.type === SettingType.VARIABLE_NUMBER_SLIDER) {
  4472. return new VariableNumberSliderSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4473. }
  4474. else if (setting.type === SettingType.VARIABLE_SELECT) {
  4475. return new VariableSelectSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4476. }
  4477. else if (setting.type === SettingType.VARIABLE_COLOR) {
  4478. return new VariableColorSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4479. }
  4480. else if (setting.type === SettingType.VARIABLE_THEMED_COLOR) {
  4481. return new VariableThemedColorSettingComponent(parent, sectionId, sectionName, setting, settingsManager, isView);
  4482. }
  4483. else {
  4484. return undefined;
  4485. }
  4486. }
  4487. function buildSettingComponentTree(opts) {
  4488. const { containerEl, isView, sectionId, settings, settingsManager, sectionName, } = opts;
  4489. const root = new HeadingSettingComponent(containerEl, sectionId, sectionName, settings[0], settingsManager, isView);
  4490. let currentHeading = root;
  4491. for (const setting of settings.splice(1)) {
  4492. if (setting.type === 'heading') {
  4493. const newHeading = setting;
  4494. if (newHeading.level < currentHeading.setting.level) {
  4495. while (newHeading.level < currentHeading.setting.level) {
  4496. currentHeading = currentHeading.parent;
  4497. }
  4498. if (currentHeading.setting.id === root.setting.id) {
  4499. currentHeading = currentHeading.addSettingChild(newHeading);
  4500. }
  4501. else {
  4502. currentHeading = currentHeading.parent.addSettingChild(newHeading);
  4503. }
  4504. }
  4505. else if (newHeading.level === currentHeading.setting.level) {
  4506. currentHeading = currentHeading.parent.addSettingChild(newHeading);
  4507. }
  4508. else {
  4509. currentHeading = currentHeading.addSettingChild(newHeading);
  4510. }
  4511. }
  4512. else {
  4513. currentHeading.addSettingChild(setting);
  4514. }
  4515. }
  4516. return root;
  4517. }
  4518. class HeadingSettingComponent extends AbstractSettingComponent {
  4519. constructor() {
  4520. super(...arguments);
  4521. this.children = [];
  4522. this.filteredChildren = [];
  4523. this.filterMode = false;
  4524. this.filterResultCount = 0;
  4525. }
  4526. render() {
  4527. const title = getTitle(this.setting);
  4528. const description = getDescription(this.setting);
  4529. this.settingEl = new obsidian.Setting(this.containerEl);
  4530. this.settingEl.setHeading();
  4531. this.settingEl.setClass('style-settings-heading');
  4532. this.settingEl.setName(title);
  4533. this.settingEl.setDesc(description !== null && description !== void 0 ? description : '');
  4534. this.settingEl.settingEl.dataset.level = this.setting.level.toString();
  4535. this.settingEl.settingEl.dataset.id = this.setting.id;
  4536. const iconContainer = createSpan({
  4537. cls: 'style-settings-collapse-indicator',
  4538. });
  4539. obsidian.setIcon(iconContainer, 'right-triangle');
  4540. this.settingEl.nameEl.prepend(iconContainer);
  4541. this.resultsEl = this.settingEl.nameEl.createSpan({
  4542. cls: 'style-settings-filter-result-count',
  4543. text: this.filterMode ? `${this.filterResultCount} Results` : undefined,
  4544. });
  4545. this.settingEl.settingEl.addEventListener('click', () => {
  4546. this.toggleVisible();
  4547. });
  4548. this.addResetButton();
  4549. this.addExportButton();
  4550. this.childEl = this.containerEl.createDiv({
  4551. cls: 'style-settings-container',
  4552. });
  4553. this.setCollapsed(this.setting.collapsed);
  4554. }
  4555. destroy() {
  4556. var _a;
  4557. this.removeChildren();
  4558. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.remove();
  4559. this.childEl.remove();
  4560. }
  4561. filter(filterString) {
  4562. var _a;
  4563. this.filteredChildren = [];
  4564. this.filterResultCount = 0;
  4565. for (const child of this.children) {
  4566. if (child.setting.type === SettingType.HEADING) {
  4567. const childResultCount = child.filter(filterString);
  4568. if (childResultCount > 0) {
  4569. this.filterResultCount += childResultCount;
  4570. this.filteredChildren.push(child);
  4571. }
  4572. }
  4573. else {
  4574. if (child.decisiveMatch(filterString)) {
  4575. this.filteredChildren.push(child);
  4576. this.filterResultCount += 1;
  4577. }
  4578. }
  4579. }
  4580. this.filterMode = true;
  4581. if (this.filterResultCount) {
  4582. this.setCollapsed(false);
  4583. }
  4584. else {
  4585. this.setCollapsed(true);
  4586. }
  4587. this.renderChildren();
  4588. (_a = this.resultsEl) === null || _a === void 0 ? void 0 : _a.setText(`${this.filterResultCount} Results`);
  4589. return this.filterResultCount;
  4590. }
  4591. clearFilter() {
  4592. var _a;
  4593. this.filteredChildren = [];
  4594. for (const child of this.children) {
  4595. if (child.setting.type === SettingType.HEADING) {
  4596. child.clearFilter();
  4597. }
  4598. }
  4599. this.filterMode = false;
  4600. this.setCollapsed(true);
  4601. this.renderChildren();
  4602. (_a = this.resultsEl) === null || _a === void 0 ? void 0 : _a.empty();
  4603. }
  4604. renderChildren() {
  4605. this.removeChildren();
  4606. if (this.filterMode) {
  4607. for (const child of this.filteredChildren) {
  4608. this.addChild(child);
  4609. }
  4610. }
  4611. else {
  4612. for (const child of this.children) {
  4613. this.addChild(child);
  4614. }
  4615. }
  4616. }
  4617. removeChildren() {
  4618. for (const child of this.children) {
  4619. this.removeChild(child);
  4620. }
  4621. }
  4622. toggleVisible() {
  4623. this.setCollapsed(!this.setting.collapsed);
  4624. }
  4625. setCollapsed(collapsed) {
  4626. var _a;
  4627. this.setting.collapsed = collapsed;
  4628. (_a = this.settingEl) === null || _a === void 0 ? void 0 : _a.settingEl.toggleClass('is-collapsed', collapsed);
  4629. if (collapsed) {
  4630. this.removeChildren();
  4631. }
  4632. else {
  4633. this.renderChildren();
  4634. }
  4635. }
  4636. addResetButton() {
  4637. if (this.setting.resetFn) {
  4638. this.settingEl.addExtraButton((b) => {
  4639. b.setIcon('reset')
  4640. .setTooltip('Reset all settings to default')
  4641. .onClick(this.setting.resetFn);
  4642. });
  4643. }
  4644. }
  4645. addExportButton() {
  4646. this.settingEl.addExtraButton((b) => {
  4647. b.setIcon('install');
  4648. b.setTooltip('Export settings');
  4649. b.extraSettingsEl.onClickEvent((e) => {
  4650. e.stopPropagation();
  4651. let title = getTitle(this.setting);
  4652. title =
  4653. this.sectionName === title ? title : `${this.sectionName} > ${title}`;
  4654. this.settingsManager.export(title, this.settingsManager.getSettings(this.sectionId, this.getAllChildrenIds()));
  4655. });
  4656. });
  4657. }
  4658. addSettingChild(child) {
  4659. const newSettingComponent = createSettingComponent(this, this.sectionId, this.sectionName, child, this.settingsManager, this.isView);
  4660. if (!newSettingComponent) {
  4661. return undefined;
  4662. }
  4663. this.children.push(newSettingComponent);
  4664. return newSettingComponent;
  4665. }
  4666. getAllChildrenIds() {
  4667. const children = [];
  4668. for (const child of this.children) {
  4669. children.push(child.setting.id);
  4670. if (child.setting.type === 'heading') {
  4671. children.push(...child.getAllChildrenIds());
  4672. }
  4673. }
  4674. return children;
  4675. }
  4676. }
  4677. class SettingsMarkup extends obsidian.Component {
  4678. constructor(app, plugin, containerEl, isView) {
  4679. super();
  4680. this.settingsComponentTrees = [];
  4681. this.filterString = '';
  4682. this.settings = [];
  4683. this.errorList = [];
  4684. this.app = app;
  4685. this.plugin = plugin;
  4686. this.containerEl = containerEl;
  4687. this.isView = !!isView;
  4688. }
  4689. onload() {
  4690. this.display();
  4691. }
  4692. onunload() {
  4693. this.settingsComponentTrees = [];
  4694. }
  4695. display() {
  4696. this.generate(this.settings);
  4697. }
  4698. removeChildren() {
  4699. for (const settingsComponentTree of this.settingsComponentTrees) {
  4700. this.removeChild(settingsComponentTree);
  4701. }
  4702. }
  4703. /**
  4704. * Recursively destroys all setting elements.
  4705. */
  4706. cleanup() {
  4707. var _a;
  4708. this.removeChildren();
  4709. (_a = this.settingsContainerEl) === null || _a === void 0 ? void 0 : _a.empty();
  4710. }
  4711. setSettings(settings, errorList) {
  4712. this.settings = settings;
  4713. this.errorList = errorList;
  4714. if (this.containerEl.parentNode) {
  4715. this.generate(settings);
  4716. }
  4717. }
  4718. displayErrors() {
  4719. const { containerEl, errorList } = this;
  4720. errorList.forEach((err) => {
  4721. containerEl.createDiv({ cls: 'style-settings-error' }, (wrapper) => {
  4722. wrapper.createDiv({
  4723. cls: 'style-settings-error-name',
  4724. text: `Error: ${err.name}`,
  4725. });
  4726. wrapper.createDiv({
  4727. cls: 'style-settings-error-desc',
  4728. text: err.error,
  4729. });
  4730. });
  4731. });
  4732. }
  4733. displayEmpty() {
  4734. const { containerEl } = this;
  4735. containerEl.createDiv({ cls: 'style-settings-empty' }, (wrapper) => {
  4736. wrapper.createDiv({
  4737. cls: 'style-settings-empty-name',
  4738. text: 'No style settings found',
  4739. });
  4740. wrapper.createDiv({ cls: 'style-settings-empty-desc' }).appendChild(createFragment((frag) => {
  4741. frag.appendText('Style settings configured by theme and plugin authors will show up here. You can also create your own configuration by creating a CSS snippet in your vault. ');
  4742. frag.createEl('a', {
  4743. text: 'Click here for details and examples.',
  4744. href: 'https://github.com/mgmeyers/obsidian-style-settings#obsidian-style-settings-plugin',
  4745. });
  4746. }));
  4747. });
  4748. }
  4749. generate(settings) {
  4750. var _a;
  4751. const { containerEl, plugin } = this;
  4752. containerEl.empty();
  4753. this.cleanup();
  4754. this.displayErrors();
  4755. if (settings.length === 0) {
  4756. return this.displayEmpty();
  4757. }
  4758. new obsidian.Setting(containerEl).then((setting) => {
  4759. // Build and import link to open the import modal
  4760. setting.controlEl.createEl('a', {
  4761. cls: 'style-settings-import',
  4762. text: 'Import',
  4763. href: '#',
  4764. }, (el) => {
  4765. el.addEventListener('click', (e) => {
  4766. e.preventDefault();
  4767. this.plugin.settingsManager.import();
  4768. });
  4769. });
  4770. // Build and export link to open the export modal
  4771. setting.controlEl.createEl('a', {
  4772. cls: 'style-settings-export',
  4773. text: 'Export',
  4774. href: '#',
  4775. }, (el) => {
  4776. el.addEventListener('click', (e) => {
  4777. e.preventDefault();
  4778. this.plugin.settingsManager.export('All settings', this.plugin.settingsManager.settings);
  4779. });
  4780. });
  4781. // Searchbar
  4782. let searchComponent;
  4783. setting.addSearch((s) => {
  4784. searchComponent = s;
  4785. });
  4786. // move the search component from the back to the front
  4787. setting.nameEl.appendChild(setting.controlEl.lastChild);
  4788. searchComponent.setValue(this.filterString);
  4789. searchComponent.onChange(obsidian.debounce((value) => {
  4790. this.filterString = value;
  4791. if (value) {
  4792. this.filter();
  4793. }
  4794. else {
  4795. this.clearFilter();
  4796. }
  4797. }, 250, true));
  4798. searchComponent.setPlaceholder('Search Style Settings...');
  4799. });
  4800. this.settingsContainerEl = containerEl.createDiv();
  4801. this.settingsComponentTrees = [];
  4802. for (const s of settings) {
  4803. const options = [
  4804. {
  4805. id: s.id,
  4806. type: 'heading',
  4807. title: s.name,
  4808. level: 0,
  4809. collapsed: (_a = s.collapsed) !== null && _a !== void 0 ? _a : true,
  4810. resetFn: () => {
  4811. plugin.settingsManager.clearSection(s.id);
  4812. this.rerender();
  4813. },
  4814. },
  4815. ...s.settings,
  4816. ];
  4817. try {
  4818. const settingsComponentTree = buildSettingComponentTree({
  4819. containerEl: this.settingsContainerEl,
  4820. isView: this.isView,
  4821. sectionId: s.id,
  4822. sectionName: s.name,
  4823. settings: options,
  4824. settingsManager: plugin.settingsManager,
  4825. });
  4826. this.addChild(settingsComponentTree);
  4827. this.settingsComponentTrees.push(settingsComponentTree);
  4828. }
  4829. catch (e) {
  4830. console.error('Style Settings | Failed to render section', e);
  4831. }
  4832. }
  4833. }
  4834. /**
  4835. * Recursively filter all setting elements based on `filterString` and then re-renders.
  4836. */
  4837. filter() {
  4838. for (const settingsComponentTree of this.settingsComponentTrees) {
  4839. settingsComponentTree.filter(this.filterString);
  4840. }
  4841. }
  4842. /**
  4843. * Recursively clears the filter and then re-renders.
  4844. */
  4845. clearFilter() {
  4846. for (const settingsComponentTree of this.settingsComponentTrees) {
  4847. settingsComponentTree.clearFilter();
  4848. }
  4849. }
  4850. rerender() {
  4851. this.cleanup();
  4852. this.display();
  4853. }
  4854. }
  4855. class CSSSettingsTab extends obsidian.PluginSettingTab {
  4856. constructor(app, plugin) {
  4857. super(app, plugin);
  4858. this.plugin = plugin;
  4859. }
  4860. rerender() {
  4861. var _a;
  4862. (_a = this.settingsMarkup) === null || _a === void 0 ? void 0 : _a.rerender();
  4863. }
  4864. setSettings(settings, errorList) {
  4865. this.settings = settings;
  4866. this.errorList = errorList;
  4867. if (this.settingsMarkup) {
  4868. this.settingsMarkup.setSettings(settings, errorList);
  4869. }
  4870. }
  4871. display() {
  4872. this.settingsMarkup = this.plugin.addChild(new SettingsMarkup(this.app, this.plugin, this.containerEl));
  4873. if (this.settings) {
  4874. this.settingsMarkup.setSettings(this.settings, this.errorList);
  4875. }
  4876. }
  4877. hide() {
  4878. this.plugin.removeChild(this.settingsMarkup);
  4879. this.settingsMarkup = null;
  4880. }
  4881. }
  4882. const viewType = 'style-settings';
  4883. class SettingsView extends obsidian.ItemView {
  4884. constructor(plugin, leaf) {
  4885. super(leaf);
  4886. this.plugin = plugin;
  4887. }
  4888. rerender() {
  4889. var _a;
  4890. (_a = this.settingsMarkup) === null || _a === void 0 ? void 0 : _a.rerender();
  4891. }
  4892. setSettings(settings, errorList) {
  4893. this.settings = settings;
  4894. this.errorList = errorList;
  4895. if (this.settingsMarkup) {
  4896. this.settingsMarkup.setSettings(settings, errorList);
  4897. }
  4898. }
  4899. onload() {
  4900. this.settingsMarkup = this.addChild(new SettingsMarkup(this.plugin.app, this.plugin, this.contentEl, true));
  4901. if (this.settings) {
  4902. this.settingsMarkup.setSettings(this.settings, this.errorList);
  4903. }
  4904. }
  4905. onunload() {
  4906. this.settingsMarkup = null;
  4907. }
  4908. getViewType() {
  4909. return viewType;
  4910. }
  4911. getIcon() {
  4912. return 'gear';
  4913. }
  4914. getDisplayText() {
  4915. return 'Style Settings';
  4916. }
  4917. }
  4918. // Detect either spaces or tabs but not both to properly handle tabs for indentation and spaces for alignment
  4919. const INDENT_REGEX = /^(?:( )+|\t+)/;
  4920. const INDENT_TYPE_SPACE = 'space';
  4921. const INDENT_TYPE_TAB = 'tab';
  4922. /**
  4923. Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation.
  4924. The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents.
  4925. ```
  4926. indents = {
  4927. t3: [1, 0],
  4928. t4: [1, 5],
  4929. s5: [1, 0],
  4930. s12: [1, 0],
  4931. }
  4932. ```
  4933. */
  4934. function makeIndentsMap(string, ignoreSingleSpaces) {
  4935. const indents = new Map();
  4936. // Remember the size of previous line's indentation
  4937. let previousSize = 0;
  4938. let previousIndentType;
  4939. // Indents key (ident type + size of the indents/unindents)
  4940. let key;
  4941. for (const line of string.split(/\n/g)) {
  4942. if (!line) {
  4943. // Ignore empty lines
  4944. continue;
  4945. }
  4946. let indent;
  4947. let indentType;
  4948. let weight;
  4949. let entry;
  4950. const matches = line.match(INDENT_REGEX);
  4951. if (matches === null) {
  4952. previousSize = 0;
  4953. previousIndentType = '';
  4954. } else {
  4955. indent = matches[0].length;
  4956. indentType = matches[1] ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
  4957. // Ignore single space unless it's the only indent detected to prevent common false positives
  4958. if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) {
  4959. continue;
  4960. }
  4961. if (indentType !== previousIndentType) {
  4962. previousSize = 0;
  4963. }
  4964. previousIndentType = indentType;
  4965. weight = 0;
  4966. const indentDifference = indent - previousSize;
  4967. previousSize = indent;
  4968. // Previous line have same indent?
  4969. if (indentDifference === 0) {
  4970. weight++;
  4971. // We use the key from previous loop
  4972. } else {
  4973. const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference;
  4974. key = encodeIndentsKey(indentType, absoluteIndentDifference);
  4975. }
  4976. // Update the stats
  4977. entry = indents.get(key);
  4978. entry = entry === undefined ? [1, 0] : [++entry[0], entry[1] + weight];
  4979. indents.set(key, entry);
  4980. }
  4981. }
  4982. return indents;
  4983. }
  4984. // Encode the indent type and amount as a string (e.g. 's4') for use as a compound key in the indents Map.
  4985. function encodeIndentsKey(indentType, indentAmount) {
  4986. const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't';
  4987. return typeCharacter + String(indentAmount);
  4988. }
  4989. // Extract the indent type and amount from a key of the indents Map.
  4990. function decodeIndentsKey(indentsKey) {
  4991. const keyHasTypeSpace = indentsKey[0] === 's';
  4992. const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
  4993. const amount = Number(indentsKey.slice(1));
  4994. return {type, amount};
  4995. }
  4996. // Return the key (e.g. 's4') from the indents Map that represents the most common indent,
  4997. // or return undefined if there are no indents.
  4998. function getMostUsedKey(indents) {
  4999. let result;
  5000. let maxUsed = 0;
  5001. let maxWeight = 0;
  5002. for (const [key, [usedCount, weight]] of indents) {
  5003. if (usedCount > maxUsed || (usedCount === maxUsed && weight > maxWeight)) {
  5004. maxUsed = usedCount;
  5005. maxWeight = weight;
  5006. result = key;
  5007. }
  5008. }
  5009. return result;
  5010. }
  5011. function makeIndentString(type, amount) {
  5012. const indentCharacter = type === INDENT_TYPE_SPACE ? ' ' : '\t';
  5013. return indentCharacter.repeat(amount);
  5014. }
  5015. function detectIndent(string) {
  5016. if (typeof string !== 'string') {
  5017. throw new TypeError('Expected a string');
  5018. }
  5019. // Identify indents while skipping single space indents to avoid common edge cases (e.g. code comments)
  5020. // If no indents are identified, run again and include all indents for comprehensive detection
  5021. let indents = makeIndentsMap(string, true);
  5022. if (indents.size === 0) {
  5023. indents = makeIndentsMap(string, false);
  5024. }
  5025. const keyOfMostUsedIndent = getMostUsedKey(indents);
  5026. let type;
  5027. let amount = 0;
  5028. let indent = '';
  5029. if (keyOfMostUsedIndent !== undefined) {
  5030. ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent));
  5031. indent = makeIndentString(type, amount);
  5032. }
  5033. return {
  5034. amount,
  5035. type,
  5036. indent,
  5037. };
  5038. }
  5039. /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
  5040. function isNothing(subject) {
  5041. return (typeof subject === 'undefined') || (subject === null);
  5042. }
  5043. function isObject(subject) {
  5044. return (typeof subject === 'object') && (subject !== null);
  5045. }
  5046. function toArray(sequence) {
  5047. if (Array.isArray(sequence)) return sequence;
  5048. else if (isNothing(sequence)) return [];
  5049. return [ sequence ];
  5050. }
  5051. function extend(target, source) {
  5052. var index, length, key, sourceKeys;
  5053. if (source) {
  5054. sourceKeys = Object.keys(source);
  5055. for (index = 0, length = sourceKeys.length; index < length; index += 1) {
  5056. key = sourceKeys[index];
  5057. target[key] = source[key];
  5058. }
  5059. }
  5060. return target;
  5061. }
  5062. function repeat(string, count) {
  5063. var result = '', cycle;
  5064. for (cycle = 0; cycle < count; cycle += 1) {
  5065. result += string;
  5066. }
  5067. return result;
  5068. }
  5069. function isNegativeZero(number) {
  5070. return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
  5071. }
  5072. var isNothing_1 = isNothing;
  5073. var isObject_1 = isObject;
  5074. var toArray_1 = toArray;
  5075. var repeat_1 = repeat;
  5076. var isNegativeZero_1 = isNegativeZero;
  5077. var extend_1 = extend;
  5078. var common = {
  5079. isNothing: isNothing_1,
  5080. isObject: isObject_1,
  5081. toArray: toArray_1,
  5082. repeat: repeat_1,
  5083. isNegativeZero: isNegativeZero_1,
  5084. extend: extend_1
  5085. };
  5086. // YAML error class. http://stackoverflow.com/questions/8458984
  5087. function formatError(exception, compact) {
  5088. var where = '', message = exception.reason || '(unknown reason)';
  5089. if (!exception.mark) return message;
  5090. if (exception.mark.name) {
  5091. where += 'in "' + exception.mark.name + '" ';
  5092. }
  5093. where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';
  5094. if (!compact && exception.mark.snippet) {
  5095. where += '\n\n' + exception.mark.snippet;
  5096. }
  5097. return message + ' ' + where;
  5098. }
  5099. function YAMLException$1(reason, mark) {
  5100. // Super constructor
  5101. Error.call(this);
  5102. this.name = 'YAMLException';
  5103. this.reason = reason;
  5104. this.mark = mark;
  5105. this.message = formatError(this, false);
  5106. // Include stack trace in error object
  5107. if (Error.captureStackTrace) {
  5108. // Chrome and NodeJS
  5109. Error.captureStackTrace(this, this.constructor);
  5110. } else {
  5111. // FF, IE 10+ and Safari 6+. Fallback for others
  5112. this.stack = (new Error()).stack || '';
  5113. }
  5114. }
  5115. // Inherit from Error
  5116. YAMLException$1.prototype = Object.create(Error.prototype);
  5117. YAMLException$1.prototype.constructor = YAMLException$1;
  5118. YAMLException$1.prototype.toString = function toString(compact) {
  5119. return this.name + ': ' + formatError(this, compact);
  5120. };
  5121. var exception = YAMLException$1;
  5122. // get snippet for a single line, respecting maxLength
  5123. function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
  5124. var head = '';
  5125. var tail = '';
  5126. var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
  5127. if (position - lineStart > maxHalfLength) {
  5128. head = ' ... ';
  5129. lineStart = position - maxHalfLength + head.length;
  5130. }
  5131. if (lineEnd - position > maxHalfLength) {
  5132. tail = ' ...';
  5133. lineEnd = position + maxHalfLength - tail.length;
  5134. }
  5135. return {
  5136. str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
  5137. pos: position - lineStart + head.length // relative position
  5138. };
  5139. }
  5140. function padStart(string, max) {
  5141. return common.repeat(' ', max - string.length) + string;
  5142. }
  5143. function makeSnippet(mark, options) {
  5144. options = Object.create(options || null);
  5145. if (!mark.buffer) return null;
  5146. if (!options.maxLength) options.maxLength = 79;
  5147. if (typeof options.indent !== 'number') options.indent = 1;
  5148. if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
  5149. if (typeof options.linesAfter !== 'number') options.linesAfter = 2;
  5150. var re = /\r?\n|\r|\0/g;
  5151. var lineStarts = [ 0 ];
  5152. var lineEnds = [];
  5153. var match;
  5154. var foundLineNo = -1;
  5155. while ((match = re.exec(mark.buffer))) {
  5156. lineEnds.push(match.index);
  5157. lineStarts.push(match.index + match[0].length);
  5158. if (mark.position <= match.index && foundLineNo < 0) {
  5159. foundLineNo = lineStarts.length - 2;
  5160. }
  5161. }
  5162. if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
  5163. var result = '', i, line;
  5164. var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
  5165. var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
  5166. for (i = 1; i <= options.linesBefore; i++) {
  5167. if (foundLineNo - i < 0) break;
  5168. line = getLine(
  5169. mark.buffer,
  5170. lineStarts[foundLineNo - i],
  5171. lineEnds[foundLineNo - i],
  5172. mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
  5173. maxLineLength
  5174. );
  5175. result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
  5176. ' | ' + line.str + '\n' + result;
  5177. }
  5178. line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
  5179. result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
  5180. ' | ' + line.str + '\n';
  5181. result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';
  5182. for (i = 1; i <= options.linesAfter; i++) {
  5183. if (foundLineNo + i >= lineEnds.length) break;
  5184. line = getLine(
  5185. mark.buffer,
  5186. lineStarts[foundLineNo + i],
  5187. lineEnds[foundLineNo + i],
  5188. mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
  5189. maxLineLength
  5190. );
  5191. result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
  5192. ' | ' + line.str + '\n';
  5193. }
  5194. return result.replace(/\n$/, '');
  5195. }
  5196. var snippet = makeSnippet;
  5197. var TYPE_CONSTRUCTOR_OPTIONS = [
  5198. 'kind',
  5199. 'multi',
  5200. 'resolve',
  5201. 'construct',
  5202. 'instanceOf',
  5203. 'predicate',
  5204. 'represent',
  5205. 'representName',
  5206. 'defaultStyle',
  5207. 'styleAliases'
  5208. ];
  5209. var YAML_NODE_KINDS = [
  5210. 'scalar',
  5211. 'sequence',
  5212. 'mapping'
  5213. ];
  5214. function compileStyleAliases(map) {
  5215. var result = {};
  5216. if (map !== null) {
  5217. Object.keys(map).forEach(function (style) {
  5218. map[style].forEach(function (alias) {
  5219. result[String(alias)] = style;
  5220. });
  5221. });
  5222. }
  5223. return result;
  5224. }
  5225. function Type$1(tag, options) {
  5226. options = options || {};
  5227. Object.keys(options).forEach(function (name) {
  5228. if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
  5229. throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
  5230. }
  5231. });
  5232. // TODO: Add tag format check.
  5233. this.options = options; // keep original options in case user wants to extend this type later
  5234. this.tag = tag;
  5235. this.kind = options['kind'] || null;
  5236. this.resolve = options['resolve'] || function () { return true; };
  5237. this.construct = options['construct'] || function (data) { return data; };
  5238. this.instanceOf = options['instanceOf'] || null;
  5239. this.predicate = options['predicate'] || null;
  5240. this.represent = options['represent'] || null;
  5241. this.representName = options['representName'] || null;
  5242. this.defaultStyle = options['defaultStyle'] || null;
  5243. this.multi = options['multi'] || false;
  5244. this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
  5245. if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
  5246. throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
  5247. }
  5248. }
  5249. var type = Type$1;
  5250. /*eslint-disable max-len*/
  5251. function compileList(schema, name) {
  5252. var result = [];
  5253. schema[name].forEach(function (currentType) {
  5254. var newIndex = result.length;
  5255. result.forEach(function (previousType, previousIndex) {
  5256. if (previousType.tag === currentType.tag &&
  5257. previousType.kind === currentType.kind &&
  5258. previousType.multi === currentType.multi) {
  5259. newIndex = previousIndex;
  5260. }
  5261. });
  5262. result[newIndex] = currentType;
  5263. });
  5264. return result;
  5265. }
  5266. function compileMap(/* lists... */) {
  5267. var result = {
  5268. scalar: {},
  5269. sequence: {},
  5270. mapping: {},
  5271. fallback: {},
  5272. multi: {
  5273. scalar: [],
  5274. sequence: [],
  5275. mapping: [],
  5276. fallback: []
  5277. }
  5278. }, index, length;
  5279. function collectType(type) {
  5280. if (type.multi) {
  5281. result.multi[type.kind].push(type);
  5282. result.multi['fallback'].push(type);
  5283. } else {
  5284. result[type.kind][type.tag] = result['fallback'][type.tag] = type;
  5285. }
  5286. }
  5287. for (index = 0, length = arguments.length; index < length; index += 1) {
  5288. arguments[index].forEach(collectType);
  5289. }
  5290. return result;
  5291. }
  5292. function Schema$1(definition) {
  5293. return this.extend(definition);
  5294. }
  5295. Schema$1.prototype.extend = function extend(definition) {
  5296. var implicit = [];
  5297. var explicit = [];
  5298. if (definition instanceof type) {
  5299. // Schema.extend(type)
  5300. explicit.push(definition);
  5301. } else if (Array.isArray(definition)) {
  5302. // Schema.extend([ type1, type2, ... ])
  5303. explicit = explicit.concat(definition);
  5304. } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
  5305. // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
  5306. if (definition.implicit) implicit = implicit.concat(definition.implicit);
  5307. if (definition.explicit) explicit = explicit.concat(definition.explicit);
  5308. } else {
  5309. throw new exception('Schema.extend argument should be a Type, [ Type ], ' +
  5310. 'or a schema definition ({ implicit: [...], explicit: [...] })');
  5311. }
  5312. implicit.forEach(function (type$1) {
  5313. if (!(type$1 instanceof type)) {
  5314. throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  5315. }
  5316. if (type$1.loadKind && type$1.loadKind !== 'scalar') {
  5317. throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
  5318. }
  5319. if (type$1.multi) {
  5320. throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
  5321. }
  5322. });
  5323. explicit.forEach(function (type$1) {
  5324. if (!(type$1 instanceof type)) {
  5325. throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  5326. }
  5327. });
  5328. var result = Object.create(Schema$1.prototype);
  5329. result.implicit = (this.implicit || []).concat(implicit);
  5330. result.explicit = (this.explicit || []).concat(explicit);
  5331. result.compiledImplicit = compileList(result, 'implicit');
  5332. result.compiledExplicit = compileList(result, 'explicit');
  5333. result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
  5334. return result;
  5335. };
  5336. var schema = Schema$1;
  5337. var str = new type('tag:yaml.org,2002:str', {
  5338. kind: 'scalar',
  5339. construct: function (data) { return data !== null ? data : ''; }
  5340. });
  5341. var seq = new type('tag:yaml.org,2002:seq', {
  5342. kind: 'sequence',
  5343. construct: function (data) { return data !== null ? data : []; }
  5344. });
  5345. var map = new type('tag:yaml.org,2002:map', {
  5346. kind: 'mapping',
  5347. construct: function (data) { return data !== null ? data : {}; }
  5348. });
  5349. var failsafe = new schema({
  5350. explicit: [
  5351. str,
  5352. seq,
  5353. map
  5354. ]
  5355. });
  5356. function resolveYamlNull(data) {
  5357. if (data === null) return true;
  5358. var max = data.length;
  5359. return (max === 1 && data === '~') ||
  5360. (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
  5361. }
  5362. function constructYamlNull() {
  5363. return null;
  5364. }
  5365. function isNull(object) {
  5366. return object === null;
  5367. }
  5368. var _null = new type('tag:yaml.org,2002:null', {
  5369. kind: 'scalar',
  5370. resolve: resolveYamlNull,
  5371. construct: constructYamlNull,
  5372. predicate: isNull,
  5373. represent: {
  5374. canonical: function () { return '~'; },
  5375. lowercase: function () { return 'null'; },
  5376. uppercase: function () { return 'NULL'; },
  5377. camelcase: function () { return 'Null'; },
  5378. empty: function () { return ''; }
  5379. },
  5380. defaultStyle: 'lowercase'
  5381. });
  5382. function resolveYamlBoolean(data) {
  5383. if (data === null) return false;
  5384. var max = data.length;
  5385. return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
  5386. (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
  5387. }
  5388. function constructYamlBoolean(data) {
  5389. return data === 'true' ||
  5390. data === 'True' ||
  5391. data === 'TRUE';
  5392. }
  5393. function isBoolean(object) {
  5394. return Object.prototype.toString.call(object) === '[object Boolean]';
  5395. }
  5396. var bool = new type('tag:yaml.org,2002:bool', {
  5397. kind: 'scalar',
  5398. resolve: resolveYamlBoolean,
  5399. construct: constructYamlBoolean,
  5400. predicate: isBoolean,
  5401. represent: {
  5402. lowercase: function (object) { return object ? 'true' : 'false'; },
  5403. uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
  5404. camelcase: function (object) { return object ? 'True' : 'False'; }
  5405. },
  5406. defaultStyle: 'lowercase'
  5407. });
  5408. function isHexCode(c) {
  5409. return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
  5410. ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
  5411. ((0x61/* a */ <= c) && (c <= 0x66/* f */));
  5412. }
  5413. function isOctCode(c) {
  5414. return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
  5415. }
  5416. function isDecCode(c) {
  5417. return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
  5418. }
  5419. function resolveYamlInteger(data) {
  5420. if (data === null) return false;
  5421. var max = data.length,
  5422. index = 0,
  5423. hasDigits = false,
  5424. ch;
  5425. if (!max) return false;
  5426. ch = data[index];
  5427. // sign
  5428. if (ch === '-' || ch === '+') {
  5429. ch = data[++index];
  5430. }
  5431. if (ch === '0') {
  5432. // 0
  5433. if (index + 1 === max) return true;
  5434. ch = data[++index];
  5435. // base 2, base 8, base 16
  5436. if (ch === 'b') {
  5437. // base 2
  5438. index++;
  5439. for (; index < max; index++) {
  5440. ch = data[index];
  5441. if (ch === '_') continue;
  5442. if (ch !== '0' && ch !== '1') return false;
  5443. hasDigits = true;
  5444. }
  5445. return hasDigits && ch !== '_';
  5446. }
  5447. if (ch === 'x') {
  5448. // base 16
  5449. index++;
  5450. for (; index < max; index++) {
  5451. ch = data[index];
  5452. if (ch === '_') continue;
  5453. if (!isHexCode(data.charCodeAt(index))) return false;
  5454. hasDigits = true;
  5455. }
  5456. return hasDigits && ch !== '_';
  5457. }
  5458. if (ch === 'o') {
  5459. // base 8
  5460. index++;
  5461. for (; index < max; index++) {
  5462. ch = data[index];
  5463. if (ch === '_') continue;
  5464. if (!isOctCode(data.charCodeAt(index))) return false;
  5465. hasDigits = true;
  5466. }
  5467. return hasDigits && ch !== '_';
  5468. }
  5469. }
  5470. // base 10 (except 0)
  5471. // value should not start with `_`;
  5472. if (ch === '_') return false;
  5473. for (; index < max; index++) {
  5474. ch = data[index];
  5475. if (ch === '_') continue;
  5476. if (!isDecCode(data.charCodeAt(index))) {
  5477. return false;
  5478. }
  5479. hasDigits = true;
  5480. }
  5481. // Should have digits and should not end with `_`
  5482. if (!hasDigits || ch === '_') return false;
  5483. return true;
  5484. }
  5485. function constructYamlInteger(data) {
  5486. var value = data, sign = 1, ch;
  5487. if (value.indexOf('_') !== -1) {
  5488. value = value.replace(/_/g, '');
  5489. }
  5490. ch = value[0];
  5491. if (ch === '-' || ch === '+') {
  5492. if (ch === '-') sign = -1;
  5493. value = value.slice(1);
  5494. ch = value[0];
  5495. }
  5496. if (value === '0') return 0;
  5497. if (ch === '0') {
  5498. if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
  5499. if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
  5500. if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
  5501. }
  5502. return sign * parseInt(value, 10);
  5503. }
  5504. function isInteger(object) {
  5505. return (Object.prototype.toString.call(object)) === '[object Number]' &&
  5506. (object % 1 === 0 && !common.isNegativeZero(object));
  5507. }
  5508. var int = new type('tag:yaml.org,2002:int', {
  5509. kind: 'scalar',
  5510. resolve: resolveYamlInteger,
  5511. construct: constructYamlInteger,
  5512. predicate: isInteger,
  5513. represent: {
  5514. binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
  5515. octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },
  5516. decimal: function (obj) { return obj.toString(10); },
  5517. /* eslint-disable max-len */
  5518. hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
  5519. },
  5520. defaultStyle: 'decimal',
  5521. styleAliases: {
  5522. binary: [ 2, 'bin' ],
  5523. octal: [ 8, 'oct' ],
  5524. decimal: [ 10, 'dec' ],
  5525. hexadecimal: [ 16, 'hex' ]
  5526. }
  5527. });
  5528. var YAML_FLOAT_PATTERN = new RegExp(
  5529. // 2.5e4, 2.5 and integers
  5530. '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
  5531. // .2e4, .2
  5532. // special case, seems not from spec
  5533. '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
  5534. // .inf
  5535. '|[-+]?\\.(?:inf|Inf|INF)' +
  5536. // .nan
  5537. '|\\.(?:nan|NaN|NAN))$');
  5538. function resolveYamlFloat(data) {
  5539. if (data === null) return false;
  5540. if (!YAML_FLOAT_PATTERN.test(data) ||
  5541. // Quick hack to not allow integers end with `_`
  5542. // Probably should update regexp & check speed
  5543. data[data.length - 1] === '_') {
  5544. return false;
  5545. }
  5546. return true;
  5547. }
  5548. function constructYamlFloat(data) {
  5549. var value, sign;
  5550. value = data.replace(/_/g, '').toLowerCase();
  5551. sign = value[0] === '-' ? -1 : 1;
  5552. if ('+-'.indexOf(value[0]) >= 0) {
  5553. value = value.slice(1);
  5554. }
  5555. if (value === '.inf') {
  5556. return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
  5557. } else if (value === '.nan') {
  5558. return NaN;
  5559. }
  5560. return sign * parseFloat(value, 10);
  5561. }
  5562. var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
  5563. function representYamlFloat(object, style) {
  5564. var res;
  5565. if (isNaN(object)) {
  5566. switch (style) {
  5567. case 'lowercase': return '.nan';
  5568. case 'uppercase': return '.NAN';
  5569. case 'camelcase': return '.NaN';
  5570. }
  5571. } else if (Number.POSITIVE_INFINITY === object) {
  5572. switch (style) {
  5573. case 'lowercase': return '.inf';
  5574. case 'uppercase': return '.INF';
  5575. case 'camelcase': return '.Inf';
  5576. }
  5577. } else if (Number.NEGATIVE_INFINITY === object) {
  5578. switch (style) {
  5579. case 'lowercase': return '-.inf';
  5580. case 'uppercase': return '-.INF';
  5581. case 'camelcase': return '-.Inf';
  5582. }
  5583. } else if (common.isNegativeZero(object)) {
  5584. return '-0.0';
  5585. }
  5586. res = object.toString(10);
  5587. // JS stringifier can build scientific format without dots: 5e-100,
  5588. // while YAML requres dot: 5.e-100. Fix it with simple hack
  5589. return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
  5590. }
  5591. function isFloat(object) {
  5592. return (Object.prototype.toString.call(object) === '[object Number]') &&
  5593. (object % 1 !== 0 || common.isNegativeZero(object));
  5594. }
  5595. var float = new type('tag:yaml.org,2002:float', {
  5596. kind: 'scalar',
  5597. resolve: resolveYamlFloat,
  5598. construct: constructYamlFloat,
  5599. predicate: isFloat,
  5600. represent: representYamlFloat,
  5601. defaultStyle: 'lowercase'
  5602. });
  5603. var json = failsafe.extend({
  5604. implicit: [
  5605. _null,
  5606. bool,
  5607. int,
  5608. float
  5609. ]
  5610. });
  5611. var core = json;
  5612. var YAML_DATE_REGEXP = new RegExp(
  5613. '^([0-9][0-9][0-9][0-9])' + // [1] year
  5614. '-([0-9][0-9])' + // [2] month
  5615. '-([0-9][0-9])$'); // [3] day
  5616. var YAML_TIMESTAMP_REGEXP = new RegExp(
  5617. '^([0-9][0-9][0-9][0-9])' + // [1] year
  5618. '-([0-9][0-9]?)' + // [2] month
  5619. '-([0-9][0-9]?)' + // [3] day
  5620. '(?:[Tt]|[ \\t]+)' + // ...
  5621. '([0-9][0-9]?)' + // [4] hour
  5622. ':([0-9][0-9])' + // [5] minute
  5623. ':([0-9][0-9])' + // [6] second
  5624. '(?:\\.([0-9]*))?' + // [7] fraction
  5625. '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
  5626. '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
  5627. function resolveYamlTimestamp(data) {
  5628. if (data === null) return false;
  5629. if (YAML_DATE_REGEXP.exec(data) !== null) return true;
  5630. if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
  5631. return false;
  5632. }
  5633. function constructYamlTimestamp(data) {
  5634. var match, year, month, day, hour, minute, second, fraction = 0,
  5635. delta = null, tz_hour, tz_minute, date;
  5636. match = YAML_DATE_REGEXP.exec(data);
  5637. if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
  5638. if (match === null) throw new Error('Date resolve error');
  5639. // match: [1] year [2] month [3] day
  5640. year = +(match[1]);
  5641. month = +(match[2]) - 1; // JS month starts with 0
  5642. day = +(match[3]);
  5643. if (!match[4]) { // no hour
  5644. return new Date(Date.UTC(year, month, day));
  5645. }
  5646. // match: [4] hour [5] minute [6] second [7] fraction
  5647. hour = +(match[4]);
  5648. minute = +(match[5]);
  5649. second = +(match[6]);
  5650. if (match[7]) {
  5651. fraction = match[7].slice(0, 3);
  5652. while (fraction.length < 3) { // milli-seconds
  5653. fraction += '0';
  5654. }
  5655. fraction = +fraction;
  5656. }
  5657. // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
  5658. if (match[9]) {
  5659. tz_hour = +(match[10]);
  5660. tz_minute = +(match[11] || 0);
  5661. delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
  5662. if (match[9] === '-') delta = -delta;
  5663. }
  5664. date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
  5665. if (delta) date.setTime(date.getTime() - delta);
  5666. return date;
  5667. }
  5668. function representYamlTimestamp(object /*, style*/) {
  5669. return object.toISOString();
  5670. }
  5671. var timestamp = new type('tag:yaml.org,2002:timestamp', {
  5672. kind: 'scalar',
  5673. resolve: resolveYamlTimestamp,
  5674. construct: constructYamlTimestamp,
  5675. instanceOf: Date,
  5676. represent: representYamlTimestamp
  5677. });
  5678. function resolveYamlMerge(data) {
  5679. return data === '<<' || data === null;
  5680. }
  5681. var merge = new type('tag:yaml.org,2002:merge', {
  5682. kind: 'scalar',
  5683. resolve: resolveYamlMerge
  5684. });
  5685. /*eslint-disable no-bitwise*/
  5686. // [ 64, 65, 66 ] -> [ padding, CR, LF ]
  5687. var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
  5688. function resolveYamlBinary(data) {
  5689. if (data === null) return false;
  5690. var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
  5691. // Convert one by one.
  5692. for (idx = 0; idx < max; idx++) {
  5693. code = map.indexOf(data.charAt(idx));
  5694. // Skip CR/LF
  5695. if (code > 64) continue;
  5696. // Fail on illegal characters
  5697. if (code < 0) return false;
  5698. bitlen += 6;
  5699. }
  5700. // If there are any bits left, source was corrupted
  5701. return (bitlen % 8) === 0;
  5702. }
  5703. function constructYamlBinary(data) {
  5704. var idx, tailbits,
  5705. input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
  5706. max = input.length,
  5707. map = BASE64_MAP,
  5708. bits = 0,
  5709. result = [];
  5710. // Collect by 6*4 bits (3 bytes)
  5711. for (idx = 0; idx < max; idx++) {
  5712. if ((idx % 4 === 0) && idx) {
  5713. result.push((bits >> 16) & 0xFF);
  5714. result.push((bits >> 8) & 0xFF);
  5715. result.push(bits & 0xFF);
  5716. }
  5717. bits = (bits << 6) | map.indexOf(input.charAt(idx));
  5718. }
  5719. // Dump tail
  5720. tailbits = (max % 4) * 6;
  5721. if (tailbits === 0) {
  5722. result.push((bits >> 16) & 0xFF);
  5723. result.push((bits >> 8) & 0xFF);
  5724. result.push(bits & 0xFF);
  5725. } else if (tailbits === 18) {
  5726. result.push((bits >> 10) & 0xFF);
  5727. result.push((bits >> 2) & 0xFF);
  5728. } else if (tailbits === 12) {
  5729. result.push((bits >> 4) & 0xFF);
  5730. }
  5731. return new Uint8Array(result);
  5732. }
  5733. function representYamlBinary(object /*, style*/) {
  5734. var result = '', bits = 0, idx, tail,
  5735. max = object.length,
  5736. map = BASE64_MAP;
  5737. // Convert every three bytes to 4 ASCII characters.
  5738. for (idx = 0; idx < max; idx++) {
  5739. if ((idx % 3 === 0) && idx) {
  5740. result += map[(bits >> 18) & 0x3F];
  5741. result += map[(bits >> 12) & 0x3F];
  5742. result += map[(bits >> 6) & 0x3F];
  5743. result += map[bits & 0x3F];
  5744. }
  5745. bits = (bits << 8) + object[idx];
  5746. }
  5747. // Dump tail
  5748. tail = max % 3;
  5749. if (tail === 0) {
  5750. result += map[(bits >> 18) & 0x3F];
  5751. result += map[(bits >> 12) & 0x3F];
  5752. result += map[(bits >> 6) & 0x3F];
  5753. result += map[bits & 0x3F];
  5754. } else if (tail === 2) {
  5755. result += map[(bits >> 10) & 0x3F];
  5756. result += map[(bits >> 4) & 0x3F];
  5757. result += map[(bits << 2) & 0x3F];
  5758. result += map[64];
  5759. } else if (tail === 1) {
  5760. result += map[(bits >> 2) & 0x3F];
  5761. result += map[(bits << 4) & 0x3F];
  5762. result += map[64];
  5763. result += map[64];
  5764. }
  5765. return result;
  5766. }
  5767. function isBinary(obj) {
  5768. return Object.prototype.toString.call(obj) === '[object Uint8Array]';
  5769. }
  5770. var binary = new type('tag:yaml.org,2002:binary', {
  5771. kind: 'scalar',
  5772. resolve: resolveYamlBinary,
  5773. construct: constructYamlBinary,
  5774. predicate: isBinary,
  5775. represent: representYamlBinary
  5776. });
  5777. var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  5778. var _toString$2 = Object.prototype.toString;
  5779. function resolveYamlOmap(data) {
  5780. if (data === null) return true;
  5781. var objectKeys = [], index, length, pair, pairKey, pairHasKey,
  5782. object = data;
  5783. for (index = 0, length = object.length; index < length; index += 1) {
  5784. pair = object[index];
  5785. pairHasKey = false;
  5786. if (_toString$2.call(pair) !== '[object Object]') return false;
  5787. for (pairKey in pair) {
  5788. if (_hasOwnProperty$3.call(pair, pairKey)) {
  5789. if (!pairHasKey) pairHasKey = true;
  5790. else return false;
  5791. }
  5792. }
  5793. if (!pairHasKey) return false;
  5794. if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
  5795. else return false;
  5796. }
  5797. return true;
  5798. }
  5799. function constructYamlOmap(data) {
  5800. return data !== null ? data : [];
  5801. }
  5802. var omap = new type('tag:yaml.org,2002:omap', {
  5803. kind: 'sequence',
  5804. resolve: resolveYamlOmap,
  5805. construct: constructYamlOmap
  5806. });
  5807. var _toString$1 = Object.prototype.toString;
  5808. function resolveYamlPairs(data) {
  5809. if (data === null) return true;
  5810. var index, length, pair, keys, result,
  5811. object = data;
  5812. result = new Array(object.length);
  5813. for (index = 0, length = object.length; index < length; index += 1) {
  5814. pair = object[index];
  5815. if (_toString$1.call(pair) !== '[object Object]') return false;
  5816. keys = Object.keys(pair);
  5817. if (keys.length !== 1) return false;
  5818. result[index] = [ keys[0], pair[keys[0]] ];
  5819. }
  5820. return true;
  5821. }
  5822. function constructYamlPairs(data) {
  5823. if (data === null) return [];
  5824. var index, length, pair, keys, result,
  5825. object = data;
  5826. result = new Array(object.length);
  5827. for (index = 0, length = object.length; index < length; index += 1) {
  5828. pair = object[index];
  5829. keys = Object.keys(pair);
  5830. result[index] = [ keys[0], pair[keys[0]] ];
  5831. }
  5832. return result;
  5833. }
  5834. var pairs = new type('tag:yaml.org,2002:pairs', {
  5835. kind: 'sequence',
  5836. resolve: resolveYamlPairs,
  5837. construct: constructYamlPairs
  5838. });
  5839. var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  5840. function resolveYamlSet(data) {
  5841. if (data === null) return true;
  5842. var key, object = data;
  5843. for (key in object) {
  5844. if (_hasOwnProperty$2.call(object, key)) {
  5845. if (object[key] !== null) return false;
  5846. }
  5847. }
  5848. return true;
  5849. }
  5850. function constructYamlSet(data) {
  5851. return data !== null ? data : {};
  5852. }
  5853. var set = new type('tag:yaml.org,2002:set', {
  5854. kind: 'mapping',
  5855. resolve: resolveYamlSet,
  5856. construct: constructYamlSet
  5857. });
  5858. var _default = core.extend({
  5859. implicit: [
  5860. timestamp,
  5861. merge
  5862. ],
  5863. explicit: [
  5864. binary,
  5865. omap,
  5866. pairs,
  5867. set
  5868. ]
  5869. });
  5870. /*eslint-disable max-len,no-use-before-define*/
  5871. var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  5872. var CONTEXT_FLOW_IN = 1;
  5873. var CONTEXT_FLOW_OUT = 2;
  5874. var CONTEXT_BLOCK_IN = 3;
  5875. var CONTEXT_BLOCK_OUT = 4;
  5876. var CHOMPING_CLIP = 1;
  5877. var CHOMPING_STRIP = 2;
  5878. var CHOMPING_KEEP = 3;
  5879. var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  5880. var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
  5881. var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
  5882. var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
  5883. var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
  5884. function _class(obj) { return Object.prototype.toString.call(obj); }
  5885. function is_EOL(c) {
  5886. return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
  5887. }
  5888. function is_WHITE_SPACE(c) {
  5889. return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
  5890. }
  5891. function is_WS_OR_EOL(c) {
  5892. return (c === 0x09/* Tab */) ||
  5893. (c === 0x20/* Space */) ||
  5894. (c === 0x0A/* LF */) ||
  5895. (c === 0x0D/* CR */);
  5896. }
  5897. function is_FLOW_INDICATOR(c) {
  5898. return c === 0x2C/* , */ ||
  5899. c === 0x5B/* [ */ ||
  5900. c === 0x5D/* ] */ ||
  5901. c === 0x7B/* { */ ||
  5902. c === 0x7D/* } */;
  5903. }
  5904. function fromHexCode(c) {
  5905. var lc;
  5906. if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
  5907. return c - 0x30;
  5908. }
  5909. /*eslint-disable no-bitwise*/
  5910. lc = c | 0x20;
  5911. if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
  5912. return lc - 0x61 + 10;
  5913. }
  5914. return -1;
  5915. }
  5916. function escapedHexLen(c) {
  5917. if (c === 0x78/* x */) { return 2; }
  5918. if (c === 0x75/* u */) { return 4; }
  5919. if (c === 0x55/* U */) { return 8; }
  5920. return 0;
  5921. }
  5922. function fromDecimalCode(c) {
  5923. if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
  5924. return c - 0x30;
  5925. }
  5926. return -1;
  5927. }
  5928. function simpleEscapeSequence(c) {
  5929. /* eslint-disable indent */
  5930. return (c === 0x30/* 0 */) ? '\x00' :
  5931. (c === 0x61/* a */) ? '\x07' :
  5932. (c === 0x62/* b */) ? '\x08' :
  5933. (c === 0x74/* t */) ? '\x09' :
  5934. (c === 0x09/* Tab */) ? '\x09' :
  5935. (c === 0x6E/* n */) ? '\x0A' :
  5936. (c === 0x76/* v */) ? '\x0B' :
  5937. (c === 0x66/* f */) ? '\x0C' :
  5938. (c === 0x72/* r */) ? '\x0D' :
  5939. (c === 0x65/* e */) ? '\x1B' :
  5940. (c === 0x20/* Space */) ? ' ' :
  5941. (c === 0x22/* " */) ? '\x22' :
  5942. (c === 0x2F/* / */) ? '/' :
  5943. (c === 0x5C/* \ */) ? '\x5C' :
  5944. (c === 0x4E/* N */) ? '\x85' :
  5945. (c === 0x5F/* _ */) ? '\xA0' :
  5946. (c === 0x4C/* L */) ? '\u2028' :
  5947. (c === 0x50/* P */) ? '\u2029' : '';
  5948. }
  5949. function charFromCodepoint(c) {
  5950. if (c <= 0xFFFF) {
  5951. return String.fromCharCode(c);
  5952. }
  5953. // Encode UTF-16 surrogate pair
  5954. // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
  5955. return String.fromCharCode(
  5956. ((c - 0x010000) >> 10) + 0xD800,
  5957. ((c - 0x010000) & 0x03FF) + 0xDC00
  5958. );
  5959. }
  5960. var simpleEscapeCheck = new Array(256); // integer, for fast access
  5961. var simpleEscapeMap = new Array(256);
  5962. for (var i = 0; i < 256; i++) {
  5963. simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
  5964. simpleEscapeMap[i] = simpleEscapeSequence(i);
  5965. }
  5966. function State$1(input, options) {
  5967. this.input = input;
  5968. this.filename = options['filename'] || null;
  5969. this.schema = options['schema'] || _default;
  5970. this.onWarning = options['onWarning'] || null;
  5971. // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
  5972. // if such documents have no explicit %YAML directive
  5973. this.legacy = options['legacy'] || false;
  5974. this.json = options['json'] || false;
  5975. this.listener = options['listener'] || null;
  5976. this.implicitTypes = this.schema.compiledImplicit;
  5977. this.typeMap = this.schema.compiledTypeMap;
  5978. this.length = input.length;
  5979. this.position = 0;
  5980. this.line = 0;
  5981. this.lineStart = 0;
  5982. this.lineIndent = 0;
  5983. // position of first leading tab in the current line,
  5984. // used to make sure there are no tabs in the indentation
  5985. this.firstTabInLine = -1;
  5986. this.documents = [];
  5987. /*
  5988. this.version;
  5989. this.checkLineBreaks;
  5990. this.tagMap;
  5991. this.anchorMap;
  5992. this.tag;
  5993. this.anchor;
  5994. this.kind;
  5995. this.result;*/
  5996. }
  5997. function generateError(state, message) {
  5998. var mark = {
  5999. name: state.filename,
  6000. buffer: state.input.slice(0, -1), // omit trailing \0
  6001. position: state.position,
  6002. line: state.line,
  6003. column: state.position - state.lineStart
  6004. };
  6005. mark.snippet = snippet(mark);
  6006. return new exception(message, mark);
  6007. }
  6008. function throwError(state, message) {
  6009. throw generateError(state, message);
  6010. }
  6011. function throwWarning(state, message) {
  6012. if (state.onWarning) {
  6013. state.onWarning.call(null, generateError(state, message));
  6014. }
  6015. }
  6016. var directiveHandlers = {
  6017. YAML: function handleYamlDirective(state, name, args) {
  6018. var match, major, minor;
  6019. if (state.version !== null) {
  6020. throwError(state, 'duplication of %YAML directive');
  6021. }
  6022. if (args.length !== 1) {
  6023. throwError(state, 'YAML directive accepts exactly one argument');
  6024. }
  6025. match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
  6026. if (match === null) {
  6027. throwError(state, 'ill-formed argument of the YAML directive');
  6028. }
  6029. major = parseInt(match[1], 10);
  6030. minor = parseInt(match[2], 10);
  6031. if (major !== 1) {
  6032. throwError(state, 'unacceptable YAML version of the document');
  6033. }
  6034. state.version = args[0];
  6035. state.checkLineBreaks = (minor < 2);
  6036. if (minor !== 1 && minor !== 2) {
  6037. throwWarning(state, 'unsupported YAML version of the document');
  6038. }
  6039. },
  6040. TAG: function handleTagDirective(state, name, args) {
  6041. var handle, prefix;
  6042. if (args.length !== 2) {
  6043. throwError(state, 'TAG directive accepts exactly two arguments');
  6044. }
  6045. handle = args[0];
  6046. prefix = args[1];
  6047. if (!PATTERN_TAG_HANDLE.test(handle)) {
  6048. throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
  6049. }
  6050. if (_hasOwnProperty$1.call(state.tagMap, handle)) {
  6051. throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
  6052. }
  6053. if (!PATTERN_TAG_URI.test(prefix)) {
  6054. throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
  6055. }
  6056. try {
  6057. prefix = decodeURIComponent(prefix);
  6058. } catch (err) {
  6059. throwError(state, 'tag prefix is malformed: ' + prefix);
  6060. }
  6061. state.tagMap[handle] = prefix;
  6062. }
  6063. };
  6064. function captureSegment(state, start, end, checkJson) {
  6065. var _position, _length, _character, _result;
  6066. if (start < end) {
  6067. _result = state.input.slice(start, end);
  6068. if (checkJson) {
  6069. for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
  6070. _character = _result.charCodeAt(_position);
  6071. if (!(_character === 0x09 ||
  6072. (0x20 <= _character && _character <= 0x10FFFF))) {
  6073. throwError(state, 'expected valid JSON character');
  6074. }
  6075. }
  6076. } else if (PATTERN_NON_PRINTABLE.test(_result)) {
  6077. throwError(state, 'the stream contains non-printable characters');
  6078. }
  6079. state.result += _result;
  6080. }
  6081. }
  6082. function mergeMappings(state, destination, source, overridableKeys) {
  6083. var sourceKeys, key, index, quantity;
  6084. if (!common.isObject(source)) {
  6085. throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
  6086. }
  6087. sourceKeys = Object.keys(source);
  6088. for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
  6089. key = sourceKeys[index];
  6090. if (!_hasOwnProperty$1.call(destination, key)) {
  6091. destination[key] = source[key];
  6092. overridableKeys[key] = true;
  6093. }
  6094. }
  6095. }
  6096. function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
  6097. startLine, startLineStart, startPos) {
  6098. var index, quantity;
  6099. // The output is a plain object here, so keys can only be strings.
  6100. // We need to convert keyNode to a string, but doing so can hang the process
  6101. // (deeply nested arrays that explode exponentially using aliases).
  6102. if (Array.isArray(keyNode)) {
  6103. keyNode = Array.prototype.slice.call(keyNode);
  6104. for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
  6105. if (Array.isArray(keyNode[index])) {
  6106. throwError(state, 'nested arrays are not supported inside keys');
  6107. }
  6108. if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
  6109. keyNode[index] = '[object Object]';
  6110. }
  6111. }
  6112. }
  6113. // Avoid code execution in load() via toString property
  6114. // (still use its own toString for arrays, timestamps,
  6115. // and whatever user schema extensions happen to have @@toStringTag)
  6116. if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
  6117. keyNode = '[object Object]';
  6118. }
  6119. keyNode = String(keyNode);
  6120. if (_result === null) {
  6121. _result = {};
  6122. }
  6123. if (keyTag === 'tag:yaml.org,2002:merge') {
  6124. if (Array.isArray(valueNode)) {
  6125. for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
  6126. mergeMappings(state, _result, valueNode[index], overridableKeys);
  6127. }
  6128. } else {
  6129. mergeMappings(state, _result, valueNode, overridableKeys);
  6130. }
  6131. } else {
  6132. if (!state.json &&
  6133. !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
  6134. _hasOwnProperty$1.call(_result, keyNode)) {
  6135. state.line = startLine || state.line;
  6136. state.lineStart = startLineStart || state.lineStart;
  6137. state.position = startPos || state.position;
  6138. throwError(state, 'duplicated mapping key');
  6139. }
  6140. // used for this specific key only because Object.defineProperty is slow
  6141. if (keyNode === '__proto__') {
  6142. Object.defineProperty(_result, keyNode, {
  6143. configurable: true,
  6144. enumerable: true,
  6145. writable: true,
  6146. value: valueNode
  6147. });
  6148. } else {
  6149. _result[keyNode] = valueNode;
  6150. }
  6151. delete overridableKeys[keyNode];
  6152. }
  6153. return _result;
  6154. }
  6155. function readLineBreak(state) {
  6156. var ch;
  6157. ch = state.input.charCodeAt(state.position);
  6158. if (ch === 0x0A/* LF */) {
  6159. state.position++;
  6160. } else if (ch === 0x0D/* CR */) {
  6161. state.position++;
  6162. if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
  6163. state.position++;
  6164. }
  6165. } else {
  6166. throwError(state, 'a line break is expected');
  6167. }
  6168. state.line += 1;
  6169. state.lineStart = state.position;
  6170. state.firstTabInLine = -1;
  6171. }
  6172. function skipSeparationSpace(state, allowComments, checkIndent) {
  6173. var lineBreaks = 0,
  6174. ch = state.input.charCodeAt(state.position);
  6175. while (ch !== 0) {
  6176. while (is_WHITE_SPACE(ch)) {
  6177. if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
  6178. state.firstTabInLine = state.position;
  6179. }
  6180. ch = state.input.charCodeAt(++state.position);
  6181. }
  6182. if (allowComments && ch === 0x23/* # */) {
  6183. do {
  6184. ch = state.input.charCodeAt(++state.position);
  6185. } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
  6186. }
  6187. if (is_EOL(ch)) {
  6188. readLineBreak(state);
  6189. ch = state.input.charCodeAt(state.position);
  6190. lineBreaks++;
  6191. state.lineIndent = 0;
  6192. while (ch === 0x20/* Space */) {
  6193. state.lineIndent++;
  6194. ch = state.input.charCodeAt(++state.position);
  6195. }
  6196. } else {
  6197. break;
  6198. }
  6199. }
  6200. if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
  6201. throwWarning(state, 'deficient indentation');
  6202. }
  6203. return lineBreaks;
  6204. }
  6205. function testDocumentSeparator(state) {
  6206. var _position = state.position,
  6207. ch;
  6208. ch = state.input.charCodeAt(_position);
  6209. // Condition state.position === state.lineStart is tested
  6210. // in parent on each call, for efficiency. No needs to test here again.
  6211. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
  6212. ch === state.input.charCodeAt(_position + 1) &&
  6213. ch === state.input.charCodeAt(_position + 2)) {
  6214. _position += 3;
  6215. ch = state.input.charCodeAt(_position);
  6216. if (ch === 0 || is_WS_OR_EOL(ch)) {
  6217. return true;
  6218. }
  6219. }
  6220. return false;
  6221. }
  6222. function writeFoldedLines(state, count) {
  6223. if (count === 1) {
  6224. state.result += ' ';
  6225. } else if (count > 1) {
  6226. state.result += common.repeat('\n', count - 1);
  6227. }
  6228. }
  6229. function readPlainScalar(state, nodeIndent, withinFlowCollection) {
  6230. var preceding,
  6231. following,
  6232. captureStart,
  6233. captureEnd,
  6234. hasPendingContent,
  6235. _line,
  6236. _lineStart,
  6237. _lineIndent,
  6238. _kind = state.kind,
  6239. _result = state.result,
  6240. ch;
  6241. ch = state.input.charCodeAt(state.position);
  6242. if (is_WS_OR_EOL(ch) ||
  6243. is_FLOW_INDICATOR(ch) ||
  6244. ch === 0x23/* # */ ||
  6245. ch === 0x26/* & */ ||
  6246. ch === 0x2A/* * */ ||
  6247. ch === 0x21/* ! */ ||
  6248. ch === 0x7C/* | */ ||
  6249. ch === 0x3E/* > */ ||
  6250. ch === 0x27/* ' */ ||
  6251. ch === 0x22/* " */ ||
  6252. ch === 0x25/* % */ ||
  6253. ch === 0x40/* @ */ ||
  6254. ch === 0x60/* ` */) {
  6255. return false;
  6256. }
  6257. if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
  6258. following = state.input.charCodeAt(state.position + 1);
  6259. if (is_WS_OR_EOL(following) ||
  6260. withinFlowCollection && is_FLOW_INDICATOR(following)) {
  6261. return false;
  6262. }
  6263. }
  6264. state.kind = 'scalar';
  6265. state.result = '';
  6266. captureStart = captureEnd = state.position;
  6267. hasPendingContent = false;
  6268. while (ch !== 0) {
  6269. if (ch === 0x3A/* : */) {
  6270. following = state.input.charCodeAt(state.position + 1);
  6271. if (is_WS_OR_EOL(following) ||
  6272. withinFlowCollection && is_FLOW_INDICATOR(following)) {
  6273. break;
  6274. }
  6275. } else if (ch === 0x23/* # */) {
  6276. preceding = state.input.charCodeAt(state.position - 1);
  6277. if (is_WS_OR_EOL(preceding)) {
  6278. break;
  6279. }
  6280. } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
  6281. withinFlowCollection && is_FLOW_INDICATOR(ch)) {
  6282. break;
  6283. } else if (is_EOL(ch)) {
  6284. _line = state.line;
  6285. _lineStart = state.lineStart;
  6286. _lineIndent = state.lineIndent;
  6287. skipSeparationSpace(state, false, -1);
  6288. if (state.lineIndent >= nodeIndent) {
  6289. hasPendingContent = true;
  6290. ch = state.input.charCodeAt(state.position);
  6291. continue;
  6292. } else {
  6293. state.position = captureEnd;
  6294. state.line = _line;
  6295. state.lineStart = _lineStart;
  6296. state.lineIndent = _lineIndent;
  6297. break;
  6298. }
  6299. }
  6300. if (hasPendingContent) {
  6301. captureSegment(state, captureStart, captureEnd, false);
  6302. writeFoldedLines(state, state.line - _line);
  6303. captureStart = captureEnd = state.position;
  6304. hasPendingContent = false;
  6305. }
  6306. if (!is_WHITE_SPACE(ch)) {
  6307. captureEnd = state.position + 1;
  6308. }
  6309. ch = state.input.charCodeAt(++state.position);
  6310. }
  6311. captureSegment(state, captureStart, captureEnd, false);
  6312. if (state.result) {
  6313. return true;
  6314. }
  6315. state.kind = _kind;
  6316. state.result = _result;
  6317. return false;
  6318. }
  6319. function readSingleQuotedScalar(state, nodeIndent) {
  6320. var ch,
  6321. captureStart, captureEnd;
  6322. ch = state.input.charCodeAt(state.position);
  6323. if (ch !== 0x27/* ' */) {
  6324. return false;
  6325. }
  6326. state.kind = 'scalar';
  6327. state.result = '';
  6328. state.position++;
  6329. captureStart = captureEnd = state.position;
  6330. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  6331. if (ch === 0x27/* ' */) {
  6332. captureSegment(state, captureStart, state.position, true);
  6333. ch = state.input.charCodeAt(++state.position);
  6334. if (ch === 0x27/* ' */) {
  6335. captureStart = state.position;
  6336. state.position++;
  6337. captureEnd = state.position;
  6338. } else {
  6339. return true;
  6340. }
  6341. } else if (is_EOL(ch)) {
  6342. captureSegment(state, captureStart, captureEnd, true);
  6343. writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
  6344. captureStart = captureEnd = state.position;
  6345. } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
  6346. throwError(state, 'unexpected end of the document within a single quoted scalar');
  6347. } else {
  6348. state.position++;
  6349. captureEnd = state.position;
  6350. }
  6351. }
  6352. throwError(state, 'unexpected end of the stream within a single quoted scalar');
  6353. }
  6354. function readDoubleQuotedScalar(state, nodeIndent) {
  6355. var captureStart,
  6356. captureEnd,
  6357. hexLength,
  6358. hexResult,
  6359. tmp,
  6360. ch;
  6361. ch = state.input.charCodeAt(state.position);
  6362. if (ch !== 0x22/* " */) {
  6363. return false;
  6364. }
  6365. state.kind = 'scalar';
  6366. state.result = '';
  6367. state.position++;
  6368. captureStart = captureEnd = state.position;
  6369. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  6370. if (ch === 0x22/* " */) {
  6371. captureSegment(state, captureStart, state.position, true);
  6372. state.position++;
  6373. return true;
  6374. } else if (ch === 0x5C/* \ */) {
  6375. captureSegment(state, captureStart, state.position, true);
  6376. ch = state.input.charCodeAt(++state.position);
  6377. if (is_EOL(ch)) {
  6378. skipSeparationSpace(state, false, nodeIndent);
  6379. // TODO: rework to inline fn with no type cast?
  6380. } else if (ch < 256 && simpleEscapeCheck[ch]) {
  6381. state.result += simpleEscapeMap[ch];
  6382. state.position++;
  6383. } else if ((tmp = escapedHexLen(ch)) > 0) {
  6384. hexLength = tmp;
  6385. hexResult = 0;
  6386. for (; hexLength > 0; hexLength--) {
  6387. ch = state.input.charCodeAt(++state.position);
  6388. if ((tmp = fromHexCode(ch)) >= 0) {
  6389. hexResult = (hexResult << 4) + tmp;
  6390. } else {
  6391. throwError(state, 'expected hexadecimal character');
  6392. }
  6393. }
  6394. state.result += charFromCodepoint(hexResult);
  6395. state.position++;
  6396. } else {
  6397. throwError(state, 'unknown escape sequence');
  6398. }
  6399. captureStart = captureEnd = state.position;
  6400. } else if (is_EOL(ch)) {
  6401. captureSegment(state, captureStart, captureEnd, true);
  6402. writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
  6403. captureStart = captureEnd = state.position;
  6404. } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
  6405. throwError(state, 'unexpected end of the document within a double quoted scalar');
  6406. } else {
  6407. state.position++;
  6408. captureEnd = state.position;
  6409. }
  6410. }
  6411. throwError(state, 'unexpected end of the stream within a double quoted scalar');
  6412. }
  6413. function readFlowCollection(state, nodeIndent) {
  6414. var readNext = true,
  6415. _line,
  6416. _lineStart,
  6417. _pos,
  6418. _tag = state.tag,
  6419. _result,
  6420. _anchor = state.anchor,
  6421. following,
  6422. terminator,
  6423. isPair,
  6424. isExplicitPair,
  6425. isMapping,
  6426. overridableKeys = Object.create(null),
  6427. keyNode,
  6428. keyTag,
  6429. valueNode,
  6430. ch;
  6431. ch = state.input.charCodeAt(state.position);
  6432. if (ch === 0x5B/* [ */) {
  6433. terminator = 0x5D;/* ] */
  6434. isMapping = false;
  6435. _result = [];
  6436. } else if (ch === 0x7B/* { */) {
  6437. terminator = 0x7D;/* } */
  6438. isMapping = true;
  6439. _result = {};
  6440. } else {
  6441. return false;
  6442. }
  6443. if (state.anchor !== null) {
  6444. state.anchorMap[state.anchor] = _result;
  6445. }
  6446. ch = state.input.charCodeAt(++state.position);
  6447. while (ch !== 0) {
  6448. skipSeparationSpace(state, true, nodeIndent);
  6449. ch = state.input.charCodeAt(state.position);
  6450. if (ch === terminator) {
  6451. state.position++;
  6452. state.tag = _tag;
  6453. state.anchor = _anchor;
  6454. state.kind = isMapping ? 'mapping' : 'sequence';
  6455. state.result = _result;
  6456. return true;
  6457. } else if (!readNext) {
  6458. throwError(state, 'missed comma between flow collection entries');
  6459. } else if (ch === 0x2C/* , */) {
  6460. // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
  6461. throwError(state, "expected the node content, but found ','");
  6462. }
  6463. keyTag = keyNode = valueNode = null;
  6464. isPair = isExplicitPair = false;
  6465. if (ch === 0x3F/* ? */) {
  6466. following = state.input.charCodeAt(state.position + 1);
  6467. if (is_WS_OR_EOL(following)) {
  6468. isPair = isExplicitPair = true;
  6469. state.position++;
  6470. skipSeparationSpace(state, true, nodeIndent);
  6471. }
  6472. }
  6473. _line = state.line; // Save the current line.
  6474. _lineStart = state.lineStart;
  6475. _pos = state.position;
  6476. composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
  6477. keyTag = state.tag;
  6478. keyNode = state.result;
  6479. skipSeparationSpace(state, true, nodeIndent);
  6480. ch = state.input.charCodeAt(state.position);
  6481. if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
  6482. isPair = true;
  6483. ch = state.input.charCodeAt(++state.position);
  6484. skipSeparationSpace(state, true, nodeIndent);
  6485. composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
  6486. valueNode = state.result;
  6487. }
  6488. if (isMapping) {
  6489. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
  6490. } else if (isPair) {
  6491. _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
  6492. } else {
  6493. _result.push(keyNode);
  6494. }
  6495. skipSeparationSpace(state, true, nodeIndent);
  6496. ch = state.input.charCodeAt(state.position);
  6497. if (ch === 0x2C/* , */) {
  6498. readNext = true;
  6499. ch = state.input.charCodeAt(++state.position);
  6500. } else {
  6501. readNext = false;
  6502. }
  6503. }
  6504. throwError(state, 'unexpected end of the stream within a flow collection');
  6505. }
  6506. function readBlockScalar(state, nodeIndent) {
  6507. var captureStart,
  6508. folding,
  6509. chomping = CHOMPING_CLIP,
  6510. didReadContent = false,
  6511. detectedIndent = false,
  6512. textIndent = nodeIndent,
  6513. emptyLines = 0,
  6514. atMoreIndented = false,
  6515. tmp,
  6516. ch;
  6517. ch = state.input.charCodeAt(state.position);
  6518. if (ch === 0x7C/* | */) {
  6519. folding = false;
  6520. } else if (ch === 0x3E/* > */) {
  6521. folding = true;
  6522. } else {
  6523. return false;
  6524. }
  6525. state.kind = 'scalar';
  6526. state.result = '';
  6527. while (ch !== 0) {
  6528. ch = state.input.charCodeAt(++state.position);
  6529. if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
  6530. if (CHOMPING_CLIP === chomping) {
  6531. chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
  6532. } else {
  6533. throwError(state, 'repeat of a chomping mode identifier');
  6534. }
  6535. } else if ((tmp = fromDecimalCode(ch)) >= 0) {
  6536. if (tmp === 0) {
  6537. throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
  6538. } else if (!detectedIndent) {
  6539. textIndent = nodeIndent + tmp - 1;
  6540. detectedIndent = true;
  6541. } else {
  6542. throwError(state, 'repeat of an indentation width identifier');
  6543. }
  6544. } else {
  6545. break;
  6546. }
  6547. }
  6548. if (is_WHITE_SPACE(ch)) {
  6549. do { ch = state.input.charCodeAt(++state.position); }
  6550. while (is_WHITE_SPACE(ch));
  6551. if (ch === 0x23/* # */) {
  6552. do { ch = state.input.charCodeAt(++state.position); }
  6553. while (!is_EOL(ch) && (ch !== 0));
  6554. }
  6555. }
  6556. while (ch !== 0) {
  6557. readLineBreak(state);
  6558. state.lineIndent = 0;
  6559. ch = state.input.charCodeAt(state.position);
  6560. while ((!detectedIndent || state.lineIndent < textIndent) &&
  6561. (ch === 0x20/* Space */)) {
  6562. state.lineIndent++;
  6563. ch = state.input.charCodeAt(++state.position);
  6564. }
  6565. if (!detectedIndent && state.lineIndent > textIndent) {
  6566. textIndent = state.lineIndent;
  6567. }
  6568. if (is_EOL(ch)) {
  6569. emptyLines++;
  6570. continue;
  6571. }
  6572. // End of the scalar.
  6573. if (state.lineIndent < textIndent) {
  6574. // Perform the chomping.
  6575. if (chomping === CHOMPING_KEEP) {
  6576. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  6577. } else if (chomping === CHOMPING_CLIP) {
  6578. if (didReadContent) { // i.e. only if the scalar is not empty.
  6579. state.result += '\n';
  6580. }
  6581. }
  6582. // Break this `while` cycle and go to the funciton's epilogue.
  6583. break;
  6584. }
  6585. // Folded style: use fancy rules to handle line breaks.
  6586. if (folding) {
  6587. // Lines starting with white space characters (more-indented lines) are not folded.
  6588. if (is_WHITE_SPACE(ch)) {
  6589. atMoreIndented = true;
  6590. // except for the first content line (cf. Example 8.1)
  6591. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  6592. // End of more-indented block.
  6593. } else if (atMoreIndented) {
  6594. atMoreIndented = false;
  6595. state.result += common.repeat('\n', emptyLines + 1);
  6596. // Just one line break - perceive as the same line.
  6597. } else if (emptyLines === 0) {
  6598. if (didReadContent) { // i.e. only if we have already read some scalar content.
  6599. state.result += ' ';
  6600. }
  6601. // Several line breaks - perceive as different lines.
  6602. } else {
  6603. state.result += common.repeat('\n', emptyLines);
  6604. }
  6605. // Literal style: just add exact number of line breaks between content lines.
  6606. } else {
  6607. // Keep all line breaks except the header line break.
  6608. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  6609. }
  6610. didReadContent = true;
  6611. detectedIndent = true;
  6612. emptyLines = 0;
  6613. captureStart = state.position;
  6614. while (!is_EOL(ch) && (ch !== 0)) {
  6615. ch = state.input.charCodeAt(++state.position);
  6616. }
  6617. captureSegment(state, captureStart, state.position, false);
  6618. }
  6619. return true;
  6620. }
  6621. function readBlockSequence(state, nodeIndent) {
  6622. var _line,
  6623. _tag = state.tag,
  6624. _anchor = state.anchor,
  6625. _result = [],
  6626. following,
  6627. detected = false,
  6628. ch;
  6629. // there is a leading tab before this token, so it can't be a block sequence/mapping;
  6630. // it can still be flow sequence/mapping or a scalar
  6631. if (state.firstTabInLine !== -1) return false;
  6632. if (state.anchor !== null) {
  6633. state.anchorMap[state.anchor] = _result;
  6634. }
  6635. ch = state.input.charCodeAt(state.position);
  6636. while (ch !== 0) {
  6637. if (state.firstTabInLine !== -1) {
  6638. state.position = state.firstTabInLine;
  6639. throwError(state, 'tab characters must not be used in indentation');
  6640. }
  6641. if (ch !== 0x2D/* - */) {
  6642. break;
  6643. }
  6644. following = state.input.charCodeAt(state.position + 1);
  6645. if (!is_WS_OR_EOL(following)) {
  6646. break;
  6647. }
  6648. detected = true;
  6649. state.position++;
  6650. if (skipSeparationSpace(state, true, -1)) {
  6651. if (state.lineIndent <= nodeIndent) {
  6652. _result.push(null);
  6653. ch = state.input.charCodeAt(state.position);
  6654. continue;
  6655. }
  6656. }
  6657. _line = state.line;
  6658. composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
  6659. _result.push(state.result);
  6660. skipSeparationSpace(state, true, -1);
  6661. ch = state.input.charCodeAt(state.position);
  6662. if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
  6663. throwError(state, 'bad indentation of a sequence entry');
  6664. } else if (state.lineIndent < nodeIndent) {
  6665. break;
  6666. }
  6667. }
  6668. if (detected) {
  6669. state.tag = _tag;
  6670. state.anchor = _anchor;
  6671. state.kind = 'sequence';
  6672. state.result = _result;
  6673. return true;
  6674. }
  6675. return false;
  6676. }
  6677. function readBlockMapping(state, nodeIndent, flowIndent) {
  6678. var following,
  6679. allowCompact,
  6680. _line,
  6681. _keyLine,
  6682. _keyLineStart,
  6683. _keyPos,
  6684. _tag = state.tag,
  6685. _anchor = state.anchor,
  6686. _result = {},
  6687. overridableKeys = Object.create(null),
  6688. keyTag = null,
  6689. keyNode = null,
  6690. valueNode = null,
  6691. atExplicitKey = false,
  6692. detected = false,
  6693. ch;
  6694. // there is a leading tab before this token, so it can't be a block sequence/mapping;
  6695. // it can still be flow sequence/mapping or a scalar
  6696. if (state.firstTabInLine !== -1) return false;
  6697. if (state.anchor !== null) {
  6698. state.anchorMap[state.anchor] = _result;
  6699. }
  6700. ch = state.input.charCodeAt(state.position);
  6701. while (ch !== 0) {
  6702. if (!atExplicitKey && state.firstTabInLine !== -1) {
  6703. state.position = state.firstTabInLine;
  6704. throwError(state, 'tab characters must not be used in indentation');
  6705. }
  6706. following = state.input.charCodeAt(state.position + 1);
  6707. _line = state.line; // Save the current line.
  6708. //
  6709. // Explicit notation case. There are two separate blocks:
  6710. // first for the key (denoted by "?") and second for the value (denoted by ":")
  6711. //
  6712. if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
  6713. if (ch === 0x3F/* ? */) {
  6714. if (atExplicitKey) {
  6715. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  6716. keyTag = keyNode = valueNode = null;
  6717. }
  6718. detected = true;
  6719. atExplicitKey = true;
  6720. allowCompact = true;
  6721. } else if (atExplicitKey) {
  6722. // i.e. 0x3A/* : */ === character after the explicit key.
  6723. atExplicitKey = false;
  6724. allowCompact = true;
  6725. } else {
  6726. throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
  6727. }
  6728. state.position += 1;
  6729. ch = following;
  6730. //
  6731. // Implicit notation case. Flow-style node as the key first, then ":", and the value.
  6732. //
  6733. } else {
  6734. _keyLine = state.line;
  6735. _keyLineStart = state.lineStart;
  6736. _keyPos = state.position;
  6737. if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
  6738. // Neither implicit nor explicit notation.
  6739. // Reading is done. Go to the epilogue.
  6740. break;
  6741. }
  6742. if (state.line === _line) {
  6743. ch = state.input.charCodeAt(state.position);
  6744. while (is_WHITE_SPACE(ch)) {
  6745. ch = state.input.charCodeAt(++state.position);
  6746. }
  6747. if (ch === 0x3A/* : */) {
  6748. ch = state.input.charCodeAt(++state.position);
  6749. if (!is_WS_OR_EOL(ch)) {
  6750. throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
  6751. }
  6752. if (atExplicitKey) {
  6753. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  6754. keyTag = keyNode = valueNode = null;
  6755. }
  6756. detected = true;
  6757. atExplicitKey = false;
  6758. allowCompact = false;
  6759. keyTag = state.tag;
  6760. keyNode = state.result;
  6761. } else if (detected) {
  6762. throwError(state, 'can not read an implicit mapping pair; a colon is missed');
  6763. } else {
  6764. state.tag = _tag;
  6765. state.anchor = _anchor;
  6766. return true; // Keep the result of `composeNode`.
  6767. }
  6768. } else if (detected) {
  6769. throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
  6770. } else {
  6771. state.tag = _tag;
  6772. state.anchor = _anchor;
  6773. return true; // Keep the result of `composeNode`.
  6774. }
  6775. }
  6776. //
  6777. // Common reading code for both explicit and implicit notations.
  6778. //
  6779. if (state.line === _line || state.lineIndent > nodeIndent) {
  6780. if (atExplicitKey) {
  6781. _keyLine = state.line;
  6782. _keyLineStart = state.lineStart;
  6783. _keyPos = state.position;
  6784. }
  6785. if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
  6786. if (atExplicitKey) {
  6787. keyNode = state.result;
  6788. } else {
  6789. valueNode = state.result;
  6790. }
  6791. }
  6792. if (!atExplicitKey) {
  6793. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
  6794. keyTag = keyNode = valueNode = null;
  6795. }
  6796. skipSeparationSpace(state, true, -1);
  6797. ch = state.input.charCodeAt(state.position);
  6798. }
  6799. if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
  6800. throwError(state, 'bad indentation of a mapping entry');
  6801. } else if (state.lineIndent < nodeIndent) {
  6802. break;
  6803. }
  6804. }
  6805. //
  6806. // Epilogue.
  6807. //
  6808. // Special case: last mapping's node contains only the key in explicit notation.
  6809. if (atExplicitKey) {
  6810. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  6811. }
  6812. // Expose the resulting mapping.
  6813. if (detected) {
  6814. state.tag = _tag;
  6815. state.anchor = _anchor;
  6816. state.kind = 'mapping';
  6817. state.result = _result;
  6818. }
  6819. return detected;
  6820. }
  6821. function readTagProperty(state) {
  6822. var _position,
  6823. isVerbatim = false,
  6824. isNamed = false,
  6825. tagHandle,
  6826. tagName,
  6827. ch;
  6828. ch = state.input.charCodeAt(state.position);
  6829. if (ch !== 0x21/* ! */) return false;
  6830. if (state.tag !== null) {
  6831. throwError(state, 'duplication of a tag property');
  6832. }
  6833. ch = state.input.charCodeAt(++state.position);
  6834. if (ch === 0x3C/* < */) {
  6835. isVerbatim = true;
  6836. ch = state.input.charCodeAt(++state.position);
  6837. } else if (ch === 0x21/* ! */) {
  6838. isNamed = true;
  6839. tagHandle = '!!';
  6840. ch = state.input.charCodeAt(++state.position);
  6841. } else {
  6842. tagHandle = '!';
  6843. }
  6844. _position = state.position;
  6845. if (isVerbatim) {
  6846. do { ch = state.input.charCodeAt(++state.position); }
  6847. while (ch !== 0 && ch !== 0x3E/* > */);
  6848. if (state.position < state.length) {
  6849. tagName = state.input.slice(_position, state.position);
  6850. ch = state.input.charCodeAt(++state.position);
  6851. } else {
  6852. throwError(state, 'unexpected end of the stream within a verbatim tag');
  6853. }
  6854. } else {
  6855. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  6856. if (ch === 0x21/* ! */) {
  6857. if (!isNamed) {
  6858. tagHandle = state.input.slice(_position - 1, state.position + 1);
  6859. if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
  6860. throwError(state, 'named tag handle cannot contain such characters');
  6861. }
  6862. isNamed = true;
  6863. _position = state.position + 1;
  6864. } else {
  6865. throwError(state, 'tag suffix cannot contain exclamation marks');
  6866. }
  6867. }
  6868. ch = state.input.charCodeAt(++state.position);
  6869. }
  6870. tagName = state.input.slice(_position, state.position);
  6871. if (PATTERN_FLOW_INDICATORS.test(tagName)) {
  6872. throwError(state, 'tag suffix cannot contain flow indicator characters');
  6873. }
  6874. }
  6875. if (tagName && !PATTERN_TAG_URI.test(tagName)) {
  6876. throwError(state, 'tag name cannot contain such characters: ' + tagName);
  6877. }
  6878. try {
  6879. tagName = decodeURIComponent(tagName);
  6880. } catch (err) {
  6881. throwError(state, 'tag name is malformed: ' + tagName);
  6882. }
  6883. if (isVerbatim) {
  6884. state.tag = tagName;
  6885. } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
  6886. state.tag = state.tagMap[tagHandle] + tagName;
  6887. } else if (tagHandle === '!') {
  6888. state.tag = '!' + tagName;
  6889. } else if (tagHandle === '!!') {
  6890. state.tag = 'tag:yaml.org,2002:' + tagName;
  6891. } else {
  6892. throwError(state, 'undeclared tag handle "' + tagHandle + '"');
  6893. }
  6894. return true;
  6895. }
  6896. function readAnchorProperty(state) {
  6897. var _position,
  6898. ch;
  6899. ch = state.input.charCodeAt(state.position);
  6900. if (ch !== 0x26/* & */) return false;
  6901. if (state.anchor !== null) {
  6902. throwError(state, 'duplication of an anchor property');
  6903. }
  6904. ch = state.input.charCodeAt(++state.position);
  6905. _position = state.position;
  6906. while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
  6907. ch = state.input.charCodeAt(++state.position);
  6908. }
  6909. if (state.position === _position) {
  6910. throwError(state, 'name of an anchor node must contain at least one character');
  6911. }
  6912. state.anchor = state.input.slice(_position, state.position);
  6913. return true;
  6914. }
  6915. function readAlias(state) {
  6916. var _position, alias,
  6917. ch;
  6918. ch = state.input.charCodeAt(state.position);
  6919. if (ch !== 0x2A/* * */) return false;
  6920. ch = state.input.charCodeAt(++state.position);
  6921. _position = state.position;
  6922. while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
  6923. ch = state.input.charCodeAt(++state.position);
  6924. }
  6925. if (state.position === _position) {
  6926. throwError(state, 'name of an alias node must contain at least one character');
  6927. }
  6928. alias = state.input.slice(_position, state.position);
  6929. if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
  6930. throwError(state, 'unidentified alias "' + alias + '"');
  6931. }
  6932. state.result = state.anchorMap[alias];
  6933. skipSeparationSpace(state, true, -1);
  6934. return true;
  6935. }
  6936. function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
  6937. var allowBlockStyles,
  6938. allowBlockScalars,
  6939. allowBlockCollections,
  6940. indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
  6941. atNewLine = false,
  6942. hasContent = false,
  6943. typeIndex,
  6944. typeQuantity,
  6945. typeList,
  6946. type,
  6947. flowIndent,
  6948. blockIndent;
  6949. if (state.listener !== null) {
  6950. state.listener('open', state);
  6951. }
  6952. state.tag = null;
  6953. state.anchor = null;
  6954. state.kind = null;
  6955. state.result = null;
  6956. allowBlockStyles = allowBlockScalars = allowBlockCollections =
  6957. CONTEXT_BLOCK_OUT === nodeContext ||
  6958. CONTEXT_BLOCK_IN === nodeContext;
  6959. if (allowToSeek) {
  6960. if (skipSeparationSpace(state, true, -1)) {
  6961. atNewLine = true;
  6962. if (state.lineIndent > parentIndent) {
  6963. indentStatus = 1;
  6964. } else if (state.lineIndent === parentIndent) {
  6965. indentStatus = 0;
  6966. } else if (state.lineIndent < parentIndent) {
  6967. indentStatus = -1;
  6968. }
  6969. }
  6970. }
  6971. if (indentStatus === 1) {
  6972. while (readTagProperty(state) || readAnchorProperty(state)) {
  6973. if (skipSeparationSpace(state, true, -1)) {
  6974. atNewLine = true;
  6975. allowBlockCollections = allowBlockStyles;
  6976. if (state.lineIndent > parentIndent) {
  6977. indentStatus = 1;
  6978. } else if (state.lineIndent === parentIndent) {
  6979. indentStatus = 0;
  6980. } else if (state.lineIndent < parentIndent) {
  6981. indentStatus = -1;
  6982. }
  6983. } else {
  6984. allowBlockCollections = false;
  6985. }
  6986. }
  6987. }
  6988. if (allowBlockCollections) {
  6989. allowBlockCollections = atNewLine || allowCompact;
  6990. }
  6991. if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
  6992. if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
  6993. flowIndent = parentIndent;
  6994. } else {
  6995. flowIndent = parentIndent + 1;
  6996. }
  6997. blockIndent = state.position - state.lineStart;
  6998. if (indentStatus === 1) {
  6999. if (allowBlockCollections &&
  7000. (readBlockSequence(state, blockIndent) ||
  7001. readBlockMapping(state, blockIndent, flowIndent)) ||
  7002. readFlowCollection(state, flowIndent)) {
  7003. hasContent = true;
  7004. } else {
  7005. if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
  7006. readSingleQuotedScalar(state, flowIndent) ||
  7007. readDoubleQuotedScalar(state, flowIndent)) {
  7008. hasContent = true;
  7009. } else if (readAlias(state)) {
  7010. hasContent = true;
  7011. if (state.tag !== null || state.anchor !== null) {
  7012. throwError(state, 'alias node should not have any properties');
  7013. }
  7014. } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
  7015. hasContent = true;
  7016. if (state.tag === null) {
  7017. state.tag = '?';
  7018. }
  7019. }
  7020. if (state.anchor !== null) {
  7021. state.anchorMap[state.anchor] = state.result;
  7022. }
  7023. }
  7024. } else if (indentStatus === 0) {
  7025. // Special case: block sequences are allowed to have same indentation level as the parent.
  7026. // http://www.yaml.org/spec/1.2/spec.html#id2799784
  7027. hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
  7028. }
  7029. }
  7030. if (state.tag === null) {
  7031. if (state.anchor !== null) {
  7032. state.anchorMap[state.anchor] = state.result;
  7033. }
  7034. } else if (state.tag === '?') {
  7035. // Implicit resolving is not allowed for non-scalar types, and '?'
  7036. // non-specific tag is only automatically assigned to plain scalars.
  7037. //
  7038. // We only need to check kind conformity in case user explicitly assigns '?'
  7039. // tag, for example like this: "!<?> [0]"
  7040. //
  7041. if (state.result !== null && state.kind !== 'scalar') {
  7042. throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
  7043. }
  7044. for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
  7045. type = state.implicitTypes[typeIndex];
  7046. if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
  7047. state.result = type.construct(state.result);
  7048. state.tag = type.tag;
  7049. if (state.anchor !== null) {
  7050. state.anchorMap[state.anchor] = state.result;
  7051. }
  7052. break;
  7053. }
  7054. }
  7055. } else if (state.tag !== '!') {
  7056. if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
  7057. type = state.typeMap[state.kind || 'fallback'][state.tag];
  7058. } else {
  7059. // looking for multi type
  7060. type = null;
  7061. typeList = state.typeMap.multi[state.kind || 'fallback'];
  7062. for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
  7063. if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
  7064. type = typeList[typeIndex];
  7065. break;
  7066. }
  7067. }
  7068. }
  7069. if (!type) {
  7070. throwError(state, 'unknown tag !<' + state.tag + '>');
  7071. }
  7072. if (state.result !== null && type.kind !== state.kind) {
  7073. throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
  7074. }
  7075. if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
  7076. throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
  7077. } else {
  7078. state.result = type.construct(state.result, state.tag);
  7079. if (state.anchor !== null) {
  7080. state.anchorMap[state.anchor] = state.result;
  7081. }
  7082. }
  7083. }
  7084. if (state.listener !== null) {
  7085. state.listener('close', state);
  7086. }
  7087. return state.tag !== null || state.anchor !== null || hasContent;
  7088. }
  7089. function readDocument(state) {
  7090. var documentStart = state.position,
  7091. _position,
  7092. directiveName,
  7093. directiveArgs,
  7094. hasDirectives = false,
  7095. ch;
  7096. state.version = null;
  7097. state.checkLineBreaks = state.legacy;
  7098. state.tagMap = Object.create(null);
  7099. state.anchorMap = Object.create(null);
  7100. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  7101. skipSeparationSpace(state, true, -1);
  7102. ch = state.input.charCodeAt(state.position);
  7103. if (state.lineIndent > 0 || ch !== 0x25/* % */) {
  7104. break;
  7105. }
  7106. hasDirectives = true;
  7107. ch = state.input.charCodeAt(++state.position);
  7108. _position = state.position;
  7109. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  7110. ch = state.input.charCodeAt(++state.position);
  7111. }
  7112. directiveName = state.input.slice(_position, state.position);
  7113. directiveArgs = [];
  7114. if (directiveName.length < 1) {
  7115. throwError(state, 'directive name must not be less than one character in length');
  7116. }
  7117. while (ch !== 0) {
  7118. while (is_WHITE_SPACE(ch)) {
  7119. ch = state.input.charCodeAt(++state.position);
  7120. }
  7121. if (ch === 0x23/* # */) {
  7122. do { ch = state.input.charCodeAt(++state.position); }
  7123. while (ch !== 0 && !is_EOL(ch));
  7124. break;
  7125. }
  7126. if (is_EOL(ch)) break;
  7127. _position = state.position;
  7128. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  7129. ch = state.input.charCodeAt(++state.position);
  7130. }
  7131. directiveArgs.push(state.input.slice(_position, state.position));
  7132. }
  7133. if (ch !== 0) readLineBreak(state);
  7134. if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
  7135. directiveHandlers[directiveName](state, directiveName, directiveArgs);
  7136. } else {
  7137. throwWarning(state, 'unknown document directive "' + directiveName + '"');
  7138. }
  7139. }
  7140. skipSeparationSpace(state, true, -1);
  7141. if (state.lineIndent === 0 &&
  7142. state.input.charCodeAt(state.position) === 0x2D/* - */ &&
  7143. state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
  7144. state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
  7145. state.position += 3;
  7146. skipSeparationSpace(state, true, -1);
  7147. } else if (hasDirectives) {
  7148. throwError(state, 'directives end mark is expected');
  7149. }
  7150. composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
  7151. skipSeparationSpace(state, true, -1);
  7152. if (state.checkLineBreaks &&
  7153. PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
  7154. throwWarning(state, 'non-ASCII line breaks are interpreted as content');
  7155. }
  7156. state.documents.push(state.result);
  7157. if (state.position === state.lineStart && testDocumentSeparator(state)) {
  7158. if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
  7159. state.position += 3;
  7160. skipSeparationSpace(state, true, -1);
  7161. }
  7162. return;
  7163. }
  7164. if (state.position < (state.length - 1)) {
  7165. throwError(state, 'end of the stream or a document separator is expected');
  7166. } else {
  7167. return;
  7168. }
  7169. }
  7170. function loadDocuments(input, options) {
  7171. input = String(input);
  7172. options = options || {};
  7173. if (input.length !== 0) {
  7174. // Add tailing `\n` if not exists
  7175. if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
  7176. input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
  7177. input += '\n';
  7178. }
  7179. // Strip BOM
  7180. if (input.charCodeAt(0) === 0xFEFF) {
  7181. input = input.slice(1);
  7182. }
  7183. }
  7184. var state = new State$1(input, options);
  7185. var nullpos = input.indexOf('\0');
  7186. if (nullpos !== -1) {
  7187. state.position = nullpos;
  7188. throwError(state, 'null byte is not allowed in input');
  7189. }
  7190. // Use 0 as string terminator. That significantly simplifies bounds check.
  7191. state.input += '\0';
  7192. while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
  7193. state.lineIndent += 1;
  7194. state.position += 1;
  7195. }
  7196. while (state.position < (state.length - 1)) {
  7197. readDocument(state);
  7198. }
  7199. return state.documents;
  7200. }
  7201. function loadAll$1(input, iterator, options) {
  7202. if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
  7203. options = iterator;
  7204. iterator = null;
  7205. }
  7206. var documents = loadDocuments(input, options);
  7207. if (typeof iterator !== 'function') {
  7208. return documents;
  7209. }
  7210. for (var index = 0, length = documents.length; index < length; index += 1) {
  7211. iterator(documents[index]);
  7212. }
  7213. }
  7214. function load$1(input, options) {
  7215. var documents = loadDocuments(input, options);
  7216. if (documents.length === 0) {
  7217. /*eslint-disable no-undefined*/
  7218. return undefined;
  7219. } else if (documents.length === 1) {
  7220. return documents[0];
  7221. }
  7222. throw new exception('expected a single document in the stream, but found more');
  7223. }
  7224. var loadAll_1 = loadAll$1;
  7225. var load_1 = load$1;
  7226. var loader = {
  7227. loadAll: loadAll_1,
  7228. load: load_1
  7229. };
  7230. /*eslint-disable no-use-before-define*/
  7231. var _toString = Object.prototype.toString;
  7232. var _hasOwnProperty = Object.prototype.hasOwnProperty;
  7233. var CHAR_BOM = 0xFEFF;
  7234. var CHAR_TAB = 0x09; /* Tab */
  7235. var CHAR_LINE_FEED = 0x0A; /* LF */
  7236. var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
  7237. var CHAR_SPACE = 0x20; /* Space */
  7238. var CHAR_EXCLAMATION = 0x21; /* ! */
  7239. var CHAR_DOUBLE_QUOTE = 0x22; /* " */
  7240. var CHAR_SHARP = 0x23; /* # */
  7241. var CHAR_PERCENT = 0x25; /* % */
  7242. var CHAR_AMPERSAND = 0x26; /* & */
  7243. var CHAR_SINGLE_QUOTE = 0x27; /* ' */
  7244. var CHAR_ASTERISK = 0x2A; /* * */
  7245. var CHAR_COMMA = 0x2C; /* , */
  7246. var CHAR_MINUS = 0x2D; /* - */
  7247. var CHAR_COLON = 0x3A; /* : */
  7248. var CHAR_EQUALS = 0x3D; /* = */
  7249. var CHAR_GREATER_THAN = 0x3E; /* > */
  7250. var CHAR_QUESTION = 0x3F; /* ? */
  7251. var CHAR_COMMERCIAL_AT = 0x40; /* @ */
  7252. var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
  7253. var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
  7254. var CHAR_GRAVE_ACCENT = 0x60; /* ` */
  7255. var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
  7256. var CHAR_VERTICAL_LINE = 0x7C; /* | */
  7257. var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
  7258. var ESCAPE_SEQUENCES = {};
  7259. ESCAPE_SEQUENCES[0x00] = '\\0';
  7260. ESCAPE_SEQUENCES[0x07] = '\\a';
  7261. ESCAPE_SEQUENCES[0x08] = '\\b';
  7262. ESCAPE_SEQUENCES[0x09] = '\\t';
  7263. ESCAPE_SEQUENCES[0x0A] = '\\n';
  7264. ESCAPE_SEQUENCES[0x0B] = '\\v';
  7265. ESCAPE_SEQUENCES[0x0C] = '\\f';
  7266. ESCAPE_SEQUENCES[0x0D] = '\\r';
  7267. ESCAPE_SEQUENCES[0x1B] = '\\e';
  7268. ESCAPE_SEQUENCES[0x22] = '\\"';
  7269. ESCAPE_SEQUENCES[0x5C] = '\\\\';
  7270. ESCAPE_SEQUENCES[0x85] = '\\N';
  7271. ESCAPE_SEQUENCES[0xA0] = '\\_';
  7272. ESCAPE_SEQUENCES[0x2028] = '\\L';
  7273. ESCAPE_SEQUENCES[0x2029] = '\\P';
  7274. var DEPRECATED_BOOLEANS_SYNTAX = [
  7275. 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
  7276. 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
  7277. ];
  7278. var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
  7279. function compileStyleMap(schema, map) {
  7280. var result, keys, index, length, tag, style, type;
  7281. if (map === null) return {};
  7282. result = {};
  7283. keys = Object.keys(map);
  7284. for (index = 0, length = keys.length; index < length; index += 1) {
  7285. tag = keys[index];
  7286. style = String(map[tag]);
  7287. if (tag.slice(0, 2) === '!!') {
  7288. tag = 'tag:yaml.org,2002:' + tag.slice(2);
  7289. }
  7290. type = schema.compiledTypeMap['fallback'][tag];
  7291. if (type && _hasOwnProperty.call(type.styleAliases, style)) {
  7292. style = type.styleAliases[style];
  7293. }
  7294. result[tag] = style;
  7295. }
  7296. return result;
  7297. }
  7298. function encodeHex(character) {
  7299. var string, handle, length;
  7300. string = character.toString(16).toUpperCase();
  7301. if (character <= 0xFF) {
  7302. handle = 'x';
  7303. length = 2;
  7304. } else if (character <= 0xFFFF) {
  7305. handle = 'u';
  7306. length = 4;
  7307. } else if (character <= 0xFFFFFFFF) {
  7308. handle = 'U';
  7309. length = 8;
  7310. } else {
  7311. throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
  7312. }
  7313. return '\\' + handle + common.repeat('0', length - string.length) + string;
  7314. }
  7315. var QUOTING_TYPE_SINGLE = 1,
  7316. QUOTING_TYPE_DOUBLE = 2;
  7317. function State(options) {
  7318. this.schema = options['schema'] || _default;
  7319. this.indent = Math.max(1, (options['indent'] || 2));
  7320. this.noArrayIndent = options['noArrayIndent'] || false;
  7321. this.skipInvalid = options['skipInvalid'] || false;
  7322. this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
  7323. this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
  7324. this.sortKeys = options['sortKeys'] || false;
  7325. this.lineWidth = options['lineWidth'] || 80;
  7326. this.noRefs = options['noRefs'] || false;
  7327. this.noCompatMode = options['noCompatMode'] || false;
  7328. this.condenseFlow = options['condenseFlow'] || false;
  7329. this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
  7330. this.forceQuotes = options['forceQuotes'] || false;
  7331. this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;
  7332. this.implicitTypes = this.schema.compiledImplicit;
  7333. this.explicitTypes = this.schema.compiledExplicit;
  7334. this.tag = null;
  7335. this.result = '';
  7336. this.duplicates = [];
  7337. this.usedDuplicates = null;
  7338. }
  7339. // Indents every line in a string. Empty lines (\n only) are not indented.
  7340. function indentString(string, spaces) {
  7341. var ind = common.repeat(' ', spaces),
  7342. position = 0,
  7343. next = -1,
  7344. result = '',
  7345. line,
  7346. length = string.length;
  7347. while (position < length) {
  7348. next = string.indexOf('\n', position);
  7349. if (next === -1) {
  7350. line = string.slice(position);
  7351. position = length;
  7352. } else {
  7353. line = string.slice(position, next + 1);
  7354. position = next + 1;
  7355. }
  7356. if (line.length && line !== '\n') result += ind;
  7357. result += line;
  7358. }
  7359. return result;
  7360. }
  7361. function generateNextLine(state, level) {
  7362. return '\n' + common.repeat(' ', state.indent * level);
  7363. }
  7364. function testImplicitResolving(state, str) {
  7365. var index, length, type;
  7366. for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
  7367. type = state.implicitTypes[index];
  7368. if (type.resolve(str)) {
  7369. return true;
  7370. }
  7371. }
  7372. return false;
  7373. }
  7374. // [33] s-white ::= s-space | s-tab
  7375. function isWhitespace(c) {
  7376. return c === CHAR_SPACE || c === CHAR_TAB;
  7377. }
  7378. // Returns true if the character can be printed without escaping.
  7379. // From YAML 1.2: "any allowed characters known to be non-printable
  7380. // should also be escaped. [However,] This isn’t mandatory"
  7381. // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
  7382. function isPrintable(c) {
  7383. return (0x00020 <= c && c <= 0x00007E)
  7384. || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
  7385. || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
  7386. || (0x10000 <= c && c <= 0x10FFFF);
  7387. }
  7388. // [34] ns-char ::= nb-char - s-white
  7389. // [27] nb-char ::= c-printable - b-char - c-byte-order-mark
  7390. // [26] b-char ::= b-line-feed | b-carriage-return
  7391. // Including s-white (for some reason, examples doesn't match specs in this aspect)
  7392. // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
  7393. function isNsCharOrWhitespace(c) {
  7394. return isPrintable(c)
  7395. && c !== CHAR_BOM
  7396. // - b-char
  7397. && c !== CHAR_CARRIAGE_RETURN
  7398. && c !== CHAR_LINE_FEED;
  7399. }
  7400. // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out
  7401. // c = flow-in ⇒ ns-plain-safe-in
  7402. // c = block-key ⇒ ns-plain-safe-out
  7403. // c = flow-key ⇒ ns-plain-safe-in
  7404. // [128] ns-plain-safe-out ::= ns-char
  7405. // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator
  7406. // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )
  7407. // | ( /* An ns-char preceding */ “#” )
  7408. // | ( “:” /* Followed by an ns-plain-safe(c) */ )
  7409. function isPlainSafe(c, prev, inblock) {
  7410. var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
  7411. var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
  7412. return (
  7413. // ns-plain-safe
  7414. inblock ? // c = flow-in
  7415. cIsNsCharOrWhitespace
  7416. : cIsNsCharOrWhitespace
  7417. // - c-flow-indicator
  7418. && c !== CHAR_COMMA
  7419. && c !== CHAR_LEFT_SQUARE_BRACKET
  7420. && c !== CHAR_RIGHT_SQUARE_BRACKET
  7421. && c !== CHAR_LEFT_CURLY_BRACKET
  7422. && c !== CHAR_RIGHT_CURLY_BRACKET
  7423. )
  7424. // ns-plain-char
  7425. && c !== CHAR_SHARP // false on '#'
  7426. && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
  7427. || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
  7428. || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
  7429. }
  7430. // Simplified test for values allowed as the first character in plain style.
  7431. function isPlainSafeFirst(c) {
  7432. // Uses a subset of ns-char - c-indicator
  7433. // where ns-char = nb-char - s-white.
  7434. // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
  7435. return isPrintable(c) && c !== CHAR_BOM
  7436. && !isWhitespace(c) // - s-white
  7437. // - (c-indicator ::=
  7438. // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
  7439. && c !== CHAR_MINUS
  7440. && c !== CHAR_QUESTION
  7441. && c !== CHAR_COLON
  7442. && c !== CHAR_COMMA
  7443. && c !== CHAR_LEFT_SQUARE_BRACKET
  7444. && c !== CHAR_RIGHT_SQUARE_BRACKET
  7445. && c !== CHAR_LEFT_CURLY_BRACKET
  7446. && c !== CHAR_RIGHT_CURLY_BRACKET
  7447. // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
  7448. && c !== CHAR_SHARP
  7449. && c !== CHAR_AMPERSAND
  7450. && c !== CHAR_ASTERISK
  7451. && c !== CHAR_EXCLAMATION
  7452. && c !== CHAR_VERTICAL_LINE
  7453. && c !== CHAR_EQUALS
  7454. && c !== CHAR_GREATER_THAN
  7455. && c !== CHAR_SINGLE_QUOTE
  7456. && c !== CHAR_DOUBLE_QUOTE
  7457. // | “%” | “@” | “`”)
  7458. && c !== CHAR_PERCENT
  7459. && c !== CHAR_COMMERCIAL_AT
  7460. && c !== CHAR_GRAVE_ACCENT;
  7461. }
  7462. // Simplified test for values allowed as the last character in plain style.
  7463. function isPlainSafeLast(c) {
  7464. // just not whitespace or colon, it will be checked to be plain character later
  7465. return !isWhitespace(c) && c !== CHAR_COLON;
  7466. }
  7467. // Same as 'string'.codePointAt(pos), but works in older browsers.
  7468. function codePointAt(string, pos) {
  7469. var first = string.charCodeAt(pos), second;
  7470. if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
  7471. second = string.charCodeAt(pos + 1);
  7472. if (second >= 0xDC00 && second <= 0xDFFF) {
  7473. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  7474. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  7475. }
  7476. }
  7477. return first;
  7478. }
  7479. // Determines whether block indentation indicator is required.
  7480. function needIndentIndicator(string) {
  7481. var leadingSpaceRe = /^\n* /;
  7482. return leadingSpaceRe.test(string);
  7483. }
  7484. var STYLE_PLAIN = 1,
  7485. STYLE_SINGLE = 2,
  7486. STYLE_LITERAL = 3,
  7487. STYLE_FOLDED = 4,
  7488. STYLE_DOUBLE = 5;
  7489. // Determines which scalar styles are possible and returns the preferred style.
  7490. // lineWidth = -1 => no limit.
  7491. // Pre-conditions: str.length > 0.
  7492. // Post-conditions:
  7493. // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
  7494. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
  7495. // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
  7496. function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
  7497. testAmbiguousType, quotingType, forceQuotes, inblock) {
  7498. var i;
  7499. var char = 0;
  7500. var prevChar = null;
  7501. var hasLineBreak = false;
  7502. var hasFoldableLine = false; // only checked if shouldTrackWidth
  7503. var shouldTrackWidth = lineWidth !== -1;
  7504. var previousLineBreak = -1; // count the first line correctly
  7505. var plain = isPlainSafeFirst(codePointAt(string, 0))
  7506. && isPlainSafeLast(codePointAt(string, string.length - 1));
  7507. if (singleLineOnly || forceQuotes) {
  7508. // Case: no block styles.
  7509. // Check for disallowed characters to rule out plain and single.
  7510. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
  7511. char = codePointAt(string, i);
  7512. if (!isPrintable(char)) {
  7513. return STYLE_DOUBLE;
  7514. }
  7515. plain = plain && isPlainSafe(char, prevChar, inblock);
  7516. prevChar = char;
  7517. }
  7518. } else {
  7519. // Case: block styles permitted.
  7520. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
  7521. char = codePointAt(string, i);
  7522. if (char === CHAR_LINE_FEED) {
  7523. hasLineBreak = true;
  7524. // Check if any line can be folded.
  7525. if (shouldTrackWidth) {
  7526. hasFoldableLine = hasFoldableLine ||
  7527. // Foldable line = too long, and not more-indented.
  7528. (i - previousLineBreak - 1 > lineWidth &&
  7529. string[previousLineBreak + 1] !== ' ');
  7530. previousLineBreak = i;
  7531. }
  7532. } else if (!isPrintable(char)) {
  7533. return STYLE_DOUBLE;
  7534. }
  7535. plain = plain && isPlainSafe(char, prevChar, inblock);
  7536. prevChar = char;
  7537. }
  7538. // in case the end is missing a \n
  7539. hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
  7540. (i - previousLineBreak - 1 > lineWidth &&
  7541. string[previousLineBreak + 1] !== ' '));
  7542. }
  7543. // Although every style can represent \n without escaping, prefer block styles
  7544. // for multiline, since they're more readable and they don't add empty lines.
  7545. // Also prefer folding a super-long line.
  7546. if (!hasLineBreak && !hasFoldableLine) {
  7547. // Strings interpretable as another type have to be quoted;
  7548. // e.g. the string 'true' vs. the boolean true.
  7549. if (plain && !forceQuotes && !testAmbiguousType(string)) {
  7550. return STYLE_PLAIN;
  7551. }
  7552. return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
  7553. }
  7554. // Edge case: block indentation indicator can only have one digit.
  7555. if (indentPerLevel > 9 && needIndentIndicator(string)) {
  7556. return STYLE_DOUBLE;
  7557. }
  7558. // At this point we know block styles are valid.
  7559. // Prefer literal style unless we want to fold.
  7560. if (!forceQuotes) {
  7561. return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
  7562. }
  7563. return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
  7564. }
  7565. // Note: line breaking/folding is implemented for only the folded style.
  7566. // NB. We drop the last trailing newline (if any) of a returned block scalar
  7567. // since the dumper adds its own newline. This always works:
  7568. // • No ending newline => unaffected; already using strip "-" chomping.
  7569. // • Ending newline => removed then restored.
  7570. // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
  7571. function writeScalar(state, string, level, iskey, inblock) {
  7572. state.dump = (function () {
  7573. if (string.length === 0) {
  7574. return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
  7575. }
  7576. if (!state.noCompatMode) {
  7577. if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
  7578. return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
  7579. }
  7580. }
  7581. var indent = state.indent * Math.max(1, level); // no 0-indent scalars
  7582. // As indentation gets deeper, let the width decrease monotonically
  7583. // to the lower bound min(state.lineWidth, 40).
  7584. // Note that this implies
  7585. // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
  7586. // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
  7587. // This behaves better than a constant minimum width which disallows narrower options,
  7588. // or an indent threshold which causes the width to suddenly increase.
  7589. var lineWidth = state.lineWidth === -1
  7590. ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
  7591. // Without knowing if keys are implicit/explicit, assume implicit for safety.
  7592. var singleLineOnly = iskey
  7593. // No block styles in flow mode.
  7594. || (state.flowLevel > -1 && level >= state.flowLevel);
  7595. function testAmbiguity(string) {
  7596. return testImplicitResolving(state, string);
  7597. }
  7598. switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
  7599. testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
  7600. case STYLE_PLAIN:
  7601. return string;
  7602. case STYLE_SINGLE:
  7603. return "'" + string.replace(/'/g, "''") + "'";
  7604. case STYLE_LITERAL:
  7605. return '|' + blockHeader(string, state.indent)
  7606. + dropEndingNewline(indentString(string, indent));
  7607. case STYLE_FOLDED:
  7608. return '>' + blockHeader(string, state.indent)
  7609. + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
  7610. case STYLE_DOUBLE:
  7611. return '"' + escapeString(string) + '"';
  7612. default:
  7613. throw new exception('impossible error: invalid scalar style');
  7614. }
  7615. }());
  7616. }
  7617. // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
  7618. function blockHeader(string, indentPerLevel) {
  7619. var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
  7620. // note the special case: the string '\n' counts as a "trailing" empty line.
  7621. var clip = string[string.length - 1] === '\n';
  7622. var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
  7623. var chomp = keep ? '+' : (clip ? '' : '-');
  7624. return indentIndicator + chomp + '\n';
  7625. }
  7626. // (See the note for writeScalar.)
  7627. function dropEndingNewline(string) {
  7628. return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
  7629. }
  7630. // Note: a long line without a suitable break point will exceed the width limit.
  7631. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
  7632. function foldString(string, width) {
  7633. // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
  7634. // unless they're before or after a more-indented line, or at the very
  7635. // beginning or end, in which case $k$ maps to $k$.
  7636. // Therefore, parse each chunk as newline(s) followed by a content line.
  7637. var lineRe = /(\n+)([^\n]*)/g;
  7638. // first line (possibly an empty line)
  7639. var result = (function () {
  7640. var nextLF = string.indexOf('\n');
  7641. nextLF = nextLF !== -1 ? nextLF : string.length;
  7642. lineRe.lastIndex = nextLF;
  7643. return foldLine(string.slice(0, nextLF), width);
  7644. }());
  7645. // If we haven't reached the first content line yet, don't add an extra \n.
  7646. var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
  7647. var moreIndented;
  7648. // rest of the lines
  7649. var match;
  7650. while ((match = lineRe.exec(string))) {
  7651. var prefix = match[1], line = match[2];
  7652. moreIndented = (line[0] === ' ');
  7653. result += prefix
  7654. + (!prevMoreIndented && !moreIndented && line !== ''
  7655. ? '\n' : '')
  7656. + foldLine(line, width);
  7657. prevMoreIndented = moreIndented;
  7658. }
  7659. return result;
  7660. }
  7661. // Greedy line breaking.
  7662. // Picks the longest line under the limit each time,
  7663. // otherwise settles for the shortest line over the limit.
  7664. // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
  7665. function foldLine(line, width) {
  7666. if (line === '' || line[0] === ' ') return line;
  7667. // Since a more-indented line adds a \n, breaks can't be followed by a space.
  7668. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
  7669. var match;
  7670. // start is an inclusive index. end, curr, and next are exclusive.
  7671. var start = 0, end, curr = 0, next = 0;
  7672. var result = '';
  7673. // Invariants: 0 <= start <= length-1.
  7674. // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
  7675. // Inside the loop:
  7676. // A match implies length >= 2, so curr and next are <= length-2.
  7677. while ((match = breakRe.exec(line))) {
  7678. next = match.index;
  7679. // maintain invariant: curr - start <= width
  7680. if (next - start > width) {
  7681. end = (curr > start) ? curr : next; // derive end <= length-2
  7682. result += '\n' + line.slice(start, end);
  7683. // skip the space that was output as \n
  7684. start = end + 1; // derive start <= length-1
  7685. }
  7686. curr = next;
  7687. }
  7688. // By the invariants, start <= length-1, so there is something left over.
  7689. // It is either the whole string or a part starting from non-whitespace.
  7690. result += '\n';
  7691. // Insert a break if the remainder is too long and there is a break available.
  7692. if (line.length - start > width && curr > start) {
  7693. result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
  7694. } else {
  7695. result += line.slice(start);
  7696. }
  7697. return result.slice(1); // drop extra \n joiner
  7698. }
  7699. // Escapes a double-quoted string.
  7700. function escapeString(string) {
  7701. var result = '';
  7702. var char = 0;
  7703. var escapeSeq;
  7704. for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
  7705. char = codePointAt(string, i);
  7706. escapeSeq = ESCAPE_SEQUENCES[char];
  7707. if (!escapeSeq && isPrintable(char)) {
  7708. result += string[i];
  7709. if (char >= 0x10000) result += string[i + 1];
  7710. } else {
  7711. result += escapeSeq || encodeHex(char);
  7712. }
  7713. }
  7714. return result;
  7715. }
  7716. function writeFlowSequence(state, level, object) {
  7717. var _result = '',
  7718. _tag = state.tag,
  7719. index,
  7720. length,
  7721. value;
  7722. for (index = 0, length = object.length; index < length; index += 1) {
  7723. value = object[index];
  7724. if (state.replacer) {
  7725. value = state.replacer.call(object, String(index), value);
  7726. }
  7727. // Write only valid elements, put null instead of invalid elements.
  7728. if (writeNode(state, level, value, false, false) ||
  7729. (typeof value === 'undefined' &&
  7730. writeNode(state, level, null, false, false))) {
  7731. if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
  7732. _result += state.dump;
  7733. }
  7734. }
  7735. state.tag = _tag;
  7736. state.dump = '[' + _result + ']';
  7737. }
  7738. function writeBlockSequence(state, level, object, compact) {
  7739. var _result = '',
  7740. _tag = state.tag,
  7741. index,
  7742. length,
  7743. value;
  7744. for (index = 0, length = object.length; index < length; index += 1) {
  7745. value = object[index];
  7746. if (state.replacer) {
  7747. value = state.replacer.call(object, String(index), value);
  7748. }
  7749. // Write only valid elements, put null instead of invalid elements.
  7750. if (writeNode(state, level + 1, value, true, true, false, true) ||
  7751. (typeof value === 'undefined' &&
  7752. writeNode(state, level + 1, null, true, true, false, true))) {
  7753. if (!compact || _result !== '') {
  7754. _result += generateNextLine(state, level);
  7755. }
  7756. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  7757. _result += '-';
  7758. } else {
  7759. _result += '- ';
  7760. }
  7761. _result += state.dump;
  7762. }
  7763. }
  7764. state.tag = _tag;
  7765. state.dump = _result || '[]'; // Empty sequence if no valid values.
  7766. }
  7767. function writeFlowMapping(state, level, object) {
  7768. var _result = '',
  7769. _tag = state.tag,
  7770. objectKeyList = Object.keys(object),
  7771. index,
  7772. length,
  7773. objectKey,
  7774. objectValue,
  7775. pairBuffer;
  7776. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  7777. pairBuffer = '';
  7778. if (_result !== '') pairBuffer += ', ';
  7779. if (state.condenseFlow) pairBuffer += '"';
  7780. objectKey = objectKeyList[index];
  7781. objectValue = object[objectKey];
  7782. if (state.replacer) {
  7783. objectValue = state.replacer.call(object, objectKey, objectValue);
  7784. }
  7785. if (!writeNode(state, level, objectKey, false, false)) {
  7786. continue; // Skip this pair because of invalid key;
  7787. }
  7788. if (state.dump.length > 1024) pairBuffer += '? ';
  7789. pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
  7790. if (!writeNode(state, level, objectValue, false, false)) {
  7791. continue; // Skip this pair because of invalid value.
  7792. }
  7793. pairBuffer += state.dump;
  7794. // Both key and value are valid.
  7795. _result += pairBuffer;
  7796. }
  7797. state.tag = _tag;
  7798. state.dump = '{' + _result + '}';
  7799. }
  7800. function writeBlockMapping(state, level, object, compact) {
  7801. var _result = '',
  7802. _tag = state.tag,
  7803. objectKeyList = Object.keys(object),
  7804. index,
  7805. length,
  7806. objectKey,
  7807. objectValue,
  7808. explicitPair,
  7809. pairBuffer;
  7810. // Allow sorting keys so that the output file is deterministic
  7811. if (state.sortKeys === true) {
  7812. // Default sorting
  7813. objectKeyList.sort();
  7814. } else if (typeof state.sortKeys === 'function') {
  7815. // Custom sort function
  7816. objectKeyList.sort(state.sortKeys);
  7817. } else if (state.sortKeys) {
  7818. // Something is wrong
  7819. throw new exception('sortKeys must be a boolean or a function');
  7820. }
  7821. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  7822. pairBuffer = '';
  7823. if (!compact || _result !== '') {
  7824. pairBuffer += generateNextLine(state, level);
  7825. }
  7826. objectKey = objectKeyList[index];
  7827. objectValue = object[objectKey];
  7828. if (state.replacer) {
  7829. objectValue = state.replacer.call(object, objectKey, objectValue);
  7830. }
  7831. if (!writeNode(state, level + 1, objectKey, true, true, true)) {
  7832. continue; // Skip this pair because of invalid key.
  7833. }
  7834. explicitPair = (state.tag !== null && state.tag !== '?') ||
  7835. (state.dump && state.dump.length > 1024);
  7836. if (explicitPair) {
  7837. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  7838. pairBuffer += '?';
  7839. } else {
  7840. pairBuffer += '? ';
  7841. }
  7842. }
  7843. pairBuffer += state.dump;
  7844. if (explicitPair) {
  7845. pairBuffer += generateNextLine(state, level);
  7846. }
  7847. if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
  7848. continue; // Skip this pair because of invalid value.
  7849. }
  7850. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  7851. pairBuffer += ':';
  7852. } else {
  7853. pairBuffer += ': ';
  7854. }
  7855. pairBuffer += state.dump;
  7856. // Both key and value are valid.
  7857. _result += pairBuffer;
  7858. }
  7859. state.tag = _tag;
  7860. state.dump = _result || '{}'; // Empty mapping if no valid pairs.
  7861. }
  7862. function detectType(state, object, explicit) {
  7863. var _result, typeList, index, length, type, style;
  7864. typeList = explicit ? state.explicitTypes : state.implicitTypes;
  7865. for (index = 0, length = typeList.length; index < length; index += 1) {
  7866. type = typeList[index];
  7867. if ((type.instanceOf || type.predicate) &&
  7868. (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
  7869. (!type.predicate || type.predicate(object))) {
  7870. if (explicit) {
  7871. if (type.multi && type.representName) {
  7872. state.tag = type.representName(object);
  7873. } else {
  7874. state.tag = type.tag;
  7875. }
  7876. } else {
  7877. state.tag = '?';
  7878. }
  7879. if (type.represent) {
  7880. style = state.styleMap[type.tag] || type.defaultStyle;
  7881. if (_toString.call(type.represent) === '[object Function]') {
  7882. _result = type.represent(object, style);
  7883. } else if (_hasOwnProperty.call(type.represent, style)) {
  7884. _result = type.represent[style](object, style);
  7885. } else {
  7886. throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
  7887. }
  7888. state.dump = _result;
  7889. }
  7890. return true;
  7891. }
  7892. }
  7893. return false;
  7894. }
  7895. // Serializes `object` and writes it to global `result`.
  7896. // Returns true on success, or false on invalid object.
  7897. //
  7898. function writeNode(state, level, object, block, compact, iskey, isblockseq) {
  7899. state.tag = null;
  7900. state.dump = object;
  7901. if (!detectType(state, object, false)) {
  7902. detectType(state, object, true);
  7903. }
  7904. var type = _toString.call(state.dump);
  7905. var inblock = block;
  7906. var tagStr;
  7907. if (block) {
  7908. block = (state.flowLevel < 0 || state.flowLevel > level);
  7909. }
  7910. var objectOrArray = type === '[object Object]' || type === '[object Array]',
  7911. duplicateIndex,
  7912. duplicate;
  7913. if (objectOrArray) {
  7914. duplicateIndex = state.duplicates.indexOf(object);
  7915. duplicate = duplicateIndex !== -1;
  7916. }
  7917. if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
  7918. compact = false;
  7919. }
  7920. if (duplicate && state.usedDuplicates[duplicateIndex]) {
  7921. state.dump = '*ref_' + duplicateIndex;
  7922. } else {
  7923. if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
  7924. state.usedDuplicates[duplicateIndex] = true;
  7925. }
  7926. if (type === '[object Object]') {
  7927. if (block && (Object.keys(state.dump).length !== 0)) {
  7928. writeBlockMapping(state, level, state.dump, compact);
  7929. if (duplicate) {
  7930. state.dump = '&ref_' + duplicateIndex + state.dump;
  7931. }
  7932. } else {
  7933. writeFlowMapping(state, level, state.dump);
  7934. if (duplicate) {
  7935. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  7936. }
  7937. }
  7938. } else if (type === '[object Array]') {
  7939. if (block && (state.dump.length !== 0)) {
  7940. if (state.noArrayIndent && !isblockseq && level > 0) {
  7941. writeBlockSequence(state, level - 1, state.dump, compact);
  7942. } else {
  7943. writeBlockSequence(state, level, state.dump, compact);
  7944. }
  7945. if (duplicate) {
  7946. state.dump = '&ref_' + duplicateIndex + state.dump;
  7947. }
  7948. } else {
  7949. writeFlowSequence(state, level, state.dump);
  7950. if (duplicate) {
  7951. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  7952. }
  7953. }
  7954. } else if (type === '[object String]') {
  7955. if (state.tag !== '?') {
  7956. writeScalar(state, state.dump, level, iskey, inblock);
  7957. }
  7958. } else if (type === '[object Undefined]') {
  7959. return false;
  7960. } else {
  7961. if (state.skipInvalid) return false;
  7962. throw new exception('unacceptable kind of an object to dump ' + type);
  7963. }
  7964. if (state.tag !== null && state.tag !== '?') {
  7965. // Need to encode all characters except those allowed by the spec:
  7966. //
  7967. // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
  7968. // [36] ns-hex-digit ::= ns-dec-digit
  7969. // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
  7970. // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
  7971. // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
  7972. // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
  7973. // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
  7974. // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
  7975. //
  7976. // Also need to encode '!' because it has special meaning (end of tag prefix).
  7977. //
  7978. tagStr = encodeURI(
  7979. state.tag[0] === '!' ? state.tag.slice(1) : state.tag
  7980. ).replace(/!/g, '%21');
  7981. if (state.tag[0] === '!') {
  7982. tagStr = '!' + tagStr;
  7983. } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
  7984. tagStr = '!!' + tagStr.slice(18);
  7985. } else {
  7986. tagStr = '!<' + tagStr + '>';
  7987. }
  7988. state.dump = tagStr + ' ' + state.dump;
  7989. }
  7990. }
  7991. return true;
  7992. }
  7993. function getDuplicateReferences(object, state) {
  7994. var objects = [],
  7995. duplicatesIndexes = [],
  7996. index,
  7997. length;
  7998. inspectNode(object, objects, duplicatesIndexes);
  7999. for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
  8000. state.duplicates.push(objects[duplicatesIndexes[index]]);
  8001. }
  8002. state.usedDuplicates = new Array(length);
  8003. }
  8004. function inspectNode(object, objects, duplicatesIndexes) {
  8005. var objectKeyList,
  8006. index,
  8007. length;
  8008. if (object !== null && typeof object === 'object') {
  8009. index = objects.indexOf(object);
  8010. if (index !== -1) {
  8011. if (duplicatesIndexes.indexOf(index) === -1) {
  8012. duplicatesIndexes.push(index);
  8013. }
  8014. } else {
  8015. objects.push(object);
  8016. if (Array.isArray(object)) {
  8017. for (index = 0, length = object.length; index < length; index += 1) {
  8018. inspectNode(object[index], objects, duplicatesIndexes);
  8019. }
  8020. } else {
  8021. objectKeyList = Object.keys(object);
  8022. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  8023. inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
  8024. }
  8025. }
  8026. }
  8027. }
  8028. }
  8029. function dump$1(input, options) {
  8030. options = options || {};
  8031. var state = new State(options);
  8032. if (!state.noRefs) getDuplicateReferences(input, state);
  8033. var value = input;
  8034. if (state.replacer) {
  8035. value = state.replacer.call({ '': value }, '', value);
  8036. }
  8037. if (writeNode(state, 0, value, true, true)) return state.dump + '\n';
  8038. return '';
  8039. }
  8040. var dump_1 = dump$1;
  8041. var dumper = {
  8042. dump: dump_1
  8043. };
  8044. function renamed(from, to) {
  8045. return function () {
  8046. throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
  8047. 'Use yaml.' + to + ' instead, which is now safe by default.');
  8048. };
  8049. }
  8050. var Type = type;
  8051. var Schema = schema;
  8052. var FAILSAFE_SCHEMA = failsafe;
  8053. var JSON_SCHEMA = json;
  8054. var CORE_SCHEMA = core;
  8055. var DEFAULT_SCHEMA = _default;
  8056. var load = loader.load;
  8057. var loadAll = loader.loadAll;
  8058. var dump = dumper.dump;
  8059. var YAMLException = exception;
  8060. // Re-export all types in case user wants to create custom schema
  8061. var types = {
  8062. binary: binary,
  8063. float: float,
  8064. map: map,
  8065. null: _null,
  8066. pairs: pairs,
  8067. set: set,
  8068. timestamp: timestamp,
  8069. bool: bool,
  8070. int: int,
  8071. merge: merge,
  8072. omap: omap,
  8073. seq: seq,
  8074. str: str
  8075. };
  8076. // Removed functions from JS-YAML 3.0.x
  8077. var safeLoad = renamed('safeLoad', 'load');
  8078. var safeLoadAll = renamed('safeLoadAll', 'loadAll');
  8079. var safeDump = renamed('safeDump', 'dump');
  8080. var jsYaml = {
  8081. Type: Type,
  8082. Schema: Schema,
  8083. FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
  8084. JSON_SCHEMA: JSON_SCHEMA,
  8085. CORE_SCHEMA: CORE_SCHEMA,
  8086. DEFAULT_SCHEMA: DEFAULT_SCHEMA,
  8087. load: load,
  8088. loadAll: loadAll,
  8089. dump: dump,
  8090. YAMLException: YAMLException,
  8091. types: types,
  8092. safeLoad: safeLoad,
  8093. safeLoadAll: safeLoadAll,
  8094. safeDump: safeDump
  8095. };
  8096. class CSSSettingsPlugin extends obsidian.Plugin {
  8097. constructor() {
  8098. super(...arguments);
  8099. this.settingsList = [];
  8100. this.errorList = [];
  8101. this.commandList = [];
  8102. this.debounceTimer = 0;
  8103. }
  8104. onload() {
  8105. return __awaiter(this, void 0, void 0, function* () {
  8106. this.settingsManager = new CSSSettingsManager(this);
  8107. yield this.settingsManager.load();
  8108. this.settingsTab = new CSSSettingsTab(this.app, this);
  8109. this.addSettingTab(this.settingsTab);
  8110. this.registerView(viewType, (leaf) => new SettingsView(this, leaf));
  8111. this.addCommand({
  8112. id: 'show-style-settings-leaf',
  8113. name: 'Show style settings view',
  8114. callback: () => {
  8115. this.activateView();
  8116. },
  8117. });
  8118. this.registerEvent(this.app.workspace.on('css-change', (data) => {
  8119. if ((data === null || data === void 0 ? void 0 : data.source) !== 'style-settings') {
  8120. this.parseCSS();
  8121. }
  8122. }));
  8123. this.registerEvent(this.app.workspace.on('parse-style-settings', () => {
  8124. this.parseCSS();
  8125. }));
  8126. this.lightEl = document.body.createDiv('theme-light style-settings-ref');
  8127. this.darkEl = document.body.createDiv('theme-dark style-settings-ref');
  8128. document.body.classList.add('css-settings-manager');
  8129. this.parseCSS();
  8130. this.app.workspace.onLayoutReady(() => {
  8131. if (this.settingsList) {
  8132. this.app.workspace.getLeavesOfType(viewType).forEach((leaf) => {
  8133. leaf.view.setSettings(this.settingsList, this.errorList);
  8134. });
  8135. }
  8136. });
  8137. });
  8138. }
  8139. getCSSVar(id) {
  8140. const light = getComputedStyle(this.lightEl).getPropertyValue(`--${id}`);
  8141. const dark = getComputedStyle(this.darkEl).getPropertyValue(`--${id}`);
  8142. const current = getComputedStyle(document.body).getPropertyValue(`--${id}`);
  8143. return { light, dark, current };
  8144. }
  8145. parseCSS() {
  8146. clearTimeout(this.debounceTimer);
  8147. this.debounceTimer = activeWindow.setTimeout(() => {
  8148. this.settingsList = [];
  8149. this.errorList = [];
  8150. // remove registered theme commands (sadly undocumented API)
  8151. for (const command of this.commandList) {
  8152. // @ts-ignore
  8153. this.app.commands.removeCommand(command.id);
  8154. }
  8155. this.commandList = [];
  8156. this.settingsManager.removeClasses();
  8157. const styleSheets = document.styleSheets;
  8158. for (let i = 0, len = styleSheets.length; i < len; i++) {
  8159. const sheet = styleSheets.item(i);
  8160. this.parseCSSStyleSheet(sheet);
  8161. }
  8162. // compatability with Settings Search Plugin
  8163. this.registerSettingsToSettingsSearch();
  8164. this.settingsTab.setSettings(this.settingsList, this.errorList);
  8165. this.app.workspace.getLeavesOfType(viewType).forEach((leaf) => {
  8166. leaf.view.setSettings(this.settingsList, this.errorList);
  8167. });
  8168. this.settingsManager.setConfig(this.settingsList);
  8169. this.settingsManager.initClasses();
  8170. this.registerSettingCommands();
  8171. }, 100);
  8172. }
  8173. /**
  8174. * Registers the current settings to the settings search plugin.
  8175. * It also unregisters the old settings.
  8176. *
  8177. * @private
  8178. */
  8179. registerSettingsToSettingsSearch() {
  8180. var _a;
  8181. const onSettingsSearchLoaded = () => {
  8182. if (window.SettingsSearch) {
  8183. const settingsSearch = window.SettingsSearch;
  8184. settingsSearch.removeTabResources('obsidian-style-settings');
  8185. for (const parsedCSSSetting of this.settingsList) {
  8186. settingsSearch.addResources(...parsedCSSSetting.settings.map((x) => {
  8187. var _a, _b;
  8188. const settingsSearchResource = {
  8189. tab: 'obsidian-style-settings',
  8190. name: 'Style Settings',
  8191. text: (_a = getTitle(x)) !== null && _a !== void 0 ? _a : '',
  8192. desc: (_b = getDescription(x)) !== null && _b !== void 0 ? _b : '',
  8193. };
  8194. return settingsSearchResource;
  8195. }));
  8196. }
  8197. }
  8198. };
  8199. // @ts-ignore TODO: expand obsidian types, so that the ts-ignore is not needed
  8200. if ((_a = this.app.plugins.plugins['settings-search']) === null || _a === void 0 ? void 0 : _a.loaded) {
  8201. onSettingsSearchLoaded();
  8202. }
  8203. else {
  8204. // @ts-ignore
  8205. this.app.workspace.on('settings-search-loaded', () => {
  8206. onSettingsSearchLoaded();
  8207. });
  8208. }
  8209. }
  8210. /**
  8211. * Remove any settings from settings search if settings search is loaded.
  8212. *
  8213. * @private
  8214. */
  8215. unregisterSettingsFromSettingsSearch() {
  8216. var _a;
  8217. // @ts-ignore TODO: expand obsidian types, so that the ts-ignore is not needed
  8218. if ((_a = this.app.plugins.plugins['settings-search']) === null || _a === void 0 ? void 0 : _a.loaded) {
  8219. // @ts-ignore
  8220. window.SettingsSearch.removeTabResources('obsidian-style-settings');
  8221. }
  8222. }
  8223. /**
  8224. * Parses the settings from a css style sheet.
  8225. * Adds the parsed settings to `settingsList` and any errors to `errorList`.
  8226. *
  8227. * @param sheet the stylesheet to parse
  8228. * @private
  8229. */
  8230. parseCSSStyleSheet(sheet) {
  8231. const text = sheet.ownerNode.textContent.trim();
  8232. let match = settingRegExp.exec(text);
  8233. if (match && match.length) {
  8234. do {
  8235. const nameMatch = text.match(nameRegExp);
  8236. const name = nameMatch ? nameMatch[1] : undefined;
  8237. try {
  8238. const str = match[1].trim();
  8239. const settings = this.parseCSSSettings(str, name);
  8240. if (settings &&
  8241. typeof settings === 'object' &&
  8242. settings.name &&
  8243. settings.id &&
  8244. settings.settings &&
  8245. settings.settings.length) {
  8246. this.settingsList.push(settings);
  8247. }
  8248. }
  8249. catch (e) {
  8250. this.errorList.push({ name, error: `${e}` });
  8251. }
  8252. } while ((match = settingRegExp.exec(text)) !== null);
  8253. }
  8254. }
  8255. /**
  8256. * Parse css settings from a string.
  8257. *
  8258. * @param str the stringified settings to parse
  8259. * @param name the name of the file
  8260. * @private
  8261. */
  8262. parseCSSSettings(str, name) {
  8263. const indent = detectIndent(str);
  8264. const settings = jsYaml.load(str.replace(/\t/g, indent.type === 'space' ? indent.indent : ' '), {
  8265. filename: name,
  8266. });
  8267. if (!settings.settings)
  8268. return undefined;
  8269. settings.settings = settings.settings.filter((setting) => setting);
  8270. return settings;
  8271. }
  8272. registerSettingCommands() {
  8273. for (const section of this.settingsList) {
  8274. for (const setting of section.settings) {
  8275. if (setting.type === SettingType.CLASS_TOGGLE &&
  8276. setting.addCommand) {
  8277. this.addClassToggleCommand(section, setting);
  8278. }
  8279. }
  8280. }
  8281. }
  8282. addClassToggleCommand(section, setting) {
  8283. this.commandList.push(this.addCommand({
  8284. id: `style-settings-class-toggle-${section.id}-${setting.id}`,
  8285. name: `Toggle ${setting.title}`,
  8286. callback: () => {
  8287. const value = !this.settingsManager.getSetting(section.id, setting.id);
  8288. this.settingsManager.setSetting(section.id, setting.id, value);
  8289. this.settingsTab.rerender();
  8290. for (const leaf of this.app.workspace.getLeavesOfType(viewType)) {
  8291. leaf.view.rerender();
  8292. }
  8293. },
  8294. }));
  8295. }
  8296. onunload() {
  8297. this.lightEl.remove();
  8298. this.darkEl.remove();
  8299. this.lightEl = null;
  8300. this.darkEl = null;
  8301. document.body.classList.remove('css-settings-manager');
  8302. this.settingsManager.cleanup();
  8303. this.deactivateView();
  8304. this.unregisterSettingsFromSettingsSearch();
  8305. }
  8306. deactivateView() {
  8307. this.app.workspace.detachLeavesOfType(viewType);
  8308. }
  8309. activateView() {
  8310. return __awaiter(this, void 0, void 0, function* () {
  8311. this.deactivateView();
  8312. const leaf = this.app.workspace.getLeaf('tab');
  8313. yield leaf.setViewState({
  8314. type: viewType,
  8315. active: true,
  8316. });
  8317. leaf.view.setSettings(this.settingsList, this.errorList);
  8318. });
  8319. }
  8320. }
  8321. module.exports = CSSSettingsPlugin;