main.js 291 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902
  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. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  29. function getDefaultExportFromCjs (x) {
  30. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  31. }
  32. function createCommonjsModule(fn, basedir, module) {
  33. return module = {
  34. path: basedir,
  35. exports: {},
  36. require: function (path, base) {
  37. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  38. }
  39. }, fn(module, module.exports), module.exports;
  40. }
  41. function commonjsRequire () {
  42. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  43. }
  44. var chroma = createCommonjsModule(function (module, exports) {
  45. /**
  46. * chroma.js - JavaScript library for color conversions
  47. *
  48. * Copyright (c) 2011-2019, Gregor Aisch
  49. * All rights reserved.
  50. *
  51. * Redistribution and use in source and binary forms, with or without
  52. * modification, are permitted provided that the following conditions are met:
  53. *
  54. * 1. Redistributions of source code must retain the above copyright notice, this
  55. * list of conditions and the following disclaimer.
  56. *
  57. * 2. Redistributions in binary form must reproduce the above copyright notice,
  58. * this list of conditions and the following disclaimer in the documentation
  59. * and/or other materials provided with the distribution.
  60. *
  61. * 3. The name Gregor Aisch may not be used to endorse or promote products
  62. * derived from this software without specific prior written permission.
  63. *
  64. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  65. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  66. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  67. * DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  68. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  69. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  70. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  71. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  72. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  73. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  74. *
  75. * -------------------------------------------------------
  76. *
  77. * chroma.js includes colors from colorbrewer2.org, which are released under
  78. * the following license:
  79. *
  80. * Copyright (c) 2002 Cynthia Brewer, Mark Harrower,
  81. * and The Pennsylvania State University.
  82. *
  83. * Licensed under the Apache License, Version 2.0 (the "License");
  84. * you may not use this file except in compliance with the License.
  85. * You may obtain a copy of the License at
  86. * http://www.apache.org/licenses/LICENSE-2.0
  87. *
  88. * Unless required by applicable law or agreed to in writing,
  89. * software distributed under the License is distributed on an
  90. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  91. * either express or implied. See the License for the specific
  92. * language governing permissions and limitations under the License.
  93. *
  94. * ------------------------------------------------------
  95. *
  96. * Named colors are taken from X11 Color Names.
  97. * http://www.w3.org/TR/css3-color/#svg-color
  98. *
  99. * @preserve
  100. */
  101. (function (global, factory) {
  102. module.exports = factory() ;
  103. }(commonjsGlobal, (function () {
  104. var limit = function (x, min, max) {
  105. if ( min === void 0 ) min=0;
  106. if ( max === void 0 ) max=1;
  107. return x < min ? min : x > max ? max : x;
  108. };
  109. var clip_rgb = function (rgb) {
  110. rgb._clipped = false;
  111. rgb._unclipped = rgb.slice(0);
  112. for (var i=0; i<=3; i++) {
  113. if (i < 3) {
  114. if (rgb[i] < 0 || rgb[i] > 255) { rgb._clipped = true; }
  115. rgb[i] = limit(rgb[i], 0, 255);
  116. } else if (i === 3) {
  117. rgb[i] = limit(rgb[i], 0, 1);
  118. }
  119. }
  120. return rgb;
  121. };
  122. // ported from jQuery's $.type
  123. var classToType = {};
  124. for (var i = 0, list = ['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Undefined', 'Null']; i < list.length; i += 1) {
  125. var name = list[i];
  126. classToType[("[object " + name + "]")] = name.toLowerCase();
  127. }
  128. var type = function(obj) {
  129. return classToType[Object.prototype.toString.call(obj)] || "object";
  130. };
  131. var unpack = function (args, keyOrder) {
  132. if ( keyOrder === void 0 ) keyOrder=null;
  133. // if called with more than 3 arguments, we return the arguments
  134. if (args.length >= 3) { return Array.prototype.slice.call(args); }
  135. // with less than 3 args we check if first arg is object
  136. // and use the keyOrder string to extract and sort properties
  137. if (type(args[0]) == 'object' && keyOrder) {
  138. return keyOrder.split('')
  139. .filter(function (k) { return args[0][k] !== undefined; })
  140. .map(function (k) { return args[0][k]; });
  141. }
  142. // otherwise we just return the first argument
  143. // (which we suppose is an array of args)
  144. return args[0];
  145. };
  146. var last = function (args) {
  147. if (args.length < 2) { return null; }
  148. var l = args.length-1;
  149. if (type(args[l]) == 'string') { return args[l].toLowerCase(); }
  150. return null;
  151. };
  152. var PI = Math.PI;
  153. var utils = {
  154. clip_rgb: clip_rgb,
  155. limit: limit,
  156. type: type,
  157. unpack: unpack,
  158. last: last,
  159. PI: PI,
  160. TWOPI: PI*2,
  161. PITHIRD: PI/3,
  162. DEG2RAD: PI / 180,
  163. RAD2DEG: 180 / PI
  164. };
  165. var input = {
  166. format: {},
  167. autodetect: []
  168. };
  169. var last$1 = utils.last;
  170. var clip_rgb$1 = utils.clip_rgb;
  171. var type$1 = utils.type;
  172. var Color = function Color() {
  173. var args = [], len = arguments.length;
  174. while ( len-- ) args[ len ] = arguments[ len ];
  175. var me = this;
  176. if (type$1(args[0]) === 'object' &&
  177. args[0].constructor &&
  178. args[0].constructor === this.constructor) {
  179. // the argument is already a Color instance
  180. return args[0];
  181. }
  182. // last argument could be the mode
  183. var mode = last$1(args);
  184. var autodetect = false;
  185. if (!mode) {
  186. autodetect = true;
  187. if (!input.sorted) {
  188. input.autodetect = input.autodetect.sort(function (a,b) { return b.p - a.p; });
  189. input.sorted = true;
  190. }
  191. // auto-detect format
  192. for (var i = 0, list = input.autodetect; i < list.length; i += 1) {
  193. var chk = list[i];
  194. mode = chk.test.apply(chk, args);
  195. if (mode) { break; }
  196. }
  197. }
  198. if (input.format[mode]) {
  199. var rgb = input.format[mode].apply(null, autodetect ? args : args.slice(0,-1));
  200. me._rgb = clip_rgb$1(rgb);
  201. } else {
  202. throw new Error('unknown format: '+args);
  203. }
  204. // add alpha channel
  205. if (me._rgb.length === 3) { me._rgb.push(1); }
  206. };
  207. Color.prototype.toString = function toString () {
  208. if (type$1(this.hex) == 'function') { return this.hex(); }
  209. return ("[" + (this._rgb.join(',')) + "]");
  210. };
  211. var Color_1 = Color;
  212. var chroma = function () {
  213. var args = [], len = arguments.length;
  214. while ( len-- ) args[ len ] = arguments[ len ];
  215. return new (Function.prototype.bind.apply( chroma.Color, [ null ].concat( args) ));
  216. };
  217. chroma.Color = Color_1;
  218. chroma.version = '2.1.2';
  219. var chroma_1 = chroma;
  220. var unpack$1 = utils.unpack;
  221. var max = Math.max;
  222. var rgb2cmyk = function () {
  223. var args = [], len = arguments.length;
  224. while ( len-- ) args[ len ] = arguments[ len ];
  225. var ref = unpack$1(args, 'rgb');
  226. var r = ref[0];
  227. var g = ref[1];
  228. var b = ref[2];
  229. r = r / 255;
  230. g = g / 255;
  231. b = b / 255;
  232. var k = 1 - max(r,max(g,b));
  233. var f = k < 1 ? 1 / (1-k) : 0;
  234. var c = (1-r-k) * f;
  235. var m = (1-g-k) * f;
  236. var y = (1-b-k) * f;
  237. return [c,m,y,k];
  238. };
  239. var rgb2cmyk_1 = rgb2cmyk;
  240. var unpack$2 = utils.unpack;
  241. var cmyk2rgb = function () {
  242. var args = [], len = arguments.length;
  243. while ( len-- ) args[ len ] = arguments[ len ];
  244. args = unpack$2(args, 'cmyk');
  245. var c = args[0];
  246. var m = args[1];
  247. var y = args[2];
  248. var k = args[3];
  249. var alpha = args.length > 4 ? args[4] : 1;
  250. if (k === 1) { return [0,0,0,alpha]; }
  251. return [
  252. c >= 1 ? 0 : 255 * (1-c) * (1-k), // r
  253. m >= 1 ? 0 : 255 * (1-m) * (1-k), // g
  254. y >= 1 ? 0 : 255 * (1-y) * (1-k), // b
  255. alpha
  256. ];
  257. };
  258. var cmyk2rgb_1 = cmyk2rgb;
  259. var unpack$3 = utils.unpack;
  260. var type$2 = utils.type;
  261. Color_1.prototype.cmyk = function() {
  262. return rgb2cmyk_1(this._rgb);
  263. };
  264. chroma_1.cmyk = function () {
  265. var args = [], len = arguments.length;
  266. while ( len-- ) args[ len ] = arguments[ len ];
  267. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['cmyk']) ));
  268. };
  269. input.format.cmyk = cmyk2rgb_1;
  270. input.autodetect.push({
  271. p: 2,
  272. test: function () {
  273. var args = [], len = arguments.length;
  274. while ( len-- ) args[ len ] = arguments[ len ];
  275. args = unpack$3(args, 'cmyk');
  276. if (type$2(args) === 'array' && args.length === 4) {
  277. return 'cmyk';
  278. }
  279. }
  280. });
  281. var unpack$4 = utils.unpack;
  282. var last$2 = utils.last;
  283. var rnd = function (a) { return Math.round(a*100)/100; };
  284. /*
  285. * supported arguments:
  286. * - hsl2css(h,s,l)
  287. * - hsl2css(h,s,l,a)
  288. * - hsl2css([h,s,l], mode)
  289. * - hsl2css([h,s,l,a], mode)
  290. * - hsl2css({h,s,l,a}, mode)
  291. */
  292. var hsl2css = function () {
  293. var args = [], len = arguments.length;
  294. while ( len-- ) args[ len ] = arguments[ len ];
  295. var hsla = unpack$4(args, 'hsla');
  296. var mode = last$2(args) || 'lsa';
  297. hsla[0] = rnd(hsla[0] || 0);
  298. hsla[1] = rnd(hsla[1]*100) + '%';
  299. hsla[2] = rnd(hsla[2]*100) + '%';
  300. if (mode === 'hsla' || (hsla.length > 3 && hsla[3]<1)) {
  301. hsla[3] = hsla.length > 3 ? hsla[3] : 1;
  302. mode = 'hsla';
  303. } else {
  304. hsla.length = 3;
  305. }
  306. return (mode + "(" + (hsla.join(',')) + ")");
  307. };
  308. var hsl2css_1 = hsl2css;
  309. var unpack$5 = utils.unpack;
  310. /*
  311. * supported arguments:
  312. * - rgb2hsl(r,g,b)
  313. * - rgb2hsl(r,g,b,a)
  314. * - rgb2hsl([r,g,b])
  315. * - rgb2hsl([r,g,b,a])
  316. * - rgb2hsl({r,g,b,a})
  317. */
  318. var rgb2hsl = function () {
  319. var args = [], len = arguments.length;
  320. while ( len-- ) args[ len ] = arguments[ len ];
  321. args = unpack$5(args, 'rgba');
  322. var r = args[0];
  323. var g = args[1];
  324. var b = args[2];
  325. r /= 255;
  326. g /= 255;
  327. b /= 255;
  328. var min = Math.min(r, g, b);
  329. var max = Math.max(r, g, b);
  330. var l = (max + min) / 2;
  331. var s, h;
  332. if (max === min){
  333. s = 0;
  334. h = Number.NaN;
  335. } else {
  336. s = l < 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min);
  337. }
  338. if (r == max) { h = (g - b) / (max - min); }
  339. else if (g == max) { h = 2 + (b - r) / (max - min); }
  340. else if (b == max) { h = 4 + (r - g) / (max - min); }
  341. h *= 60;
  342. if (h < 0) { h += 360; }
  343. if (args.length>3 && args[3]!==undefined) { return [h,s,l,args[3]]; }
  344. return [h,s,l];
  345. };
  346. var rgb2hsl_1 = rgb2hsl;
  347. var unpack$6 = utils.unpack;
  348. var last$3 = utils.last;
  349. var round = Math.round;
  350. /*
  351. * supported arguments:
  352. * - rgb2css(r,g,b)
  353. * - rgb2css(r,g,b,a)
  354. * - rgb2css([r,g,b], mode)
  355. * - rgb2css([r,g,b,a], mode)
  356. * - rgb2css({r,g,b,a}, mode)
  357. */
  358. var rgb2css = function () {
  359. var args = [], len = arguments.length;
  360. while ( len-- ) args[ len ] = arguments[ len ];
  361. var rgba = unpack$6(args, 'rgba');
  362. var mode = last$3(args) || 'rgb';
  363. if (mode.substr(0,3) == 'hsl') {
  364. return hsl2css_1(rgb2hsl_1(rgba), mode);
  365. }
  366. rgba[0] = round(rgba[0]);
  367. rgba[1] = round(rgba[1]);
  368. rgba[2] = round(rgba[2]);
  369. if (mode === 'rgba' || (rgba.length > 3 && rgba[3]<1)) {
  370. rgba[3] = rgba.length > 3 ? rgba[3] : 1;
  371. mode = 'rgba';
  372. }
  373. return (mode + "(" + (rgba.slice(0,mode==='rgb'?3:4).join(',')) + ")");
  374. };
  375. var rgb2css_1 = rgb2css;
  376. var unpack$7 = utils.unpack;
  377. var round$1 = Math.round;
  378. var hsl2rgb = function () {
  379. var assign;
  380. var args = [], len = arguments.length;
  381. while ( len-- ) args[ len ] = arguments[ len ];
  382. args = unpack$7(args, 'hsl');
  383. var h = args[0];
  384. var s = args[1];
  385. var l = args[2];
  386. var r,g,b;
  387. if (s === 0) {
  388. r = g = b = l*255;
  389. } else {
  390. var t3 = [0,0,0];
  391. var c = [0,0,0];
  392. var t2 = l < 0.5 ? l * (1+s) : l+s-l*s;
  393. var t1 = 2 * l - t2;
  394. var h_ = h / 360;
  395. t3[0] = h_ + 1/3;
  396. t3[1] = h_;
  397. t3[2] = h_ - 1/3;
  398. for (var i=0; i<3; i++) {
  399. if (t3[i] < 0) { t3[i] += 1; }
  400. if (t3[i] > 1) { t3[i] -= 1; }
  401. if (6 * t3[i] < 1)
  402. { c[i] = t1 + (t2 - t1) * 6 * t3[i]; }
  403. else if (2 * t3[i] < 1)
  404. { c[i] = t2; }
  405. else if (3 * t3[i] < 2)
  406. { c[i] = t1 + (t2 - t1) * ((2 / 3) - t3[i]) * 6; }
  407. else
  408. { c[i] = t1; }
  409. }
  410. (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]);
  411. }
  412. if (args.length > 3) {
  413. // keep alpha channel
  414. return [r,g,b,args[3]];
  415. }
  416. return [r,g,b,1];
  417. };
  418. var hsl2rgb_1 = hsl2rgb;
  419. var RE_RGB = /^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/;
  420. var RE_RGBA = /^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/;
  421. var RE_RGB_PCT = /^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/;
  422. var RE_RGBA_PCT = /^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/;
  423. var RE_HSL = /^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/;
  424. var RE_HSLA = /^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/;
  425. var round$2 = Math.round;
  426. var css2rgb = function (css) {
  427. css = css.toLowerCase().trim();
  428. var m;
  429. if (input.format.named) {
  430. try {
  431. return input.format.named(css);
  432. } catch (e) {
  433. // eslint-disable-next-line
  434. }
  435. }
  436. // rgb(250,20,0)
  437. if ((m = css.match(RE_RGB))) {
  438. var rgb = m.slice(1,4);
  439. for (var i=0; i<3; i++) {
  440. rgb[i] = +rgb[i];
  441. }
  442. rgb[3] = 1; // default alpha
  443. return rgb;
  444. }
  445. // rgba(250,20,0,0.4)
  446. if ((m = css.match(RE_RGBA))) {
  447. var rgb$1 = m.slice(1,5);
  448. for (var i$1=0; i$1<4; i$1++) {
  449. rgb$1[i$1] = +rgb$1[i$1];
  450. }
  451. return rgb$1;
  452. }
  453. // rgb(100%,0%,0%)
  454. if ((m = css.match(RE_RGB_PCT))) {
  455. var rgb$2 = m.slice(1,4);
  456. for (var i$2=0; i$2<3; i$2++) {
  457. rgb$2[i$2] = round$2(rgb$2[i$2] * 2.55);
  458. }
  459. rgb$2[3] = 1; // default alpha
  460. return rgb$2;
  461. }
  462. // rgba(100%,0%,0%,0.4)
  463. if ((m = css.match(RE_RGBA_PCT))) {
  464. var rgb$3 = m.slice(1,5);
  465. for (var i$3=0; i$3<3; i$3++) {
  466. rgb$3[i$3] = round$2(rgb$3[i$3] * 2.55);
  467. }
  468. rgb$3[3] = +rgb$3[3];
  469. return rgb$3;
  470. }
  471. // hsl(0,100%,50%)
  472. if ((m = css.match(RE_HSL))) {
  473. var hsl = m.slice(1,4);
  474. hsl[1] *= 0.01;
  475. hsl[2] *= 0.01;
  476. var rgb$4 = hsl2rgb_1(hsl);
  477. rgb$4[3] = 1;
  478. return rgb$4;
  479. }
  480. // hsla(0,100%,50%,0.5)
  481. if ((m = css.match(RE_HSLA))) {
  482. var hsl$1 = m.slice(1,4);
  483. hsl$1[1] *= 0.01;
  484. hsl$1[2] *= 0.01;
  485. var rgb$5 = hsl2rgb_1(hsl$1);
  486. rgb$5[3] = +m[4]; // default alpha = 1
  487. return rgb$5;
  488. }
  489. };
  490. css2rgb.test = function (s) {
  491. return RE_RGB.test(s) ||
  492. RE_RGBA.test(s) ||
  493. RE_RGB_PCT.test(s) ||
  494. RE_RGBA_PCT.test(s) ||
  495. RE_HSL.test(s) ||
  496. RE_HSLA.test(s);
  497. };
  498. var css2rgb_1 = css2rgb;
  499. var type$3 = utils.type;
  500. Color_1.prototype.css = function(mode) {
  501. return rgb2css_1(this._rgb, mode);
  502. };
  503. chroma_1.css = function () {
  504. var args = [], len = arguments.length;
  505. while ( len-- ) args[ len ] = arguments[ len ];
  506. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['css']) ));
  507. };
  508. input.format.css = css2rgb_1;
  509. input.autodetect.push({
  510. p: 5,
  511. test: function (h) {
  512. var rest = [], len = arguments.length - 1;
  513. while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ];
  514. if (!rest.length && type$3(h) === 'string' && css2rgb_1.test(h)) {
  515. return 'css';
  516. }
  517. }
  518. });
  519. var unpack$8 = utils.unpack;
  520. input.format.gl = function () {
  521. var args = [], len = arguments.length;
  522. while ( len-- ) args[ len ] = arguments[ len ];
  523. var rgb = unpack$8(args, 'rgba');
  524. rgb[0] *= 255;
  525. rgb[1] *= 255;
  526. rgb[2] *= 255;
  527. return rgb;
  528. };
  529. chroma_1.gl = function () {
  530. var args = [], len = arguments.length;
  531. while ( len-- ) args[ len ] = arguments[ len ];
  532. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['gl']) ));
  533. };
  534. Color_1.prototype.gl = function() {
  535. var rgb = this._rgb;
  536. return [rgb[0]/255, rgb[1]/255, rgb[2]/255, rgb[3]];
  537. };
  538. var unpack$9 = utils.unpack;
  539. var rgb2hcg = function () {
  540. var args = [], len = arguments.length;
  541. while ( len-- ) args[ len ] = arguments[ len ];
  542. var ref = unpack$9(args, 'rgb');
  543. var r = ref[0];
  544. var g = ref[1];
  545. var b = ref[2];
  546. var min = Math.min(r, g, b);
  547. var max = Math.max(r, g, b);
  548. var delta = max - min;
  549. var c = delta * 100 / 255;
  550. var _g = min / (255 - delta) * 100;
  551. var h;
  552. if (delta === 0) {
  553. h = Number.NaN;
  554. } else {
  555. if (r === max) { h = (g - b) / delta; }
  556. if (g === max) { h = 2+(b - r) / delta; }
  557. if (b === max) { h = 4+(r - g) / delta; }
  558. h *= 60;
  559. if (h < 0) { h += 360; }
  560. }
  561. return [h, c, _g];
  562. };
  563. var rgb2hcg_1 = rgb2hcg;
  564. var unpack$a = utils.unpack;
  565. var floor = Math.floor;
  566. /*
  567. * this is basically just HSV with some minor tweaks
  568. *
  569. * hue.. [0..360]
  570. * chroma .. [0..1]
  571. * grayness .. [0..1]
  572. */
  573. var hcg2rgb = function () {
  574. var assign, assign$1, assign$2, assign$3, assign$4, assign$5;
  575. var args = [], len = arguments.length;
  576. while ( len-- ) args[ len ] = arguments[ len ];
  577. args = unpack$a(args, 'hcg');
  578. var h = args[0];
  579. var c = args[1];
  580. var _g = args[2];
  581. var r,g,b;
  582. _g = _g * 255;
  583. var _c = c * 255;
  584. if (c === 0) {
  585. r = g = b = _g;
  586. } else {
  587. if (h === 360) { h = 0; }
  588. if (h > 360) { h -= 360; }
  589. if (h < 0) { h += 360; }
  590. h /= 60;
  591. var i = floor(h);
  592. var f = h - i;
  593. var p = _g * (1 - c);
  594. var q = p + _c * (1 - f);
  595. var t = p + _c * f;
  596. var v = p + _c;
  597. switch (i) {
  598. case 0: (assign = [v, t, p], r = assign[0], g = assign[1], b = assign[2]); break
  599. case 1: (assign$1 = [q, v, p], r = assign$1[0], g = assign$1[1], b = assign$1[2]); break
  600. case 2: (assign$2 = [p, v, t], r = assign$2[0], g = assign$2[1], b = assign$2[2]); break
  601. case 3: (assign$3 = [p, q, v], r = assign$3[0], g = assign$3[1], b = assign$3[2]); break
  602. case 4: (assign$4 = [t, p, v], r = assign$4[0], g = assign$4[1], b = assign$4[2]); break
  603. case 5: (assign$5 = [v, p, q], r = assign$5[0], g = assign$5[1], b = assign$5[2]); break
  604. }
  605. }
  606. return [r, g, b, args.length > 3 ? args[3] : 1];
  607. };
  608. var hcg2rgb_1 = hcg2rgb;
  609. var unpack$b = utils.unpack;
  610. var type$4 = utils.type;
  611. Color_1.prototype.hcg = function() {
  612. return rgb2hcg_1(this._rgb);
  613. };
  614. chroma_1.hcg = function () {
  615. var args = [], len = arguments.length;
  616. while ( len-- ) args[ len ] = arguments[ len ];
  617. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hcg']) ));
  618. };
  619. input.format.hcg = hcg2rgb_1;
  620. input.autodetect.push({
  621. p: 1,
  622. test: function () {
  623. var args = [], len = arguments.length;
  624. while ( len-- ) args[ len ] = arguments[ len ];
  625. args = unpack$b(args, 'hcg');
  626. if (type$4(args) === 'array' && args.length === 3) {
  627. return 'hcg';
  628. }
  629. }
  630. });
  631. var unpack$c = utils.unpack;
  632. var last$4 = utils.last;
  633. var round$3 = Math.round;
  634. var rgb2hex = function () {
  635. var args = [], len = arguments.length;
  636. while ( len-- ) args[ len ] = arguments[ len ];
  637. var ref = unpack$c(args, 'rgba');
  638. var r = ref[0];
  639. var g = ref[1];
  640. var b = ref[2];
  641. var a = ref[3];
  642. var mode = last$4(args) || 'auto';
  643. if (a === undefined) { a = 1; }
  644. if (mode === 'auto') {
  645. mode = a < 1 ? 'rgba' : 'rgb';
  646. }
  647. r = round$3(r);
  648. g = round$3(g);
  649. b = round$3(b);
  650. var u = r << 16 | g << 8 | b;
  651. var str = "000000" + u.toString(16); //#.toUpperCase();
  652. str = str.substr(str.length - 6);
  653. var hxa = '0' + round$3(a * 255).toString(16);
  654. hxa = hxa.substr(hxa.length - 2);
  655. switch (mode.toLowerCase()) {
  656. case 'rgba': return ("#" + str + hxa);
  657. case 'argb': return ("#" + hxa + str);
  658. default: return ("#" + str);
  659. }
  660. };
  661. var rgb2hex_1 = rgb2hex;
  662. var RE_HEX = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  663. var RE_HEXA = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/;
  664. var hex2rgb = function (hex) {
  665. if (hex.match(RE_HEX)) {
  666. // remove optional leading #
  667. if (hex.length === 4 || hex.length === 7) {
  668. hex = hex.substr(1);
  669. }
  670. // expand short-notation to full six-digit
  671. if (hex.length === 3) {
  672. hex = hex.split('');
  673. hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  674. }
  675. var u = parseInt(hex, 16);
  676. var r = u >> 16;
  677. var g = u >> 8 & 0xFF;
  678. var b = u & 0xFF;
  679. return [r,g,b,1];
  680. }
  681. // match rgba hex format, eg #FF000077
  682. if (hex.match(RE_HEXA)) {
  683. if (hex.length === 5 || hex.length === 9) {
  684. // remove optional leading #
  685. hex = hex.substr(1);
  686. }
  687. // expand short-notation to full eight-digit
  688. if (hex.length === 4) {
  689. hex = hex.split('');
  690. hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]+hex[3]+hex[3];
  691. }
  692. var u$1 = parseInt(hex, 16);
  693. var r$1 = u$1 >> 24 & 0xFF;
  694. var g$1 = u$1 >> 16 & 0xFF;
  695. var b$1 = u$1 >> 8 & 0xFF;
  696. var a = Math.round((u$1 & 0xFF) / 0xFF * 100) / 100;
  697. return [r$1,g$1,b$1,a];
  698. }
  699. // we used to check for css colors here
  700. // if _input.css? and rgb = _input.css hex
  701. // return rgb
  702. throw new Error(("unknown hex color: " + hex));
  703. };
  704. var hex2rgb_1 = hex2rgb;
  705. var type$5 = utils.type;
  706. Color_1.prototype.hex = function(mode) {
  707. return rgb2hex_1(this._rgb, mode);
  708. };
  709. chroma_1.hex = function () {
  710. var args = [], len = arguments.length;
  711. while ( len-- ) args[ len ] = arguments[ len ];
  712. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hex']) ));
  713. };
  714. input.format.hex = hex2rgb_1;
  715. input.autodetect.push({
  716. p: 4,
  717. test: function (h) {
  718. var rest = [], len = arguments.length - 1;
  719. while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ];
  720. if (!rest.length && type$5(h) === 'string' && [3,4,5,6,7,8,9].indexOf(h.length) >= 0) {
  721. return 'hex';
  722. }
  723. }
  724. });
  725. var unpack$d = utils.unpack;
  726. var TWOPI = utils.TWOPI;
  727. var min = Math.min;
  728. var sqrt = Math.sqrt;
  729. var acos = Math.acos;
  730. var rgb2hsi = function () {
  731. var args = [], len = arguments.length;
  732. while ( len-- ) args[ len ] = arguments[ len ];
  733. /*
  734. borrowed from here:
  735. http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/rgb2hsi.cpp
  736. */
  737. var ref = unpack$d(args, 'rgb');
  738. var r = ref[0];
  739. var g = ref[1];
  740. var b = ref[2];
  741. r /= 255;
  742. g /= 255;
  743. b /= 255;
  744. var h;
  745. var min_ = min(r,g,b);
  746. var i = (r+g+b) / 3;
  747. var s = i > 0 ? 1 - min_/i : 0;
  748. if (s === 0) {
  749. h = NaN;
  750. } else {
  751. h = ((r-g)+(r-b)) / 2;
  752. h /= sqrt((r-g)*(r-g) + (r-b)*(g-b));
  753. h = acos(h);
  754. if (b > g) {
  755. h = TWOPI - h;
  756. }
  757. h /= TWOPI;
  758. }
  759. return [h*360,s,i];
  760. };
  761. var rgb2hsi_1 = rgb2hsi;
  762. var unpack$e = utils.unpack;
  763. var limit$1 = utils.limit;
  764. var TWOPI$1 = utils.TWOPI;
  765. var PITHIRD = utils.PITHIRD;
  766. var cos = Math.cos;
  767. /*
  768. * hue [0..360]
  769. * saturation [0..1]
  770. * intensity [0..1]
  771. */
  772. var hsi2rgb = function () {
  773. var args = [], len = arguments.length;
  774. while ( len-- ) args[ len ] = arguments[ len ];
  775. /*
  776. borrowed from here:
  777. http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/hsi2rgb.cpp
  778. */
  779. args = unpack$e(args, 'hsi');
  780. var h = args[0];
  781. var s = args[1];
  782. var i = args[2];
  783. var r,g,b;
  784. if (isNaN(h)) { h = 0; }
  785. if (isNaN(s)) { s = 0; }
  786. // normalize hue
  787. if (h > 360) { h -= 360; }
  788. if (h < 0) { h += 360; }
  789. h /= 360;
  790. if (h < 1/3) {
  791. b = (1-s)/3;
  792. r = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3;
  793. g = 1 - (b+r);
  794. } else if (h < 2/3) {
  795. h -= 1/3;
  796. r = (1-s)/3;
  797. g = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3;
  798. b = 1 - (r+g);
  799. } else {
  800. h -= 2/3;
  801. g = (1-s)/3;
  802. b = (1+s*cos(TWOPI$1*h)/cos(PITHIRD-TWOPI$1*h))/3;
  803. r = 1 - (g+b);
  804. }
  805. r = limit$1(i*r*3);
  806. g = limit$1(i*g*3);
  807. b = limit$1(i*b*3);
  808. return [r*255, g*255, b*255, args.length > 3 ? args[3] : 1];
  809. };
  810. var hsi2rgb_1 = hsi2rgb;
  811. var unpack$f = utils.unpack;
  812. var type$6 = utils.type;
  813. Color_1.prototype.hsi = function() {
  814. return rgb2hsi_1(this._rgb);
  815. };
  816. chroma_1.hsi = function () {
  817. var args = [], len = arguments.length;
  818. while ( len-- ) args[ len ] = arguments[ len ];
  819. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsi']) ));
  820. };
  821. input.format.hsi = hsi2rgb_1;
  822. input.autodetect.push({
  823. p: 2,
  824. test: function () {
  825. var args = [], len = arguments.length;
  826. while ( len-- ) args[ len ] = arguments[ len ];
  827. args = unpack$f(args, 'hsi');
  828. if (type$6(args) === 'array' && args.length === 3) {
  829. return 'hsi';
  830. }
  831. }
  832. });
  833. var unpack$g = utils.unpack;
  834. var type$7 = utils.type;
  835. Color_1.prototype.hsl = function() {
  836. return rgb2hsl_1(this._rgb);
  837. };
  838. chroma_1.hsl = function () {
  839. var args = [], len = arguments.length;
  840. while ( len-- ) args[ len ] = arguments[ len ];
  841. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsl']) ));
  842. };
  843. input.format.hsl = hsl2rgb_1;
  844. input.autodetect.push({
  845. p: 2,
  846. test: function () {
  847. var args = [], len = arguments.length;
  848. while ( len-- ) args[ len ] = arguments[ len ];
  849. args = unpack$g(args, 'hsl');
  850. if (type$7(args) === 'array' && args.length === 3) {
  851. return 'hsl';
  852. }
  853. }
  854. });
  855. var unpack$h = utils.unpack;
  856. var min$1 = Math.min;
  857. var max$1 = Math.max;
  858. /*
  859. * supported arguments:
  860. * - rgb2hsv(r,g,b)
  861. * - rgb2hsv([r,g,b])
  862. * - rgb2hsv({r,g,b})
  863. */
  864. var rgb2hsl$1 = function () {
  865. var args = [], len = arguments.length;
  866. while ( len-- ) args[ len ] = arguments[ len ];
  867. args = unpack$h(args, 'rgb');
  868. var r = args[0];
  869. var g = args[1];
  870. var b = args[2];
  871. var min_ = min$1(r, g, b);
  872. var max_ = max$1(r, g, b);
  873. var delta = max_ - min_;
  874. var h,s,v;
  875. v = max_ / 255.0;
  876. if (max_ === 0) {
  877. h = Number.NaN;
  878. s = 0;
  879. } else {
  880. s = delta / max_;
  881. if (r === max_) { h = (g - b) / delta; }
  882. if (g === max_) { h = 2+(b - r) / delta; }
  883. if (b === max_) { h = 4+(r - g) / delta; }
  884. h *= 60;
  885. if (h < 0) { h += 360; }
  886. }
  887. return [h, s, v]
  888. };
  889. var rgb2hsv = rgb2hsl$1;
  890. var unpack$i = utils.unpack;
  891. var floor$1 = Math.floor;
  892. var hsv2rgb = function () {
  893. var assign, assign$1, assign$2, assign$3, assign$4, assign$5;
  894. var args = [], len = arguments.length;
  895. while ( len-- ) args[ len ] = arguments[ len ];
  896. args = unpack$i(args, 'hsv');
  897. var h = args[0];
  898. var s = args[1];
  899. var v = args[2];
  900. var r,g,b;
  901. v *= 255;
  902. if (s === 0) {
  903. r = g = b = v;
  904. } else {
  905. if (h === 360) { h = 0; }
  906. if (h > 360) { h -= 360; }
  907. if (h < 0) { h += 360; }
  908. h /= 60;
  909. var i = floor$1(h);
  910. var f = h - i;
  911. var p = v * (1 - s);
  912. var q = v * (1 - s * f);
  913. var t = v * (1 - s * (1 - f));
  914. switch (i) {
  915. case 0: (assign = [v, t, p], r = assign[0], g = assign[1], b = assign[2]); break
  916. case 1: (assign$1 = [q, v, p], r = assign$1[0], g = assign$1[1], b = assign$1[2]); break
  917. case 2: (assign$2 = [p, v, t], r = assign$2[0], g = assign$2[1], b = assign$2[2]); break
  918. case 3: (assign$3 = [p, q, v], r = assign$3[0], g = assign$3[1], b = assign$3[2]); break
  919. case 4: (assign$4 = [t, p, v], r = assign$4[0], g = assign$4[1], b = assign$4[2]); break
  920. case 5: (assign$5 = [v, p, q], r = assign$5[0], g = assign$5[1], b = assign$5[2]); break
  921. }
  922. }
  923. return [r,g,b,args.length > 3?args[3]:1];
  924. };
  925. var hsv2rgb_1 = hsv2rgb;
  926. var unpack$j = utils.unpack;
  927. var type$8 = utils.type;
  928. Color_1.prototype.hsv = function() {
  929. return rgb2hsv(this._rgb);
  930. };
  931. chroma_1.hsv = function () {
  932. var args = [], len = arguments.length;
  933. while ( len-- ) args[ len ] = arguments[ len ];
  934. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hsv']) ));
  935. };
  936. input.format.hsv = hsv2rgb_1;
  937. input.autodetect.push({
  938. p: 2,
  939. test: function () {
  940. var args = [], len = arguments.length;
  941. while ( len-- ) args[ len ] = arguments[ len ];
  942. args = unpack$j(args, 'hsv');
  943. if (type$8(args) === 'array' && args.length === 3) {
  944. return 'hsv';
  945. }
  946. }
  947. });
  948. var labConstants = {
  949. // Corresponds roughly to RGB brighter/darker
  950. Kn: 18,
  951. // D65 standard referent
  952. Xn: 0.950470,
  953. Yn: 1,
  954. Zn: 1.088830,
  955. t0: 0.137931034, // 4 / 29
  956. t1: 0.206896552, // 6 / 29
  957. t2: 0.12841855, // 3 * t1 * t1
  958. t3: 0.008856452, // t1 * t1 * t1
  959. };
  960. var unpack$k = utils.unpack;
  961. var pow = Math.pow;
  962. var rgb2lab = function () {
  963. var args = [], len = arguments.length;
  964. while ( len-- ) args[ len ] = arguments[ len ];
  965. var ref = unpack$k(args, 'rgb');
  966. var r = ref[0];
  967. var g = ref[1];
  968. var b = ref[2];
  969. var ref$1 = rgb2xyz(r,g,b);
  970. var x = ref$1[0];
  971. var y = ref$1[1];
  972. var z = ref$1[2];
  973. var l = 116 * y - 16;
  974. return [l < 0 ? 0 : l, 500 * (x - y), 200 * (y - z)];
  975. };
  976. var rgb_xyz = function (r) {
  977. if ((r /= 255) <= 0.04045) { return r / 12.92; }
  978. return pow((r + 0.055) / 1.055, 2.4);
  979. };
  980. var xyz_lab = function (t) {
  981. if (t > labConstants.t3) { return pow(t, 1 / 3); }
  982. return t / labConstants.t2 + labConstants.t0;
  983. };
  984. var rgb2xyz = function (r,g,b) {
  985. r = rgb_xyz(r);
  986. g = rgb_xyz(g);
  987. b = rgb_xyz(b);
  988. var x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / labConstants.Xn);
  989. var y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / labConstants.Yn);
  990. var z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / labConstants.Zn);
  991. return [x,y,z];
  992. };
  993. var rgb2lab_1 = rgb2lab;
  994. var unpack$l = utils.unpack;
  995. var pow$1 = Math.pow;
  996. /*
  997. * L* [0..100]
  998. * a [-100..100]
  999. * b [-100..100]
  1000. */
  1001. var lab2rgb = function () {
  1002. var args = [], len = arguments.length;
  1003. while ( len-- ) args[ len ] = arguments[ len ];
  1004. args = unpack$l(args, 'lab');
  1005. var l = args[0];
  1006. var a = args[1];
  1007. var b = args[2];
  1008. var x,y,z, r,g,b_;
  1009. y = (l + 16) / 116;
  1010. x = isNaN(a) ? y : y + a / 500;
  1011. z = isNaN(b) ? y : y - b / 200;
  1012. y = labConstants.Yn * lab_xyz(y);
  1013. x = labConstants.Xn * lab_xyz(x);
  1014. z = labConstants.Zn * lab_xyz(z);
  1015. r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z); // D65 -> sRGB
  1016. g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
  1017. b_ = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
  1018. return [r,g,b_,args.length > 3 ? args[3] : 1];
  1019. };
  1020. var xyz_rgb = function (r) {
  1021. return 255 * (r <= 0.00304 ? 12.92 * r : 1.055 * pow$1(r, 1 / 2.4) - 0.055)
  1022. };
  1023. var lab_xyz = function (t) {
  1024. return t > labConstants.t1 ? t * t * t : labConstants.t2 * (t - labConstants.t0)
  1025. };
  1026. var lab2rgb_1 = lab2rgb;
  1027. var unpack$m = utils.unpack;
  1028. var type$9 = utils.type;
  1029. Color_1.prototype.lab = function() {
  1030. return rgb2lab_1(this._rgb);
  1031. };
  1032. chroma_1.lab = function () {
  1033. var args = [], len = arguments.length;
  1034. while ( len-- ) args[ len ] = arguments[ len ];
  1035. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['lab']) ));
  1036. };
  1037. input.format.lab = lab2rgb_1;
  1038. input.autodetect.push({
  1039. p: 2,
  1040. test: function () {
  1041. var args = [], len = arguments.length;
  1042. while ( len-- ) args[ len ] = arguments[ len ];
  1043. args = unpack$m(args, 'lab');
  1044. if (type$9(args) === 'array' && args.length === 3) {
  1045. return 'lab';
  1046. }
  1047. }
  1048. });
  1049. var unpack$n = utils.unpack;
  1050. var RAD2DEG = utils.RAD2DEG;
  1051. var sqrt$1 = Math.sqrt;
  1052. var atan2 = Math.atan2;
  1053. var round$4 = Math.round;
  1054. var lab2lch = function () {
  1055. var args = [], len = arguments.length;
  1056. while ( len-- ) args[ len ] = arguments[ len ];
  1057. var ref = unpack$n(args, 'lab');
  1058. var l = ref[0];
  1059. var a = ref[1];
  1060. var b = ref[2];
  1061. var c = sqrt$1(a * a + b * b);
  1062. var h = (atan2(b, a) * RAD2DEG + 360) % 360;
  1063. if (round$4(c*10000) === 0) { h = Number.NaN; }
  1064. return [l, c, h];
  1065. };
  1066. var lab2lch_1 = lab2lch;
  1067. var unpack$o = utils.unpack;
  1068. var rgb2lch = function () {
  1069. var args = [], len = arguments.length;
  1070. while ( len-- ) args[ len ] = arguments[ len ];
  1071. var ref = unpack$o(args, 'rgb');
  1072. var r = ref[0];
  1073. var g = ref[1];
  1074. var b = ref[2];
  1075. var ref$1 = rgb2lab_1(r,g,b);
  1076. var l = ref$1[0];
  1077. var a = ref$1[1];
  1078. var b_ = ref$1[2];
  1079. return lab2lch_1(l,a,b_);
  1080. };
  1081. var rgb2lch_1 = rgb2lch;
  1082. var unpack$p = utils.unpack;
  1083. var DEG2RAD = utils.DEG2RAD;
  1084. var sin = Math.sin;
  1085. var cos$1 = Math.cos;
  1086. var lch2lab = function () {
  1087. var args = [], len = arguments.length;
  1088. while ( len-- ) args[ len ] = arguments[ len ];
  1089. /*
  1090. Convert from a qualitative parameter h and a quantitative parameter l to a 24-bit pixel.
  1091. These formulas were invented by David Dalrymple to obtain maximum contrast without going
  1092. out of gamut if the parameters are in the range 0-1.
  1093. A saturation multiplier was added by Gregor Aisch
  1094. */
  1095. var ref = unpack$p(args, 'lch');
  1096. var l = ref[0];
  1097. var c = ref[1];
  1098. var h = ref[2];
  1099. if (isNaN(h)) { h = 0; }
  1100. h = h * DEG2RAD;
  1101. return [l, cos$1(h) * c, sin(h) * c]
  1102. };
  1103. var lch2lab_1 = lch2lab;
  1104. var unpack$q = utils.unpack;
  1105. var lch2rgb = function () {
  1106. var args = [], len = arguments.length;
  1107. while ( len-- ) args[ len ] = arguments[ len ];
  1108. args = unpack$q(args, 'lch');
  1109. var l = args[0];
  1110. var c = args[1];
  1111. var h = args[2];
  1112. var ref = lch2lab_1 (l,c,h);
  1113. var L = ref[0];
  1114. var a = ref[1];
  1115. var b_ = ref[2];
  1116. var ref$1 = lab2rgb_1 (L,a,b_);
  1117. var r = ref$1[0];
  1118. var g = ref$1[1];
  1119. var b = ref$1[2];
  1120. return [r, g, b, args.length > 3 ? args[3] : 1];
  1121. };
  1122. var lch2rgb_1 = lch2rgb;
  1123. var unpack$r = utils.unpack;
  1124. var hcl2rgb = function () {
  1125. var args = [], len = arguments.length;
  1126. while ( len-- ) args[ len ] = arguments[ len ];
  1127. var hcl = unpack$r(args, 'hcl').reverse();
  1128. return lch2rgb_1.apply(void 0, hcl);
  1129. };
  1130. var hcl2rgb_1 = hcl2rgb;
  1131. var unpack$s = utils.unpack;
  1132. var type$a = utils.type;
  1133. Color_1.prototype.lch = function() { return rgb2lch_1(this._rgb); };
  1134. Color_1.prototype.hcl = function() { return rgb2lch_1(this._rgb).reverse(); };
  1135. chroma_1.lch = function () {
  1136. var args = [], len = arguments.length;
  1137. while ( len-- ) args[ len ] = arguments[ len ];
  1138. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['lch']) ));
  1139. };
  1140. chroma_1.hcl = function () {
  1141. var args = [], len = arguments.length;
  1142. while ( len-- ) args[ len ] = arguments[ len ];
  1143. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['hcl']) ));
  1144. };
  1145. input.format.lch = lch2rgb_1;
  1146. input.format.hcl = hcl2rgb_1;
  1147. ['lch','hcl'].forEach(function (m) { return input.autodetect.push({
  1148. p: 2,
  1149. test: function () {
  1150. var args = [], len = arguments.length;
  1151. while ( len-- ) args[ len ] = arguments[ len ];
  1152. args = unpack$s(args, m);
  1153. if (type$a(args) === 'array' && args.length === 3) {
  1154. return m;
  1155. }
  1156. }
  1157. }); });
  1158. /**
  1159. X11 color names
  1160. http://www.w3.org/TR/css3-color/#svg-color
  1161. */
  1162. var w3cx11 = {
  1163. aliceblue: '#f0f8ff',
  1164. antiquewhite: '#faebd7',
  1165. aqua: '#00ffff',
  1166. aquamarine: '#7fffd4',
  1167. azure: '#f0ffff',
  1168. beige: '#f5f5dc',
  1169. bisque: '#ffe4c4',
  1170. black: '#000000',
  1171. blanchedalmond: '#ffebcd',
  1172. blue: '#0000ff',
  1173. blueviolet: '#8a2be2',
  1174. brown: '#a52a2a',
  1175. burlywood: '#deb887',
  1176. cadetblue: '#5f9ea0',
  1177. chartreuse: '#7fff00',
  1178. chocolate: '#d2691e',
  1179. coral: '#ff7f50',
  1180. cornflower: '#6495ed',
  1181. cornflowerblue: '#6495ed',
  1182. cornsilk: '#fff8dc',
  1183. crimson: '#dc143c',
  1184. cyan: '#00ffff',
  1185. darkblue: '#00008b',
  1186. darkcyan: '#008b8b',
  1187. darkgoldenrod: '#b8860b',
  1188. darkgray: '#a9a9a9',
  1189. darkgreen: '#006400',
  1190. darkgrey: '#a9a9a9',
  1191. darkkhaki: '#bdb76b',
  1192. darkmagenta: '#8b008b',
  1193. darkolivegreen: '#556b2f',
  1194. darkorange: '#ff8c00',
  1195. darkorchid: '#9932cc',
  1196. darkred: '#8b0000',
  1197. darksalmon: '#e9967a',
  1198. darkseagreen: '#8fbc8f',
  1199. darkslateblue: '#483d8b',
  1200. darkslategray: '#2f4f4f',
  1201. darkslategrey: '#2f4f4f',
  1202. darkturquoise: '#00ced1',
  1203. darkviolet: '#9400d3',
  1204. deeppink: '#ff1493',
  1205. deepskyblue: '#00bfff',
  1206. dimgray: '#696969',
  1207. dimgrey: '#696969',
  1208. dodgerblue: '#1e90ff',
  1209. firebrick: '#b22222',
  1210. floralwhite: '#fffaf0',
  1211. forestgreen: '#228b22',
  1212. fuchsia: '#ff00ff',
  1213. gainsboro: '#dcdcdc',
  1214. ghostwhite: '#f8f8ff',
  1215. gold: '#ffd700',
  1216. goldenrod: '#daa520',
  1217. gray: '#808080',
  1218. green: '#008000',
  1219. greenyellow: '#adff2f',
  1220. grey: '#808080',
  1221. honeydew: '#f0fff0',
  1222. hotpink: '#ff69b4',
  1223. indianred: '#cd5c5c',
  1224. indigo: '#4b0082',
  1225. ivory: '#fffff0',
  1226. khaki: '#f0e68c',
  1227. laserlemon: '#ffff54',
  1228. lavender: '#e6e6fa',
  1229. lavenderblush: '#fff0f5',
  1230. lawngreen: '#7cfc00',
  1231. lemonchiffon: '#fffacd',
  1232. lightblue: '#add8e6',
  1233. lightcoral: '#f08080',
  1234. lightcyan: '#e0ffff',
  1235. lightgoldenrod: '#fafad2',
  1236. lightgoldenrodyellow: '#fafad2',
  1237. lightgray: '#d3d3d3',
  1238. lightgreen: '#90ee90',
  1239. lightgrey: '#d3d3d3',
  1240. lightpink: '#ffb6c1',
  1241. lightsalmon: '#ffa07a',
  1242. lightseagreen: '#20b2aa',
  1243. lightskyblue: '#87cefa',
  1244. lightslategray: '#778899',
  1245. lightslategrey: '#778899',
  1246. lightsteelblue: '#b0c4de',
  1247. lightyellow: '#ffffe0',
  1248. lime: '#00ff00',
  1249. limegreen: '#32cd32',
  1250. linen: '#faf0e6',
  1251. magenta: '#ff00ff',
  1252. maroon: '#800000',
  1253. maroon2: '#7f0000',
  1254. maroon3: '#b03060',
  1255. mediumaquamarine: '#66cdaa',
  1256. mediumblue: '#0000cd',
  1257. mediumorchid: '#ba55d3',
  1258. mediumpurple: '#9370db',
  1259. mediumseagreen: '#3cb371',
  1260. mediumslateblue: '#7b68ee',
  1261. mediumspringgreen: '#00fa9a',
  1262. mediumturquoise: '#48d1cc',
  1263. mediumvioletred: '#c71585',
  1264. midnightblue: '#191970',
  1265. mintcream: '#f5fffa',
  1266. mistyrose: '#ffe4e1',
  1267. moccasin: '#ffe4b5',
  1268. navajowhite: '#ffdead',
  1269. navy: '#000080',
  1270. oldlace: '#fdf5e6',
  1271. olive: '#808000',
  1272. olivedrab: '#6b8e23',
  1273. orange: '#ffa500',
  1274. orangered: '#ff4500',
  1275. orchid: '#da70d6',
  1276. palegoldenrod: '#eee8aa',
  1277. palegreen: '#98fb98',
  1278. paleturquoise: '#afeeee',
  1279. palevioletred: '#db7093',
  1280. papayawhip: '#ffefd5',
  1281. peachpuff: '#ffdab9',
  1282. peru: '#cd853f',
  1283. pink: '#ffc0cb',
  1284. plum: '#dda0dd',
  1285. powderblue: '#b0e0e6',
  1286. purple: '#800080',
  1287. purple2: '#7f007f',
  1288. purple3: '#a020f0',
  1289. rebeccapurple: '#663399',
  1290. red: '#ff0000',
  1291. rosybrown: '#bc8f8f',
  1292. royalblue: '#4169e1',
  1293. saddlebrown: '#8b4513',
  1294. salmon: '#fa8072',
  1295. sandybrown: '#f4a460',
  1296. seagreen: '#2e8b57',
  1297. seashell: '#fff5ee',
  1298. sienna: '#a0522d',
  1299. silver: '#c0c0c0',
  1300. skyblue: '#87ceeb',
  1301. slateblue: '#6a5acd',
  1302. slategray: '#708090',
  1303. slategrey: '#708090',
  1304. snow: '#fffafa',
  1305. springgreen: '#00ff7f',
  1306. steelblue: '#4682b4',
  1307. tan: '#d2b48c',
  1308. teal: '#008080',
  1309. thistle: '#d8bfd8',
  1310. tomato: '#ff6347',
  1311. turquoise: '#40e0d0',
  1312. violet: '#ee82ee',
  1313. wheat: '#f5deb3',
  1314. white: '#ffffff',
  1315. whitesmoke: '#f5f5f5',
  1316. yellow: '#ffff00',
  1317. yellowgreen: '#9acd32'
  1318. };
  1319. var w3cx11_1 = w3cx11;
  1320. var type$b = utils.type;
  1321. Color_1.prototype.name = function() {
  1322. var hex = rgb2hex_1(this._rgb, 'rgb');
  1323. for (var i = 0, list = Object.keys(w3cx11_1); i < list.length; i += 1) {
  1324. var n = list[i];
  1325. if (w3cx11_1[n] === hex) { return n.toLowerCase(); }
  1326. }
  1327. return hex;
  1328. };
  1329. input.format.named = function (name) {
  1330. name = name.toLowerCase();
  1331. if (w3cx11_1[name]) { return hex2rgb_1(w3cx11_1[name]); }
  1332. throw new Error('unknown color name: '+name);
  1333. };
  1334. input.autodetect.push({
  1335. p: 5,
  1336. test: function (h) {
  1337. var rest = [], len = arguments.length - 1;
  1338. while ( len-- > 0 ) rest[ len ] = arguments[ len + 1 ];
  1339. if (!rest.length && type$b(h) === 'string' && w3cx11_1[h.toLowerCase()]) {
  1340. return 'named';
  1341. }
  1342. }
  1343. });
  1344. var unpack$t = utils.unpack;
  1345. var rgb2num = function () {
  1346. var args = [], len = arguments.length;
  1347. while ( len-- ) args[ len ] = arguments[ len ];
  1348. var ref = unpack$t(args, 'rgb');
  1349. var r = ref[0];
  1350. var g = ref[1];
  1351. var b = ref[2];
  1352. return (r << 16) + (g << 8) + b;
  1353. };
  1354. var rgb2num_1 = rgb2num;
  1355. var type$c = utils.type;
  1356. var num2rgb = function (num) {
  1357. if (type$c(num) == "number" && num >= 0 && num <= 0xFFFFFF) {
  1358. var r = num >> 16;
  1359. var g = (num >> 8) & 0xFF;
  1360. var b = num & 0xFF;
  1361. return [r,g,b,1];
  1362. }
  1363. throw new Error("unknown num color: "+num);
  1364. };
  1365. var num2rgb_1 = num2rgb;
  1366. var type$d = utils.type;
  1367. Color_1.prototype.num = function() {
  1368. return rgb2num_1(this._rgb);
  1369. };
  1370. chroma_1.num = function () {
  1371. var args = [], len = arguments.length;
  1372. while ( len-- ) args[ len ] = arguments[ len ];
  1373. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['num']) ));
  1374. };
  1375. input.format.num = num2rgb_1;
  1376. input.autodetect.push({
  1377. p: 5,
  1378. test: function () {
  1379. var args = [], len = arguments.length;
  1380. while ( len-- ) args[ len ] = arguments[ len ];
  1381. if (args.length === 1 && type$d(args[0]) === 'number' && args[0] >= 0 && args[0] <= 0xFFFFFF) {
  1382. return 'num';
  1383. }
  1384. }
  1385. });
  1386. var unpack$u = utils.unpack;
  1387. var type$e = utils.type;
  1388. var round$5 = Math.round;
  1389. Color_1.prototype.rgb = function(rnd) {
  1390. if ( rnd === void 0 ) rnd=true;
  1391. if (rnd === false) { return this._rgb.slice(0,3); }
  1392. return this._rgb.slice(0,3).map(round$5);
  1393. };
  1394. Color_1.prototype.rgba = function(rnd) {
  1395. if ( rnd === void 0 ) rnd=true;
  1396. return this._rgb.slice(0,4).map(function (v,i) {
  1397. return i<3 ? (rnd === false ? v : round$5(v)) : v;
  1398. });
  1399. };
  1400. chroma_1.rgb = function () {
  1401. var args = [], len = arguments.length;
  1402. while ( len-- ) args[ len ] = arguments[ len ];
  1403. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['rgb']) ));
  1404. };
  1405. input.format.rgb = function () {
  1406. var args = [], len = arguments.length;
  1407. while ( len-- ) args[ len ] = arguments[ len ];
  1408. var rgba = unpack$u(args, 'rgba');
  1409. if (rgba[3] === undefined) { rgba[3] = 1; }
  1410. return rgba;
  1411. };
  1412. input.autodetect.push({
  1413. p: 3,
  1414. test: function () {
  1415. var args = [], len = arguments.length;
  1416. while ( len-- ) args[ len ] = arguments[ len ];
  1417. args = unpack$u(args, 'rgba');
  1418. if (type$e(args) === 'array' && (args.length === 3 ||
  1419. args.length === 4 && type$e(args[3]) == 'number' && args[3] >= 0 && args[3] <= 1)) {
  1420. return 'rgb';
  1421. }
  1422. }
  1423. });
  1424. /*
  1425. * Based on implementation by Neil Bartlett
  1426. * https://github.com/neilbartlett/color-temperature
  1427. */
  1428. var log = Math.log;
  1429. var temperature2rgb = function (kelvin) {
  1430. var temp = kelvin / 100;
  1431. var r,g,b;
  1432. if (temp < 66) {
  1433. r = 255;
  1434. g = -155.25485562709179 - 0.44596950469579133 * (g = temp-2) + 104.49216199393888 * log(g);
  1435. b = temp < 20 ? 0 : -254.76935184120902 + 0.8274096064007395 * (b = temp-10) + 115.67994401066147 * log(b);
  1436. } else {
  1437. r = 351.97690566805693 + 0.114206453784165 * (r = temp-55) - 40.25366309332127 * log(r);
  1438. g = 325.4494125711974 + 0.07943456536662342 * (g = temp-50) - 28.0852963507957 * log(g);
  1439. b = 255;
  1440. }
  1441. return [r,g,b,1];
  1442. };
  1443. var temperature2rgb_1 = temperature2rgb;
  1444. /*
  1445. * Based on implementation by Neil Bartlett
  1446. * https://github.com/neilbartlett/color-temperature
  1447. **/
  1448. var unpack$v = utils.unpack;
  1449. var round$6 = Math.round;
  1450. var rgb2temperature = function () {
  1451. var args = [], len = arguments.length;
  1452. while ( len-- ) args[ len ] = arguments[ len ];
  1453. var rgb = unpack$v(args, 'rgb');
  1454. var r = rgb[0], b = rgb[2];
  1455. var minTemp = 1000;
  1456. var maxTemp = 40000;
  1457. var eps = 0.4;
  1458. var temp;
  1459. while (maxTemp - minTemp > eps) {
  1460. temp = (maxTemp + minTemp) * 0.5;
  1461. var rgb$1 = temperature2rgb_1(temp);
  1462. if ((rgb$1[2] / rgb$1[0]) >= (b / r)) {
  1463. maxTemp = temp;
  1464. } else {
  1465. minTemp = temp;
  1466. }
  1467. }
  1468. return round$6(temp);
  1469. };
  1470. var rgb2temperature_1 = rgb2temperature;
  1471. Color_1.prototype.temp =
  1472. Color_1.prototype.kelvin =
  1473. Color_1.prototype.temperature = function() {
  1474. return rgb2temperature_1(this._rgb);
  1475. };
  1476. chroma_1.temp =
  1477. chroma_1.kelvin =
  1478. chroma_1.temperature = function () {
  1479. var args = [], len = arguments.length;
  1480. while ( len-- ) args[ len ] = arguments[ len ];
  1481. return new (Function.prototype.bind.apply( Color_1, [ null ].concat( args, ['temp']) ));
  1482. };
  1483. input.format.temp =
  1484. input.format.kelvin =
  1485. input.format.temperature = temperature2rgb_1;
  1486. var type$f = utils.type;
  1487. Color_1.prototype.alpha = function(a, mutate) {
  1488. if ( mutate === void 0 ) mutate=false;
  1489. if (a !== undefined && type$f(a) === 'number') {
  1490. if (mutate) {
  1491. this._rgb[3] = a;
  1492. return this;
  1493. }
  1494. return new Color_1([this._rgb[0], this._rgb[1], this._rgb[2], a], 'rgb');
  1495. }
  1496. return this._rgb[3];
  1497. };
  1498. Color_1.prototype.clipped = function() {
  1499. return this._rgb._clipped || false;
  1500. };
  1501. Color_1.prototype.darken = function(amount) {
  1502. if ( amount === void 0 ) amount=1;
  1503. var me = this;
  1504. var lab = me.lab();
  1505. lab[0] -= labConstants.Kn * amount;
  1506. return new Color_1(lab, 'lab').alpha(me.alpha(), true);
  1507. };
  1508. Color_1.prototype.brighten = function(amount) {
  1509. if ( amount === void 0 ) amount=1;
  1510. return this.darken(-amount);
  1511. };
  1512. Color_1.prototype.darker = Color_1.prototype.darken;
  1513. Color_1.prototype.brighter = Color_1.prototype.brighten;
  1514. Color_1.prototype.get = function(mc) {
  1515. var ref = mc.split('.');
  1516. var mode = ref[0];
  1517. var channel = ref[1];
  1518. var src = this[mode]();
  1519. if (channel) {
  1520. var i = mode.indexOf(channel);
  1521. if (i > -1) { return src[i]; }
  1522. throw new Error(("unknown channel " + channel + " in mode " + mode));
  1523. } else {
  1524. return src;
  1525. }
  1526. };
  1527. var type$g = utils.type;
  1528. var pow$2 = Math.pow;
  1529. var EPS = 1e-7;
  1530. var MAX_ITER = 20;
  1531. Color_1.prototype.luminance = function(lum) {
  1532. if (lum !== undefined && type$g(lum) === 'number') {
  1533. if (lum === 0) {
  1534. // return pure black
  1535. return new Color_1([0,0,0,this._rgb[3]], 'rgb');
  1536. }
  1537. if (lum === 1) {
  1538. // return pure white
  1539. return new Color_1([255,255,255,this._rgb[3]], 'rgb');
  1540. }
  1541. // compute new color using...
  1542. var cur_lum = this.luminance();
  1543. var mode = 'rgb';
  1544. var max_iter = MAX_ITER;
  1545. var test = function (low, high) {
  1546. var mid = low.interpolate(high, 0.5, mode);
  1547. var lm = mid.luminance();
  1548. if (Math.abs(lum - lm) < EPS || !max_iter--) {
  1549. // close enough
  1550. return mid;
  1551. }
  1552. return lm > lum ? test(low, mid) : test(mid, high);
  1553. };
  1554. var rgb = (cur_lum > lum ? test(new Color_1([0,0,0]), this) : test(this, new Color_1([255,255,255]))).rgb();
  1555. return new Color_1(rgb.concat( [this._rgb[3]]));
  1556. }
  1557. return rgb2luminance.apply(void 0, (this._rgb).slice(0,3));
  1558. };
  1559. var rgb2luminance = function (r,g,b) {
  1560. // relative luminance
  1561. // see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  1562. r = luminance_x(r);
  1563. g = luminance_x(g);
  1564. b = luminance_x(b);
  1565. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  1566. };
  1567. var luminance_x = function (x) {
  1568. x /= 255;
  1569. return x <= 0.03928 ? x/12.92 : pow$2((x+0.055)/1.055, 2.4);
  1570. };
  1571. var interpolator = {};
  1572. var type$h = utils.type;
  1573. var mix = function (col1, col2, f) {
  1574. if ( f === void 0 ) f=0.5;
  1575. var rest = [], len = arguments.length - 3;
  1576. while ( len-- > 0 ) rest[ len ] = arguments[ len + 3 ];
  1577. var mode = rest[0] || 'lrgb';
  1578. if (!interpolator[mode] && !rest.length) {
  1579. // fall back to the first supported mode
  1580. mode = Object.keys(interpolator)[0];
  1581. }
  1582. if (!interpolator[mode]) {
  1583. throw new Error(("interpolation mode " + mode + " is not defined"));
  1584. }
  1585. if (type$h(col1) !== 'object') { col1 = new Color_1(col1); }
  1586. if (type$h(col2) !== 'object') { col2 = new Color_1(col2); }
  1587. return interpolator[mode](col1, col2, f)
  1588. .alpha(col1.alpha() + f * (col2.alpha() - col1.alpha()));
  1589. };
  1590. Color_1.prototype.mix =
  1591. Color_1.prototype.interpolate = function(col2, f) {
  1592. if ( f === void 0 ) f=0.5;
  1593. var rest = [], len = arguments.length - 2;
  1594. while ( len-- > 0 ) rest[ len ] = arguments[ len + 2 ];
  1595. return mix.apply(void 0, [ this, col2, f ].concat( rest ));
  1596. };
  1597. Color_1.prototype.premultiply = function(mutate) {
  1598. if ( mutate === void 0 ) mutate=false;
  1599. var rgb = this._rgb;
  1600. var a = rgb[3];
  1601. if (mutate) {
  1602. this._rgb = [rgb[0]*a, rgb[1]*a, rgb[2]*a, a];
  1603. return this;
  1604. } else {
  1605. return new Color_1([rgb[0]*a, rgb[1]*a, rgb[2]*a, a], 'rgb');
  1606. }
  1607. };
  1608. Color_1.prototype.saturate = function(amount) {
  1609. if ( amount === void 0 ) amount=1;
  1610. var me = this;
  1611. var lch = me.lch();
  1612. lch[1] += labConstants.Kn * amount;
  1613. if (lch[1] < 0) { lch[1] = 0; }
  1614. return new Color_1(lch, 'lch').alpha(me.alpha(), true);
  1615. };
  1616. Color_1.prototype.desaturate = function(amount) {
  1617. if ( amount === void 0 ) amount=1;
  1618. return this.saturate(-amount);
  1619. };
  1620. var type$i = utils.type;
  1621. Color_1.prototype.set = function(mc, value, mutate) {
  1622. if ( mutate === void 0 ) mutate=false;
  1623. var ref = mc.split('.');
  1624. var mode = ref[0];
  1625. var channel = ref[1];
  1626. var src = this[mode]();
  1627. if (channel) {
  1628. var i = mode.indexOf(channel);
  1629. if (i > -1) {
  1630. if (type$i(value) == 'string') {
  1631. switch(value.charAt(0)) {
  1632. case '+': src[i] += +value; break;
  1633. case '-': src[i] += +value; break;
  1634. case '*': src[i] *= +(value.substr(1)); break;
  1635. case '/': src[i] /= +(value.substr(1)); break;
  1636. default: src[i] = +value;
  1637. }
  1638. } else if (type$i(value) === 'number') {
  1639. src[i] = value;
  1640. } else {
  1641. throw new Error("unsupported value for Color.set");
  1642. }
  1643. var out = new Color_1(src, mode);
  1644. if (mutate) {
  1645. this._rgb = out._rgb;
  1646. return this;
  1647. }
  1648. return out;
  1649. }
  1650. throw new Error(("unknown channel " + channel + " in mode " + mode));
  1651. } else {
  1652. return src;
  1653. }
  1654. };
  1655. var rgb$1 = function (col1, col2, f) {
  1656. var xyz0 = col1._rgb;
  1657. var xyz1 = col2._rgb;
  1658. return new Color_1(
  1659. xyz0[0] + f * (xyz1[0]-xyz0[0]),
  1660. xyz0[1] + f * (xyz1[1]-xyz0[1]),
  1661. xyz0[2] + f * (xyz1[2]-xyz0[2]),
  1662. 'rgb'
  1663. )
  1664. };
  1665. // register interpolator
  1666. interpolator.rgb = rgb$1;
  1667. var sqrt$2 = Math.sqrt;
  1668. var pow$3 = Math.pow;
  1669. var lrgb = function (col1, col2, f) {
  1670. var ref = col1._rgb;
  1671. var x1 = ref[0];
  1672. var y1 = ref[1];
  1673. var z1 = ref[2];
  1674. var ref$1 = col2._rgb;
  1675. var x2 = ref$1[0];
  1676. var y2 = ref$1[1];
  1677. var z2 = ref$1[2];
  1678. return new Color_1(
  1679. sqrt$2(pow$3(x1,2) * (1-f) + pow$3(x2,2) * f),
  1680. sqrt$2(pow$3(y1,2) * (1-f) + pow$3(y2,2) * f),
  1681. sqrt$2(pow$3(z1,2) * (1-f) + pow$3(z2,2) * f),
  1682. 'rgb'
  1683. )
  1684. };
  1685. // register interpolator
  1686. interpolator.lrgb = lrgb;
  1687. var lab$1 = function (col1, col2, f) {
  1688. var xyz0 = col1.lab();
  1689. var xyz1 = col2.lab();
  1690. return new Color_1(
  1691. xyz0[0] + f * (xyz1[0]-xyz0[0]),
  1692. xyz0[1] + f * (xyz1[1]-xyz0[1]),
  1693. xyz0[2] + f * (xyz1[2]-xyz0[2]),
  1694. 'lab'
  1695. )
  1696. };
  1697. // register interpolator
  1698. interpolator.lab = lab$1;
  1699. var _hsx = function (col1, col2, f, m) {
  1700. var assign, assign$1;
  1701. var xyz0, xyz1;
  1702. if (m === 'hsl') {
  1703. xyz0 = col1.hsl();
  1704. xyz1 = col2.hsl();
  1705. } else if (m === 'hsv') {
  1706. xyz0 = col1.hsv();
  1707. xyz1 = col2.hsv();
  1708. } else if (m === 'hcg') {
  1709. xyz0 = col1.hcg();
  1710. xyz1 = col2.hcg();
  1711. } else if (m === 'hsi') {
  1712. xyz0 = col1.hsi();
  1713. xyz1 = col2.hsi();
  1714. } else if (m === 'lch' || m === 'hcl') {
  1715. m = 'hcl';
  1716. xyz0 = col1.hcl();
  1717. xyz1 = col2.hcl();
  1718. }
  1719. var hue0, hue1, sat0, sat1, lbv0, lbv1;
  1720. if (m.substr(0, 1) === 'h') {
  1721. (assign = xyz0, hue0 = assign[0], sat0 = assign[1], lbv0 = assign[2]);
  1722. (assign$1 = xyz1, hue1 = assign$1[0], sat1 = assign$1[1], lbv1 = assign$1[2]);
  1723. }
  1724. var sat, hue, lbv, dh;
  1725. if (!isNaN(hue0) && !isNaN(hue1)) {
  1726. // both colors have hue
  1727. if (hue1 > hue0 && hue1 - hue0 > 180) {
  1728. dh = hue1-(hue0+360);
  1729. } else if (hue1 < hue0 && hue0 - hue1 > 180) {
  1730. dh = hue1+360-hue0;
  1731. } else {
  1732. dh = hue1 - hue0;
  1733. }
  1734. hue = hue0 + f * dh;
  1735. } else if (!isNaN(hue0)) {
  1736. hue = hue0;
  1737. if ((lbv1 == 1 || lbv1 == 0) && m != 'hsv') { sat = sat0; }
  1738. } else if (!isNaN(hue1)) {
  1739. hue = hue1;
  1740. if ((lbv0 == 1 || lbv0 == 0) && m != 'hsv') { sat = sat1; }
  1741. } else {
  1742. hue = Number.NaN;
  1743. }
  1744. if (sat === undefined) { sat = sat0 + f * (sat1 - sat0); }
  1745. lbv = lbv0 + f * (lbv1-lbv0);
  1746. return new Color_1([hue, sat, lbv], m);
  1747. };
  1748. var lch$1 = function (col1, col2, f) {
  1749. return _hsx(col1, col2, f, 'lch');
  1750. };
  1751. // register interpolator
  1752. interpolator.lch = lch$1;
  1753. interpolator.hcl = lch$1;
  1754. var num$1 = function (col1, col2, f) {
  1755. var c1 = col1.num();
  1756. var c2 = col2.num();
  1757. return new Color_1(c1 + f * (c2-c1), 'num')
  1758. };
  1759. // register interpolator
  1760. interpolator.num = num$1;
  1761. var hcg$1 = function (col1, col2, f) {
  1762. return _hsx(col1, col2, f, 'hcg');
  1763. };
  1764. // register interpolator
  1765. interpolator.hcg = hcg$1;
  1766. var hsi$1 = function (col1, col2, f) {
  1767. return _hsx(col1, col2, f, 'hsi');
  1768. };
  1769. // register interpolator
  1770. interpolator.hsi = hsi$1;
  1771. var hsl$1 = function (col1, col2, f) {
  1772. return _hsx(col1, col2, f, 'hsl');
  1773. };
  1774. // register interpolator
  1775. interpolator.hsl = hsl$1;
  1776. var hsv$1 = function (col1, col2, f) {
  1777. return _hsx(col1, col2, f, 'hsv');
  1778. };
  1779. // register interpolator
  1780. interpolator.hsv = hsv$1;
  1781. var clip_rgb$2 = utils.clip_rgb;
  1782. var pow$4 = Math.pow;
  1783. var sqrt$3 = Math.sqrt;
  1784. var PI$1 = Math.PI;
  1785. var cos$2 = Math.cos;
  1786. var sin$1 = Math.sin;
  1787. var atan2$1 = Math.atan2;
  1788. var average = function (colors, mode, weights) {
  1789. if ( mode === void 0 ) mode='lrgb';
  1790. if ( weights === void 0 ) weights=null;
  1791. var l = colors.length;
  1792. if (!weights) { weights = Array.from(new Array(l)).map(function () { return 1; }); }
  1793. // normalize weights
  1794. var k = l / weights.reduce(function(a, b) { return a + b; });
  1795. weights.forEach(function (w,i) { weights[i] *= k; });
  1796. // convert colors to Color objects
  1797. colors = colors.map(function (c) { return new Color_1(c); });
  1798. if (mode === 'lrgb') {
  1799. return _average_lrgb(colors, weights)
  1800. }
  1801. var first = colors.shift();
  1802. var xyz = first.get(mode);
  1803. var cnt = [];
  1804. var dx = 0;
  1805. var dy = 0;
  1806. // initial color
  1807. for (var i=0; i<xyz.length; i++) {
  1808. xyz[i] = (xyz[i] || 0) * weights[0];
  1809. cnt.push(isNaN(xyz[i]) ? 0 : weights[0]);
  1810. if (mode.charAt(i) === 'h' && !isNaN(xyz[i])) {
  1811. var A = xyz[i] / 180 * PI$1;
  1812. dx += cos$2(A) * weights[0];
  1813. dy += sin$1(A) * weights[0];
  1814. }
  1815. }
  1816. var alpha = first.alpha() * weights[0];
  1817. colors.forEach(function (c,ci) {
  1818. var xyz2 = c.get(mode);
  1819. alpha += c.alpha() * weights[ci+1];
  1820. for (var i=0; i<xyz.length; i++) {
  1821. if (!isNaN(xyz2[i])) {
  1822. cnt[i] += weights[ci+1];
  1823. if (mode.charAt(i) === 'h') {
  1824. var A = xyz2[i] / 180 * PI$1;
  1825. dx += cos$2(A) * weights[ci+1];
  1826. dy += sin$1(A) * weights[ci+1];
  1827. } else {
  1828. xyz[i] += xyz2[i] * weights[ci+1];
  1829. }
  1830. }
  1831. }
  1832. });
  1833. for (var i$1=0; i$1<xyz.length; i$1++) {
  1834. if (mode.charAt(i$1) === 'h') {
  1835. var A$1 = atan2$1(dy / cnt[i$1], dx / cnt[i$1]) / PI$1 * 180;
  1836. while (A$1 < 0) { A$1 += 360; }
  1837. while (A$1 >= 360) { A$1 -= 360; }
  1838. xyz[i$1] = A$1;
  1839. } else {
  1840. xyz[i$1] = xyz[i$1]/cnt[i$1];
  1841. }
  1842. }
  1843. alpha /= l;
  1844. return (new Color_1(xyz, mode)).alpha(alpha > 0.99999 ? 1 : alpha, true);
  1845. };
  1846. var _average_lrgb = function (colors, weights) {
  1847. var l = colors.length;
  1848. var xyz = [0,0,0,0];
  1849. for (var i=0; i < colors.length; i++) {
  1850. var col = colors[i];
  1851. var f = weights[i] / l;
  1852. var rgb = col._rgb;
  1853. xyz[0] += pow$4(rgb[0],2) * f;
  1854. xyz[1] += pow$4(rgb[1],2) * f;
  1855. xyz[2] += pow$4(rgb[2],2) * f;
  1856. xyz[3] += rgb[3] * f;
  1857. }
  1858. xyz[0] = sqrt$3(xyz[0]);
  1859. xyz[1] = sqrt$3(xyz[1]);
  1860. xyz[2] = sqrt$3(xyz[2]);
  1861. if (xyz[3] > 0.9999999) { xyz[3] = 1; }
  1862. return new Color_1(clip_rgb$2(xyz));
  1863. };
  1864. // minimal multi-purpose interface
  1865. // @requires utils color analyze
  1866. var type$j = utils.type;
  1867. var pow$5 = Math.pow;
  1868. var scale = function(colors) {
  1869. // constructor
  1870. var _mode = 'rgb';
  1871. var _nacol = chroma_1('#ccc');
  1872. var _spread = 0;
  1873. // const _fixed = false;
  1874. var _domain = [0, 1];
  1875. var _pos = [];
  1876. var _padding = [0,0];
  1877. var _classes = false;
  1878. var _colors = [];
  1879. var _out = false;
  1880. var _min = 0;
  1881. var _max = 1;
  1882. var _correctLightness = false;
  1883. var _colorCache = {};
  1884. var _useCache = true;
  1885. var _gamma = 1;
  1886. // private methods
  1887. var setColors = function(colors) {
  1888. colors = colors || ['#fff', '#000'];
  1889. if (colors && type$j(colors) === 'string' && chroma_1.brewer &&
  1890. chroma_1.brewer[colors.toLowerCase()]) {
  1891. colors = chroma_1.brewer[colors.toLowerCase()];
  1892. }
  1893. if (type$j(colors) === 'array') {
  1894. // handle single color
  1895. if (colors.length === 1) {
  1896. colors = [colors[0], colors[0]];
  1897. }
  1898. // make a copy of the colors
  1899. colors = colors.slice(0);
  1900. // convert to chroma classes
  1901. for (var c=0; c<colors.length; c++) {
  1902. colors[c] = chroma_1(colors[c]);
  1903. }
  1904. // auto-fill color position
  1905. _pos.length = 0;
  1906. for (var c$1=0; c$1<colors.length; c$1++) {
  1907. _pos.push(c$1/(colors.length-1));
  1908. }
  1909. }
  1910. resetCache();
  1911. return _colors = colors;
  1912. };
  1913. var getClass = function(value) {
  1914. if (_classes != null) {
  1915. var n = _classes.length-1;
  1916. var i = 0;
  1917. while (i < n && value >= _classes[i]) {
  1918. i++;
  1919. }
  1920. return i-1;
  1921. }
  1922. return 0;
  1923. };
  1924. var tMapLightness = function (t) { return t; };
  1925. var tMapDomain = function (t) { return t; };
  1926. // const classifyValue = function(value) {
  1927. // let val = value;
  1928. // if (_classes.length > 2) {
  1929. // const n = _classes.length-1;
  1930. // const i = getClass(value);
  1931. // const minc = _classes[0] + ((_classes[1]-_classes[0]) * (0 + (_spread * 0.5))); // center of 1st class
  1932. // const maxc = _classes[n-1] + ((_classes[n]-_classes[n-1]) * (1 - (_spread * 0.5))); // center of last class
  1933. // val = _min + ((((_classes[i] + ((_classes[i+1] - _classes[i]) * 0.5)) - minc) / (maxc-minc)) * (_max - _min));
  1934. // }
  1935. // return val;
  1936. // };
  1937. var getColor = function(val, bypassMap) {
  1938. var col, t;
  1939. if (bypassMap == null) { bypassMap = false; }
  1940. if (isNaN(val) || (val === null)) { return _nacol; }
  1941. if (!bypassMap) {
  1942. if (_classes && (_classes.length > 2)) {
  1943. // find the class
  1944. var c = getClass(val);
  1945. t = c / (_classes.length-2);
  1946. } else if (_max !== _min) {
  1947. // just interpolate between min/max
  1948. t = (val - _min) / (_max - _min);
  1949. } else {
  1950. t = 1;
  1951. }
  1952. } else {
  1953. t = val;
  1954. }
  1955. // domain map
  1956. t = tMapDomain(t);
  1957. if (!bypassMap) {
  1958. t = tMapLightness(t); // lightness correction
  1959. }
  1960. if (_gamma !== 1) { t = pow$5(t, _gamma); }
  1961. t = _padding[0] + (t * (1 - _padding[0] - _padding[1]));
  1962. t = Math.min(1, Math.max(0, t));
  1963. var k = Math.floor(t * 10000);
  1964. if (_useCache && _colorCache[k]) {
  1965. col = _colorCache[k];
  1966. } else {
  1967. if (type$j(_colors) === 'array') {
  1968. //for i in [0.._pos.length-1]
  1969. for (var i=0; i<_pos.length; i++) {
  1970. var p = _pos[i];
  1971. if (t <= p) {
  1972. col = _colors[i];
  1973. break;
  1974. }
  1975. if ((t >= p) && (i === (_pos.length-1))) {
  1976. col = _colors[i];
  1977. break;
  1978. }
  1979. if (t > p && t < _pos[i+1]) {
  1980. t = (t-p)/(_pos[i+1]-p);
  1981. col = chroma_1.interpolate(_colors[i], _colors[i+1], t, _mode);
  1982. break;
  1983. }
  1984. }
  1985. } else if (type$j(_colors) === 'function') {
  1986. col = _colors(t);
  1987. }
  1988. if (_useCache) { _colorCache[k] = col; }
  1989. }
  1990. return col;
  1991. };
  1992. var resetCache = function () { return _colorCache = {}; };
  1993. setColors(colors);
  1994. // public interface
  1995. var f = function(v) {
  1996. var c = chroma_1(getColor(v));
  1997. if (_out && c[_out]) { return c[_out](); } else { return c; }
  1998. };
  1999. f.classes = function(classes) {
  2000. if (classes != null) {
  2001. if (type$j(classes) === 'array') {
  2002. _classes = classes;
  2003. _domain = [classes[0], classes[classes.length-1]];
  2004. } else {
  2005. var d = chroma_1.analyze(_domain);
  2006. if (classes === 0) {
  2007. _classes = [d.min, d.max];
  2008. } else {
  2009. _classes = chroma_1.limits(d, 'e', classes);
  2010. }
  2011. }
  2012. return f;
  2013. }
  2014. return _classes;
  2015. };
  2016. f.domain = function(domain) {
  2017. if (!arguments.length) {
  2018. return _domain;
  2019. }
  2020. _min = domain[0];
  2021. _max = domain[domain.length-1];
  2022. _pos = [];
  2023. var k = _colors.length;
  2024. if ((domain.length === k) && (_min !== _max)) {
  2025. // update positions
  2026. for (var i = 0, list = Array.from(domain); i < list.length; i += 1) {
  2027. var d = list[i];
  2028. _pos.push((d-_min) / (_max-_min));
  2029. }
  2030. } else {
  2031. for (var c=0; c<k; c++) {
  2032. _pos.push(c/(k-1));
  2033. }
  2034. if (domain.length > 2) {
  2035. // set domain map
  2036. var tOut = domain.map(function (d,i) { return i/(domain.length-1); });
  2037. var tBreaks = domain.map(function (d) { return (d - _min) / (_max - _min); });
  2038. if (!tBreaks.every(function (val, i) { return tOut[i] === val; })) {
  2039. tMapDomain = function (t) {
  2040. if (t <= 0 || t >= 1) { return t; }
  2041. var i = 0;
  2042. while (t >= tBreaks[i+1]) { i++; }
  2043. var f = (t - tBreaks[i]) / (tBreaks[i+1] - tBreaks[i]);
  2044. var out = tOut[i] + f * (tOut[i+1] - tOut[i]);
  2045. return out;
  2046. };
  2047. }
  2048. }
  2049. }
  2050. _domain = [_min, _max];
  2051. return f;
  2052. };
  2053. f.mode = function(_m) {
  2054. if (!arguments.length) {
  2055. return _mode;
  2056. }
  2057. _mode = _m;
  2058. resetCache();
  2059. return f;
  2060. };
  2061. f.range = function(colors, _pos) {
  2062. setColors(colors);
  2063. return f;
  2064. };
  2065. f.out = function(_o) {
  2066. _out = _o;
  2067. return f;
  2068. };
  2069. f.spread = function(val) {
  2070. if (!arguments.length) {
  2071. return _spread;
  2072. }
  2073. _spread = val;
  2074. return f;
  2075. };
  2076. f.correctLightness = function(v) {
  2077. if (v == null) { v = true; }
  2078. _correctLightness = v;
  2079. resetCache();
  2080. if (_correctLightness) {
  2081. tMapLightness = function(t) {
  2082. var L0 = getColor(0, true).lab()[0];
  2083. var L1 = getColor(1, true).lab()[0];
  2084. var pol = L0 > L1;
  2085. var L_actual = getColor(t, true).lab()[0];
  2086. var L_ideal = L0 + ((L1 - L0) * t);
  2087. var L_diff = L_actual - L_ideal;
  2088. var t0 = 0;
  2089. var t1 = 1;
  2090. var max_iter = 20;
  2091. while ((Math.abs(L_diff) > 1e-2) && (max_iter-- > 0)) {
  2092. (function() {
  2093. if (pol) { L_diff *= -1; }
  2094. if (L_diff < 0) {
  2095. t0 = t;
  2096. t += (t1 - t) * 0.5;
  2097. } else {
  2098. t1 = t;
  2099. t += (t0 - t) * 0.5;
  2100. }
  2101. L_actual = getColor(t, true).lab()[0];
  2102. return L_diff = L_actual - L_ideal;
  2103. })();
  2104. }
  2105. return t;
  2106. };
  2107. } else {
  2108. tMapLightness = function (t) { return t; };
  2109. }
  2110. return f;
  2111. };
  2112. f.padding = function(p) {
  2113. if (p != null) {
  2114. if (type$j(p) === 'number') {
  2115. p = [p,p];
  2116. }
  2117. _padding = p;
  2118. return f;
  2119. } else {
  2120. return _padding;
  2121. }
  2122. };
  2123. f.colors = function(numColors, out) {
  2124. // If no arguments are given, return the original colors that were provided
  2125. if (arguments.length < 2) { out = 'hex'; }
  2126. var result = [];
  2127. if (arguments.length === 0) {
  2128. result = _colors.slice(0);
  2129. } else if (numColors === 1) {
  2130. result = [f(0.5)];
  2131. } else if (numColors > 1) {
  2132. var dm = _domain[0];
  2133. var dd = _domain[1] - dm;
  2134. result = __range__(0, numColors, false).map(function (i) { return f( dm + ((i/(numColors-1)) * dd) ); });
  2135. } else { // returns all colors based on the defined classes
  2136. colors = [];
  2137. var samples = [];
  2138. if (_classes && (_classes.length > 2)) {
  2139. for (var i = 1, end = _classes.length, asc = 1 <= end; asc ? i < end : i > end; asc ? i++ : i--) {
  2140. samples.push((_classes[i-1]+_classes[i])*0.5);
  2141. }
  2142. } else {
  2143. samples = _domain;
  2144. }
  2145. result = samples.map(function (v) { return f(v); });
  2146. }
  2147. if (chroma_1[out]) {
  2148. result = result.map(function (c) { return c[out](); });
  2149. }
  2150. return result;
  2151. };
  2152. f.cache = function(c) {
  2153. if (c != null) {
  2154. _useCache = c;
  2155. return f;
  2156. } else {
  2157. return _useCache;
  2158. }
  2159. };
  2160. f.gamma = function(g) {
  2161. if (g != null) {
  2162. _gamma = g;
  2163. return f;
  2164. } else {
  2165. return _gamma;
  2166. }
  2167. };
  2168. f.nodata = function(d) {
  2169. if (d != null) {
  2170. _nacol = chroma_1(d);
  2171. return f;
  2172. } else {
  2173. return _nacol;
  2174. }
  2175. };
  2176. return f;
  2177. };
  2178. function __range__(left, right, inclusive) {
  2179. var range = [];
  2180. var ascending = left < right;
  2181. var end = !inclusive ? right : ascending ? right + 1 : right - 1;
  2182. for (var i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
  2183. range.push(i);
  2184. }
  2185. return range;
  2186. }
  2187. //
  2188. // interpolates between a set of colors uzing a bezier spline
  2189. //
  2190. // @requires utils lab
  2191. var bezier = function(colors) {
  2192. var assign, assign$1, assign$2;
  2193. var I, lab0, lab1, lab2;
  2194. colors = colors.map(function (c) { return new Color_1(c); });
  2195. if (colors.length === 2) {
  2196. // linear interpolation
  2197. (assign = colors.map(function (c) { return c.lab(); }), lab0 = assign[0], lab1 = assign[1]);
  2198. I = function(t) {
  2199. var lab = ([0, 1, 2].map(function (i) { return lab0[i] + (t * (lab1[i] - lab0[i])); }));
  2200. return new Color_1(lab, 'lab');
  2201. };
  2202. } else if (colors.length === 3) {
  2203. // quadratic bezier interpolation
  2204. (assign$1 = colors.map(function (c) { return c.lab(); }), lab0 = assign$1[0], lab1 = assign$1[1], lab2 = assign$1[2]);
  2205. I = function(t) {
  2206. 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]); }));
  2207. return new Color_1(lab, 'lab');
  2208. };
  2209. } else if (colors.length === 4) {
  2210. // cubic bezier interpolation
  2211. var lab3;
  2212. (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]);
  2213. I = function(t) {
  2214. 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]); }));
  2215. return new Color_1(lab, 'lab');
  2216. };
  2217. } else if (colors.length === 5) {
  2218. var I0 = bezier(colors.slice(0, 3));
  2219. var I1 = bezier(colors.slice(2, 5));
  2220. I = function(t) {
  2221. if (t < 0.5) {
  2222. return I0(t*2);
  2223. } else {
  2224. return I1((t-0.5)*2);
  2225. }
  2226. };
  2227. }
  2228. return I;
  2229. };
  2230. var bezier_1 = function (colors) {
  2231. var f = bezier(colors);
  2232. f.scale = function () { return scale(f); };
  2233. return f;
  2234. };
  2235. /*
  2236. * interpolates between a set of colors uzing a bezier spline
  2237. * blend mode formulas taken from http://www.venture-ware.com/kevin/coding/lets-learn-math-photoshop-blend-modes/
  2238. */
  2239. var blend = function (bottom, top, mode) {
  2240. if (!blend[mode]) {
  2241. throw new Error('unknown blend mode ' + mode);
  2242. }
  2243. return blend[mode](bottom, top);
  2244. };
  2245. var blend_f = function (f) { return function (bottom,top) {
  2246. var c0 = chroma_1(top).rgb();
  2247. var c1 = chroma_1(bottom).rgb();
  2248. return chroma_1.rgb(f(c0, c1));
  2249. }; };
  2250. var each = function (f) { return function (c0, c1) {
  2251. var out = [];
  2252. out[0] = f(c0[0], c1[0]);
  2253. out[1] = f(c0[1], c1[1]);
  2254. out[2] = f(c0[2], c1[2]);
  2255. return out;
  2256. }; };
  2257. var normal = function (a) { return a; };
  2258. var multiply = function (a,b) { return a * b / 255; };
  2259. var darken$1 = function (a,b) { return a > b ? b : a; };
  2260. var lighten = function (a,b) { return a > b ? a : b; };
  2261. var screen = function (a,b) { return 255 * (1 - (1-a/255) * (1-b/255)); };
  2262. var overlay = function (a,b) { return b < 128 ? 2 * a * b / 255 : 255 * (1 - 2 * (1 - a / 255 ) * ( 1 - b / 255 )); };
  2263. var burn = function (a,b) { return 255 * (1 - (1 - b / 255) / (a/255)); };
  2264. var dodge = function (a,b) {
  2265. if (a === 255) { return 255; }
  2266. a = 255 * (b / 255) / (1 - a / 255);
  2267. return a > 255 ? 255 : a
  2268. };
  2269. // # add = (a,b) ->
  2270. // # if (a + b > 255) then 255 else a + b
  2271. blend.normal = blend_f(each(normal));
  2272. blend.multiply = blend_f(each(multiply));
  2273. blend.screen = blend_f(each(screen));
  2274. blend.overlay = blend_f(each(overlay));
  2275. blend.darken = blend_f(each(darken$1));
  2276. blend.lighten = blend_f(each(lighten));
  2277. blend.dodge = blend_f(each(dodge));
  2278. blend.burn = blend_f(each(burn));
  2279. // blend.add = blend_f(each(add));
  2280. var blend_1 = blend;
  2281. // cubehelix interpolation
  2282. // based on D.A. Green "A colour scheme for the display of astronomical intensity images"
  2283. // http://astron-soc.in/bulletin/11June/289392011.pdf
  2284. var type$k = utils.type;
  2285. var clip_rgb$3 = utils.clip_rgb;
  2286. var TWOPI$2 = utils.TWOPI;
  2287. var pow$6 = Math.pow;
  2288. var sin$2 = Math.sin;
  2289. var cos$3 = Math.cos;
  2290. var cubehelix = function(start, rotations, hue, gamma, lightness) {
  2291. if ( start === void 0 ) start=300;
  2292. if ( rotations === void 0 ) rotations=-1.5;
  2293. if ( hue === void 0 ) hue=1;
  2294. if ( gamma === void 0 ) gamma=1;
  2295. if ( lightness === void 0 ) lightness=[0,1];
  2296. var dh = 0, dl;
  2297. if (type$k(lightness) === 'array') {
  2298. dl = lightness[1] - lightness[0];
  2299. } else {
  2300. dl = 0;
  2301. lightness = [lightness, lightness];
  2302. }
  2303. var f = function(fract) {
  2304. var a = TWOPI$2 * (((start+120)/360) + (rotations * fract));
  2305. var l = pow$6(lightness[0] + (dl * fract), gamma);
  2306. var h = dh !== 0 ? hue[0] + (fract * dh) : hue;
  2307. var amp = (h * l * (1-l)) / 2;
  2308. var cos_a = cos$3(a);
  2309. var sin_a = sin$2(a);
  2310. var r = l + (amp * ((-0.14861 * cos_a) + (1.78277* sin_a)));
  2311. var g = l + (amp * ((-0.29227 * cos_a) - (0.90649* sin_a)));
  2312. var b = l + (amp * (+1.97294 * cos_a));
  2313. return chroma_1(clip_rgb$3([r*255,g*255,b*255,1]));
  2314. };
  2315. f.start = function(s) {
  2316. if ((s == null)) { return start; }
  2317. start = s;
  2318. return f;
  2319. };
  2320. f.rotations = function(r) {
  2321. if ((r == null)) { return rotations; }
  2322. rotations = r;
  2323. return f;
  2324. };
  2325. f.gamma = function(g) {
  2326. if ((g == null)) { return gamma; }
  2327. gamma = g;
  2328. return f;
  2329. };
  2330. f.hue = function(h) {
  2331. if ((h == null)) { return hue; }
  2332. hue = h;
  2333. if (type$k(hue) === 'array') {
  2334. dh = hue[1] - hue[0];
  2335. if (dh === 0) { hue = hue[1]; }
  2336. } else {
  2337. dh = 0;
  2338. }
  2339. return f;
  2340. };
  2341. f.lightness = function(h) {
  2342. if ((h == null)) { return lightness; }
  2343. if (type$k(h) === 'array') {
  2344. lightness = h;
  2345. dl = h[1] - h[0];
  2346. } else {
  2347. lightness = [h,h];
  2348. dl = 0;
  2349. }
  2350. return f;
  2351. };
  2352. f.scale = function () { return chroma_1.scale(f); };
  2353. f.hue(hue);
  2354. return f;
  2355. };
  2356. var digits = '0123456789abcdef';
  2357. var floor$2 = Math.floor;
  2358. var random = Math.random;
  2359. var random_1 = function () {
  2360. var code = '#';
  2361. for (var i=0; i<6; i++) {
  2362. code += digits.charAt(floor$2(random() * 16));
  2363. }
  2364. return new Color_1(code, 'hex');
  2365. };
  2366. var log$1 = Math.log;
  2367. var pow$7 = Math.pow;
  2368. var floor$3 = Math.floor;
  2369. var abs = Math.abs;
  2370. var analyze = function (data, key) {
  2371. if ( key === void 0 ) key=null;
  2372. var r = {
  2373. min: Number.MAX_VALUE,
  2374. max: Number.MAX_VALUE*-1,
  2375. sum: 0,
  2376. values: [],
  2377. count: 0
  2378. };
  2379. if (type(data) === 'object') {
  2380. data = Object.values(data);
  2381. }
  2382. data.forEach(function (val) {
  2383. if (key && type(val) === 'object') { val = val[key]; }
  2384. if (val !== undefined && val !== null && !isNaN(val)) {
  2385. r.values.push(val);
  2386. r.sum += val;
  2387. if (val < r.min) { r.min = val; }
  2388. if (val > r.max) { r.max = val; }
  2389. r.count += 1;
  2390. }
  2391. });
  2392. r.domain = [r.min, r.max];
  2393. r.limits = function (mode, num) { return limits(r, mode, num); };
  2394. return r;
  2395. };
  2396. var limits = function (data, mode, num) {
  2397. if ( mode === void 0 ) mode='equal';
  2398. if ( num === void 0 ) num=7;
  2399. if (type(data) == 'array') {
  2400. data = analyze(data);
  2401. }
  2402. var min = data.min;
  2403. var max = data.max;
  2404. var values = data.values.sort(function (a,b) { return a-b; });
  2405. if (num === 1) { return [min,max]; }
  2406. var limits = [];
  2407. if (mode.substr(0,1) === 'c') { // continuous
  2408. limits.push(min);
  2409. limits.push(max);
  2410. }
  2411. if (mode.substr(0,1) === 'e') { // equal interval
  2412. limits.push(min);
  2413. for (var i=1; i<num; i++) {
  2414. limits.push(min+((i/num)*(max-min)));
  2415. }
  2416. limits.push(max);
  2417. }
  2418. else if (mode.substr(0,1) === 'l') { // log scale
  2419. if (min <= 0) {
  2420. throw new Error('Logarithmic scales are only possible for values > 0');
  2421. }
  2422. var min_log = Math.LOG10E * log$1(min);
  2423. var max_log = Math.LOG10E * log$1(max);
  2424. limits.push(min);
  2425. for (var i$1=1; i$1<num; i$1++) {
  2426. limits.push(pow$7(10, min_log + ((i$1/num) * (max_log - min_log))));
  2427. }
  2428. limits.push(max);
  2429. }
  2430. else if (mode.substr(0,1) === 'q') { // quantile scale
  2431. limits.push(min);
  2432. for (var i$2=1; i$2<num; i$2++) {
  2433. var p = ((values.length-1) * i$2)/num;
  2434. var pb = floor$3(p);
  2435. if (pb === p) {
  2436. limits.push(values[pb]);
  2437. } else { // p > pb
  2438. var pr = p - pb;
  2439. limits.push((values[pb]*(1-pr)) + (values[pb+1]*pr));
  2440. }
  2441. }
  2442. limits.push(max);
  2443. }
  2444. else if (mode.substr(0,1) === 'k') { // k-means clustering
  2445. /*
  2446. implementation based on
  2447. http://code.google.com/p/figue/source/browse/trunk/figue.js#336
  2448. simplified for 1-d input values
  2449. */
  2450. var cluster;
  2451. var n = values.length;
  2452. var assignments = new Array(n);
  2453. var clusterSizes = new Array(num);
  2454. var repeat = true;
  2455. var nb_iters = 0;
  2456. var centroids = null;
  2457. // get seed values
  2458. centroids = [];
  2459. centroids.push(min);
  2460. for (var i$3=1; i$3<num; i$3++) {
  2461. centroids.push(min + ((i$3/num) * (max-min)));
  2462. }
  2463. centroids.push(max);
  2464. while (repeat) {
  2465. // assignment step
  2466. for (var j=0; j<num; j++) {
  2467. clusterSizes[j] = 0;
  2468. }
  2469. for (var i$4=0; i$4<n; i$4++) {
  2470. var value = values[i$4];
  2471. var mindist = Number.MAX_VALUE;
  2472. var best = (void 0);
  2473. for (var j$1=0; j$1<num; j$1++) {
  2474. var dist = abs(centroids[j$1]-value);
  2475. if (dist < mindist) {
  2476. mindist = dist;
  2477. best = j$1;
  2478. }
  2479. clusterSizes[best]++;
  2480. assignments[i$4] = best;
  2481. }
  2482. }
  2483. // update centroids step
  2484. var newCentroids = new Array(num);
  2485. for (var j$2=0; j$2<num; j$2++) {
  2486. newCentroids[j$2] = null;
  2487. }
  2488. for (var i$5=0; i$5<n; i$5++) {
  2489. cluster = assignments[i$5];
  2490. if (newCentroids[cluster] === null) {
  2491. newCentroids[cluster] = values[i$5];
  2492. } else {
  2493. newCentroids[cluster] += values[i$5];
  2494. }
  2495. }
  2496. for (var j$3=0; j$3<num; j$3++) {
  2497. newCentroids[j$3] *= 1/clusterSizes[j$3];
  2498. }
  2499. // check convergence
  2500. repeat = false;
  2501. for (var j$4=0; j$4<num; j$4++) {
  2502. if (newCentroids[j$4] !== centroids[j$4]) {
  2503. repeat = true;
  2504. break;
  2505. }
  2506. }
  2507. centroids = newCentroids;
  2508. nb_iters++;
  2509. if (nb_iters > 200) {
  2510. repeat = false;
  2511. }
  2512. }
  2513. // finished k-means clustering
  2514. // the next part is borrowed from gabrielflor.it
  2515. var kClusters = {};
  2516. for (var j$5=0; j$5<num; j$5++) {
  2517. kClusters[j$5] = [];
  2518. }
  2519. for (var i$6=0; i$6<n; i$6++) {
  2520. cluster = assignments[i$6];
  2521. kClusters[cluster].push(values[i$6]);
  2522. }
  2523. var tmpKMeansBreaks = [];
  2524. for (var j$6=0; j$6<num; j$6++) {
  2525. tmpKMeansBreaks.push(kClusters[j$6][0]);
  2526. tmpKMeansBreaks.push(kClusters[j$6][kClusters[j$6].length-1]);
  2527. }
  2528. tmpKMeansBreaks = tmpKMeansBreaks.sort(function (a,b){ return a-b; });
  2529. limits.push(tmpKMeansBreaks[0]);
  2530. for (var i$7=1; i$7 < tmpKMeansBreaks.length; i$7+= 2) {
  2531. var v = tmpKMeansBreaks[i$7];
  2532. if (!isNaN(v) && (limits.indexOf(v) === -1)) {
  2533. limits.push(v);
  2534. }
  2535. }
  2536. }
  2537. return limits;
  2538. };
  2539. var analyze_1 = {analyze: analyze, limits: limits};
  2540. var contrast = function (a, b) {
  2541. // WCAG contrast ratio
  2542. // see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
  2543. a = new Color_1(a);
  2544. b = new Color_1(b);
  2545. var l1 = a.luminance();
  2546. var l2 = b.luminance();
  2547. return l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05);
  2548. };
  2549. var sqrt$4 = Math.sqrt;
  2550. var atan2$2 = Math.atan2;
  2551. var abs$1 = Math.abs;
  2552. var cos$4 = Math.cos;
  2553. var PI$2 = Math.PI;
  2554. var deltaE = function(a, b, L, C) {
  2555. if ( L === void 0 ) L=1;
  2556. if ( C === void 0 ) C=1;
  2557. // Delta E (CMC)
  2558. // see http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CMC.html
  2559. a = new Color_1(a);
  2560. b = new Color_1(b);
  2561. var ref = Array.from(a.lab());
  2562. var L1 = ref[0];
  2563. var a1 = ref[1];
  2564. var b1 = ref[2];
  2565. var ref$1 = Array.from(b.lab());
  2566. var L2 = ref$1[0];
  2567. var a2 = ref$1[1];
  2568. var b2 = ref$1[2];
  2569. var c1 = sqrt$4((a1 * a1) + (b1 * b1));
  2570. var c2 = sqrt$4((a2 * a2) + (b2 * b2));
  2571. var sl = L1 < 16.0 ? 0.511 : (0.040975 * L1) / (1.0 + (0.01765 * L1));
  2572. var sc = ((0.0638 * c1) / (1.0 + (0.0131 * c1))) + 0.638;
  2573. var h1 = c1 < 0.000001 ? 0.0 : (atan2$2(b1, a1) * 180.0) / PI$2;
  2574. while (h1 < 0) { h1 += 360; }
  2575. while (h1 >= 360) { h1 -= 360; }
  2576. 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)));
  2577. var c4 = c1 * c1 * c1 * c1;
  2578. var f = sqrt$4(c4 / (c4 + 1900.0));
  2579. var sh = sc * (((f * t) + 1.0) - f);
  2580. var delL = L1 - L2;
  2581. var delC = c1 - c2;
  2582. var delA = a1 - a2;
  2583. var delB = b1 - b2;
  2584. var dH2 = ((delA * delA) + (delB * delB)) - (delC * delC);
  2585. var v1 = delL / (L * sl);
  2586. var v2 = delC / (C * sc);
  2587. var v3 = sh;
  2588. return sqrt$4((v1 * v1) + (v2 * v2) + (dH2 / (v3 * v3)));
  2589. };
  2590. // simple Euclidean distance
  2591. var distance = function(a, b, mode) {
  2592. if ( mode === void 0 ) mode='lab';
  2593. // Delta E (CIE 1976)
  2594. // see http://www.brucelindbloom.com/index.html?Equations.html
  2595. a = new Color_1(a);
  2596. b = new Color_1(b);
  2597. var l1 = a.get(mode);
  2598. var l2 = b.get(mode);
  2599. var sum_sq = 0;
  2600. for (var i in l1) {
  2601. var d = (l1[i] || 0) - (l2[i] || 0);
  2602. sum_sq += d*d;
  2603. }
  2604. return Math.sqrt(sum_sq);
  2605. };
  2606. var valid = function () {
  2607. var args = [], len = arguments.length;
  2608. while ( len-- ) args[ len ] = arguments[ len ];
  2609. try {
  2610. new (Function.prototype.bind.apply( Color_1, [ null ].concat( args) ));
  2611. return true;
  2612. } catch (e) {
  2613. return false;
  2614. }
  2615. };
  2616. // some pre-defined color scales:
  2617. var scales = {
  2618. cool: function cool() { return scale([chroma_1.hsl(180,1,.9), chroma_1.hsl(250,.7,.4)]) },
  2619. hot: function hot() { return scale(['#000','#f00','#ff0','#fff']).mode('rgb') }
  2620. };
  2621. /**
  2622. ColorBrewer colors for chroma.js
  2623. Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The
  2624. Pennsylvania State University.
  2625. Licensed under the Apache License, Version 2.0 (the "License");
  2626. you may not use this file except in compliance with the License.
  2627. You may obtain a copy of the License at
  2628. http://www.apache.org/licenses/LICENSE-2.0
  2629. Unless required by applicable law or agreed to in writing, software distributed
  2630. under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  2631. CONDITIONS OF ANY KIND, either express or implied. See the License for the
  2632. specific language governing permissions and limitations under the License.
  2633. */
  2634. var colorbrewer = {
  2635. // sequential
  2636. OrRd: ['#fff7ec', '#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'],
  2637. PuBu: ['#fff7fb', '#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858'],
  2638. BuPu: ['#f7fcfd', '#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#810f7c', '#4d004b'],
  2639. Oranges: ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704'],
  2640. BuGn: ['#f7fcfd', '#e5f5f9', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76', '#238b45', '#006d2c', '#00441b'],
  2641. YlOrBr: ['#ffffe5', '#fff7bc', '#fee391', '#fec44f', '#fe9929', '#ec7014', '#cc4c02', '#993404', '#662506'],
  2642. YlGn: ['#ffffe5', '#f7fcb9', '#d9f0a3', '#addd8e', '#78c679', '#41ab5d', '#238443', '#006837', '#004529'],
  2643. Reds: ['#fff5f0', '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', '#ef3b2c', '#cb181d', '#a50f15', '#67000d'],
  2644. RdPu: ['#fff7f3', '#fde0dd', '#fcc5c0', '#fa9fb5', '#f768a1', '#dd3497', '#ae017e', '#7a0177', '#49006a'],
  2645. Greens: ['#f7fcf5', '#e5f5e0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#006d2c', '#00441b'],
  2646. YlGnBu: ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58'],
  2647. Purples: ['#fcfbfd', '#efedf5', '#dadaeb', '#bcbddc', '#9e9ac8', '#807dba', '#6a51a3', '#54278f', '#3f007d'],
  2648. GnBu: ['#f7fcf0', '#e0f3db', '#ccebc5', '#a8ddb5', '#7bccc4', '#4eb3d3', '#2b8cbe', '#0868ac', '#084081'],
  2649. Greys: ['#ffffff', '#f0f0f0', '#d9d9d9', '#bdbdbd', '#969696', '#737373', '#525252', '#252525', '#000000'],
  2650. YlOrRd: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026'],
  2651. PuRd: ['#f7f4f9', '#e7e1ef', '#d4b9da', '#c994c7', '#df65b0', '#e7298a', '#ce1256', '#980043', '#67001f'],
  2652. Blues: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],
  2653. PuBuGn: ['#fff7fb', '#ece2f0', '#d0d1e6', '#a6bddb', '#67a9cf', '#3690c0', '#02818a', '#016c59', '#014636'],
  2654. Viridis: ['#440154', '#482777', '#3f4a8a', '#31678e', '#26838f', '#1f9d8a', '#6cce5a', '#b6de2b', '#fee825'],
  2655. // diverging
  2656. Spectral: ['#9e0142', '#d53e4f', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#e6f598', '#abdda4', '#66c2a5', '#3288bd', '#5e4fa2'],
  2657. RdYlGn: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850', '#006837'],
  2658. RdBu: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#f7f7f7', '#d1e5f0', '#92c5de', '#4393c3', '#2166ac', '#053061'],
  2659. PiYG: ['#8e0152', '#c51b7d', '#de77ae', '#f1b6da', '#fde0ef', '#f7f7f7', '#e6f5d0', '#b8e186', '#7fbc41', '#4d9221', '#276419'],
  2660. PRGn: ['#40004b', '#762a83', '#9970ab', '#c2a5cf', '#e7d4e8', '#f7f7f7', '#d9f0d3', '#a6dba0', '#5aae61', '#1b7837', '#00441b'],
  2661. RdYlBu: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'],
  2662. BrBG: ['#543005', '#8c510a', '#bf812d', '#dfc27d', '#f6e8c3', '#f5f5f5', '#c7eae5', '#80cdc1', '#35978f', '#01665e', '#003c30'],
  2663. RdGy: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#ffffff', '#e0e0e0', '#bababa', '#878787', '#4d4d4d', '#1a1a1a'],
  2664. PuOr: ['#7f3b08', '#b35806', '#e08214', '#fdb863', '#fee0b6', '#f7f7f7', '#d8daeb', '#b2abd2', '#8073ac', '#542788', '#2d004b'],
  2665. // qualitative
  2666. Set2: ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3'],
  2667. Accent: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666'],
  2668. Set1: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'],
  2669. Set3: ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f'],
  2670. Dark2: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'],
  2671. Paired: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],
  2672. Pastel2: ['#b3e2cd', '#fdcdac', '#cbd5e8', '#f4cae4', '#e6f5c9', '#fff2ae', '#f1e2cc', '#cccccc'],
  2673. Pastel1: ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2'],
  2674. };
  2675. // add lowercase aliases for case-insensitive matches
  2676. for (var i$1 = 0, list$1 = Object.keys(colorbrewer); i$1 < list$1.length; i$1 += 1) {
  2677. var key = list$1[i$1];
  2678. colorbrewer[key.toLowerCase()] = colorbrewer[key];
  2679. }
  2680. var colorbrewer_1 = colorbrewer;
  2681. // feel free to comment out anything to rollup
  2682. // a smaller chroma.js built
  2683. // io --> convert colors
  2684. // operators --> modify existing Colors
  2685. // interpolators
  2686. // generators -- > create new colors
  2687. chroma_1.average = average;
  2688. chroma_1.bezier = bezier_1;
  2689. chroma_1.blend = blend_1;
  2690. chroma_1.cubehelix = cubehelix;
  2691. chroma_1.mix = chroma_1.interpolate = mix;
  2692. chroma_1.random = random_1;
  2693. chroma_1.scale = scale;
  2694. // other utility methods
  2695. chroma_1.analyze = analyze_1.analyze;
  2696. chroma_1.contrast = contrast;
  2697. chroma_1.deltaE = deltaE;
  2698. chroma_1.distance = distance;
  2699. chroma_1.limits = analyze_1.limits;
  2700. chroma_1.valid = valid;
  2701. // scale
  2702. chroma_1.scales = scales;
  2703. // colors
  2704. chroma_1.colors = w3cx11_1;
  2705. chroma_1.brewer = colorbrewer_1;
  2706. var chroma_js = chroma_1;
  2707. return chroma_js;
  2708. })));
  2709. });
  2710. function generateColorVariables(key, format, colorStr, opacity, altFormats = []) {
  2711. const parsedColor = chroma(colorStr);
  2712. const alts = altFormats.reduce((a, alt) => {
  2713. a.push(...generateColorVariables(alt.id, alt.format, colorStr, opacity));
  2714. return a;
  2715. }, []);
  2716. switch (format) {
  2717. case "hex":
  2718. return [{ key, value: colorStr }, ...alts];
  2719. case "hsl":
  2720. return [
  2721. {
  2722. key,
  2723. value: parsedColor.css("hsl"),
  2724. },
  2725. ...alts,
  2726. ];
  2727. case "hsl-values": {
  2728. const hsl = parsedColor.hsl();
  2729. const alpha = opacity ? `,${parsedColor.alpha()}` : "";
  2730. const h = isNaN(hsl[0]) ? 0 : hsl[0];
  2731. return [
  2732. {
  2733. key,
  2734. value: `${h},${hsl[1] * 100}%,${hsl[2] * 100}%${alpha}`,
  2735. },
  2736. ...alts,
  2737. ];
  2738. }
  2739. case "hsl-split": {
  2740. const hsl = parsedColor.hsl();
  2741. const h = isNaN(hsl[0]) ? 0 : hsl[0];
  2742. const out = [
  2743. {
  2744. key: `${key}-h`,
  2745. value: h.toString(),
  2746. },
  2747. {
  2748. key: `${key}-s`,
  2749. value: (hsl[1] * 100).toString() + "%",
  2750. },
  2751. {
  2752. key: `${key}-l`,
  2753. value: (hsl[2] * 100).toString() + "%",
  2754. },
  2755. ...alts,
  2756. ];
  2757. if (opacity)
  2758. out.push({
  2759. key: `${key}-a`,
  2760. value: parsedColor.alpha().toString(),
  2761. });
  2762. return out;
  2763. }
  2764. case "rgb":
  2765. return [
  2766. {
  2767. key,
  2768. value: parsedColor.css(),
  2769. },
  2770. ...alts,
  2771. ];
  2772. case "rgb-values": {
  2773. const rgb = parsedColor.rgb();
  2774. const alpha = opacity ? `,${parsedColor.alpha()}` : "";
  2775. return [
  2776. {
  2777. key,
  2778. value: `${rgb[0]},${rgb[1]},${rgb[2]}${alpha}`,
  2779. },
  2780. ...alts,
  2781. ];
  2782. }
  2783. case "rgb-split": {
  2784. const rgb = parsedColor.rgb();
  2785. const out = [
  2786. {
  2787. key: `${key}-r`,
  2788. value: rgb[0].toString(),
  2789. },
  2790. {
  2791. key: `${key}-g`,
  2792. value: rgb[1].toString(),
  2793. },
  2794. {
  2795. key: `${key}-b`,
  2796. value: rgb[2].toString(),
  2797. },
  2798. ...alts,
  2799. ];
  2800. if (opacity)
  2801. out.push({
  2802. key: `${key}-a`,
  2803. value: parsedColor.alpha().toString(),
  2804. });
  2805. return out;
  2806. }
  2807. }
  2808. }
  2809. function pushColors(arr, id, from, to, format, step, pad) {
  2810. const scale = chroma.scale([from.trim(), to.trim()]).domain([0, 100]);
  2811. for (let i = 0; i <= 100; i++) {
  2812. if (i % step === 0) {
  2813. const c = scale(i);
  2814. arr.push(...generateColorVariables(`${id}-${i.toString().padStart(pad, "0")}`, format, c.css(), c.alpha() !== 1));
  2815. }
  2816. }
  2817. }
  2818. function getCSSVariables(settings, config, gradients, settingsManager) {
  2819. const vars = [];
  2820. const themedLight = [];
  2821. const themedDark = [];
  2822. const gradientCandidates = {};
  2823. const gradientCandidatesLight = {};
  2824. const gradientCandidatesDark = {};
  2825. const seenGradientSections = new Set();
  2826. for (const key in settings) {
  2827. const [sectionId, settingId, modifier] = key.split("@@");
  2828. const section = config[sectionId];
  2829. if (!section)
  2830. continue;
  2831. const setting = config[sectionId][settingId];
  2832. if (!setting)
  2833. continue;
  2834. const value = settings[key];
  2835. switch (setting.type) {
  2836. case "variable-number":
  2837. case "variable-number-slider":
  2838. const format = setting.format;
  2839. const val = value !== undefined ? value : setting.default;
  2840. vars.push({
  2841. key: setting.id,
  2842. value: `${val}${format || ""}`,
  2843. });
  2844. continue;
  2845. case "variable-text":
  2846. case "variable-select":
  2847. const format_text = setting;
  2848. let text = value !== undefined ? value.toString() : format_text.default.toString();
  2849. if (format_text.quotes) {
  2850. if (text !== `""`) {
  2851. text = `'${text}'`;
  2852. }
  2853. else {
  2854. text = ``;
  2855. }
  2856. }
  2857. vars.push({
  2858. key: setting.id,
  2859. value: text,
  2860. });
  2861. continue;
  2862. case "variable-color": {
  2863. if (!seenGradientSections.has(sectionId))
  2864. seenGradientSections.add(sectionId);
  2865. const colorSetting = setting;
  2866. const color = value !== undefined ? value.toString() : colorSetting.default;
  2867. vars.push(...generateColorVariables(setting.id, colorSetting.format, color, colorSetting.opacity, colorSetting["alt-format"]));
  2868. generateColorVariables(setting.id, "rgb", color, colorSetting.opacity).forEach((kv) => {
  2869. gradientCandidates[kv.key] = kv.value;
  2870. });
  2871. continue;
  2872. }
  2873. case "variable-themed-color": {
  2874. if (!seenGradientSections.has(sectionId))
  2875. seenGradientSections.add(sectionId);
  2876. const colorSetting = setting;
  2877. const color = value !== undefined
  2878. ? value.toString()
  2879. : colorSetting[modifier === "light" ? "default-light" : "default-dark"];
  2880. (modifier === "light" ? themedLight : themedDark).push(...generateColorVariables(setting.id, colorSetting.format, color, colorSetting.opacity, colorSetting["alt-format"]));
  2881. generateColorVariables(setting.id, "rgb", color, colorSetting.opacity).forEach((kv) => {
  2882. if (modifier === "light") {
  2883. gradientCandidatesLight[kv.key] = kv.value;
  2884. }
  2885. else {
  2886. gradientCandidatesDark[kv.key] = kv.value;
  2887. }
  2888. });
  2889. continue;
  2890. }
  2891. }
  2892. }
  2893. seenGradientSections.forEach((sectionId) => {
  2894. const g = gradients[sectionId];
  2895. if (!g)
  2896. return;
  2897. g.forEach((def) => {
  2898. var _a, _b, _c;
  2899. const { from, to, format, step, id, pad = 0 } = def;
  2900. if (gradientCandidatesLight[from]) {
  2901. const fromColor = gradientCandidatesLight[from];
  2902. const toColor = gradientCandidatesLight[to] || ((_a = settingsManager.plugin.getCSSVar(to).light) === null || _a === void 0 ? void 0 : _a.trim());
  2903. if (toColor) {
  2904. pushColors(themedLight, id, fromColor, toColor, format, step, pad);
  2905. }
  2906. }
  2907. if (gradientCandidatesDark[from]) {
  2908. const fromColor = gradientCandidatesDark[from];
  2909. const toColor = gradientCandidatesDark[to] || ((_b = settingsManager.plugin.getCSSVar(to).dark) === null || _b === void 0 ? void 0 : _b.trim());
  2910. if (toColor) {
  2911. pushColors(themedDark, id, fromColor, toColor, format, step, pad);
  2912. }
  2913. }
  2914. if (gradientCandidates[from]) {
  2915. const fromColor = gradientCandidates[from];
  2916. const toColor = gradientCandidates[to] || ((_c = settingsManager.plugin.getCSSVar(to).current) === null || _c === void 0 ? void 0 : _c.trim());
  2917. if (toColor) {
  2918. pushColors(vars, id, fromColor, toColor, format, step, pad);
  2919. }
  2920. }
  2921. });
  2922. });
  2923. return [vars, themedLight, themedDark];
  2924. }
  2925. class CSSSettingsManager {
  2926. constructor(plugin) {
  2927. this.config = {};
  2928. this.gradients = {};
  2929. this.plugin = plugin;
  2930. this.settings = {};
  2931. this.styleTag = document.createElement("style");
  2932. this.styleTag.id = "css-settings-manager";
  2933. document.getElementsByTagName("head")[0].appendChild(this.styleTag);
  2934. }
  2935. cleanup() {
  2936. this.styleTag.remove();
  2937. this.removeClasses();
  2938. }
  2939. save() {
  2940. return __awaiter(this, void 0, void 0, function* () {
  2941. yield this.plugin.saveData(this.settings);
  2942. this.setCSSVariables();
  2943. });
  2944. }
  2945. load() {
  2946. return __awaiter(this, void 0, void 0, function* () {
  2947. this.settings = Object.assign({}, yield this.plugin.loadData());
  2948. });
  2949. }
  2950. initClasses() {
  2951. Object.keys(this.config).forEach((section) => {
  2952. const config = this.config[section];
  2953. Object.keys(config).forEach((settingId) => {
  2954. const setting = config[settingId];
  2955. if (setting.type === "class-toggle") {
  2956. const classToggle = setting;
  2957. let value = this.getSetting(section, settingId);
  2958. if (value === true || (value === undefined && classToggle.default === true)) {
  2959. document.body.classList.add(setting.id);
  2960. }
  2961. }
  2962. else if (setting.type === "class-select") {
  2963. const multiToggle = setting;
  2964. let value = this.getSetting(section, settingId);
  2965. if (value === undefined && !!multiToggle.default) {
  2966. value = multiToggle.default;
  2967. }
  2968. else if (value === undefined) {
  2969. value = "none";
  2970. }
  2971. if (value !== "none") {
  2972. document.body.classList.add(value);
  2973. }
  2974. }
  2975. });
  2976. });
  2977. }
  2978. removeClasses() {
  2979. Object.keys(this.config).forEach((section) => {
  2980. const config = this.config[section];
  2981. Object.keys(config).forEach((settingId) => {
  2982. const setting = config[settingId];
  2983. if (setting.type === "class-toggle") {
  2984. if (this.getSetting(section, settingId)) {
  2985. document.body.classList.remove(setting.id);
  2986. }
  2987. }
  2988. });
  2989. });
  2990. }
  2991. setCSSVariables() {
  2992. const [vars, themedLight, themedDark] = getCSSVariables(this.settings, this.config, this.gradients, this);
  2993. this.styleTag.innerText = `
  2994. body.css-settings-manager {
  2995. ${vars.reduce((combined, current) => {
  2996. return combined + `--${current.key}: ${current.value}; `;
  2997. }, "")}
  2998. }
  2999. body.theme-light.css-settings-manager {
  3000. ${themedLight.reduce((combined, current) => {
  3001. return combined + `--${current.key}: ${current.value}; `;
  3002. }, "")}
  3003. }
  3004. body.theme-dark.css-settings-manager {
  3005. ${themedDark.reduce((combined, current) => {
  3006. return combined + `--${current.key}: ${current.value}; `;
  3007. }, "")}
  3008. }
  3009. `
  3010. .trim()
  3011. .replace(/[\r\n\s]+/g, " ");
  3012. }
  3013. setConfig(settings) {
  3014. this.config = {};
  3015. this.gradients = {};
  3016. settings.forEach((s) => {
  3017. this.config[s.id] = {};
  3018. s.settings.forEach((setting) => {
  3019. this.config[s.id][setting.id] = setting;
  3020. if (setting.type === "color-gradient") {
  3021. if (!this.gradients[s.id])
  3022. this.gradients[s.id] = [];
  3023. this.gradients[s.id].push(setting);
  3024. }
  3025. });
  3026. });
  3027. let pruned = false;
  3028. for (const key in this.settings) {
  3029. const [sectionId, settingId] = key.split("@@");
  3030. if (this.config[sectionId] && !this.config[sectionId][settingId]) {
  3031. delete this.settings[key];
  3032. pruned = true;
  3033. }
  3034. }
  3035. if (pruned) {
  3036. this.save();
  3037. }
  3038. else {
  3039. this.setCSSVariables();
  3040. }
  3041. }
  3042. getSetting(sectionId, settingId) {
  3043. return this.settings[`${sectionId}@@${settingId}`];
  3044. }
  3045. getSettings(sectionId, ids) {
  3046. return ids.reduce((settings, id) => {
  3047. const fullId = `${sectionId}@@${id}`;
  3048. const alts = ["dark", "light"];
  3049. if (this.settings[fullId]) {
  3050. settings[fullId] = this.settings[fullId];
  3051. }
  3052. alts.forEach((alt) => {
  3053. const id = `${fullId}@@${alt}`;
  3054. if (this.settings[id]) {
  3055. settings[id] = this.settings[id];
  3056. }
  3057. });
  3058. return settings;
  3059. }, {});
  3060. }
  3061. setSetting(sectionId, settingId, value) {
  3062. this.settings[`${sectionId}@@${settingId}`] = value;
  3063. this.save();
  3064. }
  3065. setSettings(settings) {
  3066. Object.keys(settings).forEach((id) => {
  3067. this.settings[id] = settings[id];
  3068. });
  3069. return this.save();
  3070. }
  3071. clearSetting(sectionId, settingId) {
  3072. delete this.settings[`${sectionId}@@${settingId}`];
  3073. this.save();
  3074. }
  3075. clearSection(sectionId) {
  3076. Object.keys(this.settings).forEach((key) => {
  3077. const [section] = key.split("@@");
  3078. if (section === sectionId) {
  3079. delete this.settings[key];
  3080. }
  3081. });
  3082. this.save();
  3083. }
  3084. export(section, config) {
  3085. new ExportModal(this.plugin.app, this.plugin, section, config).open();
  3086. }
  3087. import() {
  3088. new ImportModal(this.plugin.app, this.plugin).open();
  3089. }
  3090. }
  3091. class ExportModal extends obsidian.Modal {
  3092. constructor(app, plugin, section, config) {
  3093. super(app);
  3094. this.plugin = plugin;
  3095. this.config = config;
  3096. this.section = section;
  3097. }
  3098. onOpen() {
  3099. let { contentEl, modalEl } = this;
  3100. modalEl.addClass("modal-style-settings");
  3101. new obsidian.Setting(contentEl).setName(`Export settings for: ${this.section}`).then((setting) => {
  3102. const output = JSON.stringify(this.config, null, 2);
  3103. // Build a copy to clipboard link
  3104. setting.controlEl.createEl("a", {
  3105. cls: "style-settings-copy",
  3106. text: "Copy to clipboard",
  3107. href: "#",
  3108. }, (copyButton) => {
  3109. new obsidian.TextAreaComponent(contentEl).setValue(output).then((textarea) => {
  3110. copyButton.addEventListener("click", (e) => {
  3111. e.preventDefault();
  3112. // Select the textarea contents and copy them to the clipboard
  3113. textarea.inputEl.select();
  3114. textarea.inputEl.setSelectionRange(0, 99999);
  3115. document.execCommand("copy");
  3116. copyButton.addClass("success");
  3117. setTimeout(() => {
  3118. // If the button is still in the dom, remove the success class
  3119. if (copyButton.parentNode) {
  3120. copyButton.removeClass("success");
  3121. }
  3122. }, 2000);
  3123. });
  3124. });
  3125. });
  3126. // Build a download link
  3127. setting.controlEl.createEl("a", {
  3128. cls: "style-settings-download",
  3129. text: "Download",
  3130. attr: {
  3131. download: "style-settings.json",
  3132. href: `data:application/json;charset=utf-8,${encodeURIComponent(output)}`,
  3133. },
  3134. });
  3135. });
  3136. }
  3137. onClose() {
  3138. let { contentEl } = this;
  3139. contentEl.empty();
  3140. }
  3141. }
  3142. class ImportModal extends obsidian.Modal {
  3143. constructor(app, plugin) {
  3144. super(app);
  3145. this.plugin = plugin;
  3146. }
  3147. onOpen() {
  3148. let { contentEl, modalEl } = this;
  3149. modalEl.addClass("modal-style-settings");
  3150. new obsidian.Setting(contentEl)
  3151. .setName("Import style setting")
  3152. .setDesc("Import an entire or partial configuration. Warning: this may override existing settings");
  3153. new obsidian.Setting(contentEl).then((setting) => {
  3154. // Build an error message container
  3155. const errorSpan = createSpan({
  3156. cls: "style-settings-import-error",
  3157. text: "Error importing config",
  3158. });
  3159. setting.nameEl.appendChild(errorSpan);
  3160. // Attempt to parse the imported data and close if successful
  3161. const importAndClose = (str) => __awaiter(this, void 0, void 0, function* () {
  3162. if (str) {
  3163. try {
  3164. const importedSettings = JSON.parse(str);
  3165. yield this.plugin.settingsManager.setSettings(importedSettings);
  3166. this.plugin.settingsTab.display();
  3167. this.close();
  3168. }
  3169. catch (e) {
  3170. errorSpan.addClass("active");
  3171. errorSpan.setText(`Error importing style settings: ${e}`);
  3172. }
  3173. }
  3174. else {
  3175. errorSpan.addClass("active");
  3176. errorSpan.setText(`Error importing style settings: config is empty`);
  3177. }
  3178. });
  3179. // Build a file input
  3180. setting.controlEl.createEl("input", {
  3181. cls: "style-settings-import-input",
  3182. attr: {
  3183. id: "style-settings-import-input",
  3184. name: "style-settings-import-input",
  3185. type: "file",
  3186. accept: ".json",
  3187. },
  3188. }, (importInput) => {
  3189. // Set up a FileReader so we can parse the file contents
  3190. importInput.addEventListener("change", (e) => {
  3191. const reader = new FileReader();
  3192. reader.onload = (e) => __awaiter(this, void 0, void 0, function* () {
  3193. yield importAndClose(e.target.result.toString().trim());
  3194. });
  3195. reader.readAsText(e.target.files[0]);
  3196. });
  3197. });
  3198. // Build a label we will style as a link
  3199. setting.controlEl.createEl("label", {
  3200. cls: "style-settings-import-label",
  3201. text: "Import from file",
  3202. attr: {
  3203. for: "style-settings-import-input",
  3204. },
  3205. });
  3206. new obsidian.TextAreaComponent(contentEl).setPlaceholder("Paste config here...").then((ta) => {
  3207. new obsidian.ButtonComponent(contentEl).setButtonText("Save").onClick(() => __awaiter(this, void 0, void 0, function* () {
  3208. yield importAndClose(ta.getValue().trim());
  3209. }));
  3210. });
  3211. });
  3212. }
  3213. onClose() {
  3214. let { contentEl } = this;
  3215. contentEl.empty();
  3216. }
  3217. }
  3218. var pickr_min = createCommonjsModule(function (module, exports) {
  3219. /*! Pickr 1.8.4 MIT | https://github.com/Simonwep/pickr */
  3220. !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})()}));
  3221. });
  3222. var Pickr = /*@__PURE__*/getDefaultExportFromCjs(pickr_min);
  3223. const ar = {};
  3224. const cz = {};
  3225. const da = {};
  3226. const de = {
  3227. "Default:": "Standard:",
  3228. "Error:": "Fehler:",
  3229. "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",
  3230. "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",
  3231. "missing default value, or value is not in a valid color format": "Fehlender standard Wert oder Wert ist in keinem validen Farb-Format",
  3232. "missing default value": "Fehlender standard Wert",
  3233. };
  3234. const en = {
  3235. "Default:": "Default:",
  3236. "Error:": "Error:",
  3237. "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",
  3238. "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",
  3239. "missing default value, or value is not in a valid color format": "missing default value, or value is not in a valid color format",
  3240. "missing default value": "missing default value",
  3241. };
  3242. const es = {};
  3243. const fr = {};
  3244. const hi = {};
  3245. const id = {};
  3246. const it = {};
  3247. const ja = {};
  3248. const ko = {};
  3249. const nl = {
  3250. "Default:": "Standaard:",
  3251. "Error:": "Error:",
  3252. "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",
  3253. "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",
  3254. "missing default value, or value is not in a valid color format": "Geen standaard waarde, of de waarde is niet in het goede formaat",
  3255. "missing default value": "Geen standaard waarde",
  3256. };
  3257. const no = {};
  3258. const pl = {};
  3259. const pt = {};
  3260. const ptBr = {};
  3261. const ro = {};
  3262. const ru = {};
  3263. const sq = {};
  3264. const tr = {};
  3265. const uk = {};
  3266. const zh = {
  3267. "Default:": "默认:",
  3268. "Error:": "错误:",
  3269. "missing default light value, or value is not in a valid color format": "缺少默认的浅色模式色值,或该色值没有采用一个有效的颜色格式",
  3270. "missing default dark value, or value is not in a valid color format": "缺少默认的深色模式色值,或该色值没有采用一个有效的颜色格式",
  3271. "missing default value, or value is not in a valid color format": "缺少默认色值,或该色值没有采用一个有效的颜色格式",
  3272. "missing default value": "缺少默认色值",
  3273. };
  3274. const zhTw = {};
  3275. const lang = window.localStorage.getItem("language");
  3276. const localeMap = {
  3277. ar,
  3278. cz,
  3279. da,
  3280. de,
  3281. en,
  3282. es,
  3283. fr,
  3284. hi,
  3285. id,
  3286. it,
  3287. ja,
  3288. ko,
  3289. nl,
  3290. no,
  3291. pl,
  3292. "pt-BR": ptBr,
  3293. pt,
  3294. ro,
  3295. ru,
  3296. sq,
  3297. tr,
  3298. uk,
  3299. "zh-TW": zhTw,
  3300. zh,
  3301. };
  3302. const locale = localeMap[lang || "en"];
  3303. function t(str) {
  3304. if (!locale) {
  3305. console.error("Error: Style Settings locale not found", lang);
  3306. }
  3307. return (locale && locale[str]) || en[str];
  3308. }
  3309. const resetTooltip = "Restore default";
  3310. function sanitizeText(str) {
  3311. if (str === "") {
  3312. return `""`;
  3313. }
  3314. return str.replace(/[;<>]/g, "");
  3315. }
  3316. function createDescription(description, def, defLabel) {
  3317. const fragment = createFragment();
  3318. if (description) {
  3319. fragment.appendChild(document.createTextNode(description));
  3320. }
  3321. if (def) {
  3322. const small = createEl("small");
  3323. small.appendChild(createEl("strong", { text: `${t("Default:")} ` }));
  3324. small.appendChild(document.createTextNode(defLabel || def));
  3325. const div = createEl("div");
  3326. div.appendChild(small);
  3327. fragment.appendChild(div);
  3328. }
  3329. return fragment;
  3330. }
  3331. function getTitle(config) {
  3332. if (lang) {
  3333. return config[`title.${lang}`] || config.title;
  3334. }
  3335. return config.title;
  3336. }
  3337. function getDescription(config) {
  3338. if (lang) {
  3339. return (config[`description.${lang}`] ||
  3340. config.description);
  3341. }
  3342. return config.description;
  3343. }
  3344. function createHeading(opts) {
  3345. new obsidian.Setting(opts.containerEl)
  3346. .setHeading()
  3347. .setClass("style-settings-heading")
  3348. .setName(getTitle(opts.config))
  3349. .setDesc(getDescription(opts.config) ? getDescription(opts.config) : "")
  3350. .then((setting) => {
  3351. if (opts.config.collapsed)
  3352. setting.settingEl.addClass("is-collapsed");
  3353. setting.settingEl.dataset.level = opts.config.level.toString();
  3354. setting.settingEl.dataset.id = opts.config.id;
  3355. const iconContainer = createSpan({
  3356. cls: "style-settings-collapse-indicator",
  3357. });
  3358. obsidian.setIcon(iconContainer, "right-triangle");
  3359. setting.nameEl.prepend(iconContainer);
  3360. setting.settingEl.addEventListener("click", (e) => {
  3361. setting.settingEl.toggleClass("is-collapsed", !setting.settingEl.hasClass("is-collapsed"));
  3362. });
  3363. if (opts.config.resetFn) {
  3364. setting.addExtraButton((b) => {
  3365. b.setIcon("reset")
  3366. .setTooltip("Reset all settings to default")
  3367. .onClick(opts.config.resetFn);
  3368. });
  3369. }
  3370. setting.addExtraButton((b) => {
  3371. b.setIcon("install")
  3372. .setTooltip("Export settings")
  3373. .then((b) => {
  3374. b.extraSettingsEl.onClickEvent((e) => {
  3375. e.stopPropagation();
  3376. const title = opts.sectionName === getTitle(opts.config)
  3377. ? getTitle(opts.config)
  3378. : `${opts.sectionName} > ${getTitle(opts.config)}`;
  3379. opts.settingsManager.export(title, opts.settingsManager.getSettings(opts.sectionId, opts.children));
  3380. });
  3381. });
  3382. });
  3383. });
  3384. }
  3385. function createClassToggle(opts) {
  3386. const { sectionId, config, containerEl, settingsManager } = opts;
  3387. let toggleComponent;
  3388. new obsidian.Setting(containerEl)
  3389. .setName(getTitle(config))
  3390. .setDesc(getDescription(config) || "")
  3391. .addToggle((toggle) => {
  3392. const value = settingsManager.getSetting(sectionId, config.id);
  3393. toggle
  3394. .setValue(value !== undefined ? !!value : !!config.default)
  3395. .onChange((value) => {
  3396. settingsManager.setSetting(sectionId, config.id, value);
  3397. if (value) {
  3398. document.body.classList.add(config.id);
  3399. }
  3400. else {
  3401. document.body.classList.remove(config.id);
  3402. }
  3403. });
  3404. toggleComponent = toggle;
  3405. })
  3406. .addExtraButton((b) => {
  3407. b.setIcon("reset");
  3408. b.onClick(() => {
  3409. const value = !!config.default;
  3410. toggleComponent.setValue(value);
  3411. if (value) {
  3412. document.body.classList.add(config.id);
  3413. }
  3414. else {
  3415. document.body.classList.remove(config.id);
  3416. }
  3417. settingsManager.clearSetting(sectionId, config.id);
  3418. });
  3419. b.setTooltip(resetTooltip);
  3420. })
  3421. .then((setting) => {
  3422. setting.settingEl.dataset.id = opts.config.id;
  3423. });
  3424. }
  3425. function createClassMultiToggle(opts) {
  3426. const { sectionId, config, containerEl, settingsManager } = opts;
  3427. let dropdownComponent;
  3428. if (typeof config.default !== "string") {
  3429. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default value")}`);
  3430. }
  3431. let prevValue = settingsManager.getSetting(sectionId, config.id);
  3432. if (prevValue === undefined && !!config.default) {
  3433. prevValue = config.default;
  3434. }
  3435. else if (prevValue === undefined) {
  3436. prevValue = "none";
  3437. }
  3438. const defaultOption = config.default
  3439. ? config.options.find((o) => {
  3440. if (typeof o === "string") {
  3441. return o === config.default;
  3442. }
  3443. return o.value === config.default;
  3444. })
  3445. : undefined;
  3446. let defaultLabel = undefined;
  3447. if (defaultOption && typeof defaultOption === "string") {
  3448. defaultLabel = defaultOption;
  3449. }
  3450. else if (defaultOption && typeof defaultOption === "object") {
  3451. defaultLabel = defaultOption.label;
  3452. }
  3453. new obsidian.Setting(containerEl)
  3454. .setName(getTitle(config))
  3455. .setDesc(createDescription(getDescription(config), config.default, defaultLabel))
  3456. .addDropdown((dropdown) => {
  3457. if (config.allowEmpty) {
  3458. dropdown.addOption("none", "");
  3459. }
  3460. config.options.forEach((o) => {
  3461. if (typeof o === "string") {
  3462. dropdown.addOption(o, o);
  3463. }
  3464. else {
  3465. dropdown.addOption(o.value, o.label);
  3466. }
  3467. });
  3468. dropdown.setValue(prevValue).onChange((value) => {
  3469. settingsManager.setSetting(sectionId, config.id, value);
  3470. if (value !== "none") {
  3471. document.body.classList.add(value);
  3472. }
  3473. if (prevValue) {
  3474. document.body.classList.remove(prevValue);
  3475. }
  3476. prevValue = value;
  3477. });
  3478. dropdownComponent = dropdown;
  3479. })
  3480. .addExtraButton((b) => {
  3481. b.setIcon("reset");
  3482. b.onClick(() => {
  3483. const value = config.default || "none";
  3484. dropdownComponent.setValue(config.default || "none");
  3485. if (value !== "none") {
  3486. document.body.classList.add(value);
  3487. }
  3488. if (prevValue) {
  3489. document.body.classList.remove(prevValue);
  3490. }
  3491. settingsManager.clearSetting(sectionId, config.id);
  3492. });
  3493. b.setTooltip(resetTooltip);
  3494. })
  3495. .then((setting) => {
  3496. setting.settingEl.dataset.id = opts.config.id;
  3497. });
  3498. }
  3499. function createVariableText(opts) {
  3500. const { sectionId, config, containerEl, settingsManager } = opts;
  3501. let textComponent;
  3502. if (typeof config.default !== "string") {
  3503. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default value")}`);
  3504. }
  3505. new obsidian.Setting(containerEl)
  3506. .setName(getTitle(config))
  3507. .setDesc(createDescription(getDescription(config), config.default))
  3508. .addText((text) => {
  3509. let value = settingsManager.getSetting(sectionId, config.id);
  3510. const onChange = obsidian.debounce((value) => {
  3511. settingsManager.setSetting(sectionId, config.id, sanitizeText(value));
  3512. }, 250, true);
  3513. if (config.quotes && value === `""`) {
  3514. value = ``;
  3515. }
  3516. text
  3517. .setValue(value ? value.toString() : config.default)
  3518. .onChange(onChange);
  3519. textComponent = text;
  3520. })
  3521. .addExtraButton((b) => {
  3522. b.setIcon("reset");
  3523. b.onClick(() => {
  3524. textComponent.setValue(config.default);
  3525. settingsManager.clearSetting(sectionId, config.id);
  3526. });
  3527. b.setTooltip(resetTooltip);
  3528. })
  3529. .then((setting) => {
  3530. setting.settingEl.dataset.id = opts.config.id;
  3531. });
  3532. }
  3533. function createVariableNumber(opts) {
  3534. const { sectionId, config, containerEl, settingsManager } = opts;
  3535. let textComponent;
  3536. if (typeof config.default !== "number") {
  3537. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default value")}`);
  3538. }
  3539. new obsidian.Setting(containerEl)
  3540. .setName(getTitle(config))
  3541. .setDesc(createDescription(getDescription(config), config.default.toString(10)))
  3542. .addText((text) => {
  3543. const value = settingsManager.getSetting(sectionId, config.id);
  3544. const onChange = obsidian.debounce((value) => {
  3545. const isFloat = /\./.test(value);
  3546. settingsManager.setSetting(sectionId, config.id, isFloat ? parseFloat(value) : parseInt(value, 10));
  3547. }, 250, true);
  3548. text
  3549. .setValue(value !== undefined ? value.toString() : config.default.toString())
  3550. .onChange(onChange);
  3551. textComponent = text;
  3552. })
  3553. .addExtraButton((b) => {
  3554. b.setIcon("reset");
  3555. b.onClick(() => {
  3556. textComponent.setValue(config.default.toString());
  3557. settingsManager.clearSetting(sectionId, config.id);
  3558. });
  3559. b.setTooltip(resetTooltip);
  3560. })
  3561. .then((setting) => {
  3562. setting.settingEl.dataset.id = opts.config.id;
  3563. });
  3564. }
  3565. function createVariableNumberSlider(opts) {
  3566. const { sectionId, config, containerEl, settingsManager } = opts;
  3567. let sliderComponent;
  3568. if (typeof config.default !== "number") {
  3569. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default value")}`);
  3570. }
  3571. new obsidian.Setting(containerEl)
  3572. .setName(getTitle(config))
  3573. .setDesc(createDescription(getDescription(config), config.default.toString(10)))
  3574. .addSlider((slider) => {
  3575. const value = settingsManager.getSetting(sectionId, config.id);
  3576. const onChange = obsidian.debounce((value) => {
  3577. settingsManager.setSetting(sectionId, config.id, value);
  3578. }, 250, true);
  3579. slider
  3580. .setDynamicTooltip()
  3581. .setLimits(config.min, config.max, config.step)
  3582. .setValue(value !== undefined ? value : config.default)
  3583. .onChange(onChange);
  3584. sliderComponent = slider;
  3585. })
  3586. .addExtraButton((b) => {
  3587. b.setIcon("reset");
  3588. b.onClick(() => {
  3589. sliderComponent.setValue(config.default);
  3590. settingsManager.clearSetting(sectionId, config.id);
  3591. });
  3592. b.setTooltip(resetTooltip);
  3593. })
  3594. .then((setting) => {
  3595. setting.settingEl.dataset.id = opts.config.id;
  3596. });
  3597. }
  3598. function createVariableSelect(opts) {
  3599. const { sectionId, config, containerEl, settingsManager } = opts;
  3600. let dropdownComponent;
  3601. if (typeof config.default !== "string") {
  3602. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default value")}`);
  3603. }
  3604. const defaultOption = config.default
  3605. ? config.options.find((o) => {
  3606. if (typeof o === "string") {
  3607. return o === config.default;
  3608. }
  3609. return o.value === config.default;
  3610. })
  3611. : undefined;
  3612. let defaultLabel = undefined;
  3613. if (defaultOption && typeof defaultOption === "string") {
  3614. defaultLabel = defaultOption;
  3615. }
  3616. else if (defaultOption && typeof defaultOption === "object") {
  3617. defaultLabel = defaultOption.label;
  3618. }
  3619. new obsidian.Setting(containerEl)
  3620. .setName(getTitle(config))
  3621. .setDesc(createDescription(getDescription(config), config.default, defaultLabel))
  3622. .addDropdown((dropdown) => {
  3623. const value = settingsManager.getSetting(sectionId, config.id);
  3624. config.options.forEach((o) => {
  3625. if (typeof o === "string") {
  3626. dropdown.addOption(o, o);
  3627. }
  3628. else {
  3629. dropdown.addOption(o.value, o.label);
  3630. }
  3631. });
  3632. dropdown
  3633. .setValue(value !== undefined ? value : config.default)
  3634. .onChange((value) => {
  3635. settingsManager.setSetting(sectionId, config.id, value);
  3636. });
  3637. dropdownComponent = dropdown;
  3638. })
  3639. .addExtraButton((b) => {
  3640. b.setIcon("reset");
  3641. b.onClick(() => {
  3642. dropdownComponent.setValue(config.default);
  3643. settingsManager.clearSetting(sectionId, config.id);
  3644. });
  3645. b.setTooltip(resetTooltip);
  3646. })
  3647. .then((setting) => {
  3648. setting.settingEl.dataset.id = opts.config.id;
  3649. });
  3650. }
  3651. function getPickrSettings(opts) {
  3652. const { el, isView, containerEl, swatches, opacity, defaultColor } = opts;
  3653. return {
  3654. el,
  3655. container: isView ? document.body : containerEl,
  3656. theme: "nano",
  3657. swatches,
  3658. lockOpacity: !opacity,
  3659. default: defaultColor,
  3660. position: "left-middle",
  3661. components: {
  3662. preview: true,
  3663. hue: true,
  3664. opacity: !!opacity,
  3665. interaction: {
  3666. hex: true,
  3667. rgba: true,
  3668. hsla: true,
  3669. input: true,
  3670. cancel: true,
  3671. save: true,
  3672. },
  3673. },
  3674. };
  3675. }
  3676. function onPickrCancel(instance) {
  3677. instance.hide();
  3678. }
  3679. function isValidDefaultColor(color) {
  3680. return /^(#|rgb|hsl)/.test(color);
  3681. }
  3682. function createVariableColor(opts) {
  3683. var _a;
  3684. const { isView, sectionId, config, containerEl, settingsManager } = opts;
  3685. if (typeof config.default !== "string" ||
  3686. !isValidDefaultColor(config.default)) {
  3687. config.default = (_a = settingsManager.plugin.getCSSVar(config.id).current) === null || _a === void 0 ? void 0 : _a.trim();
  3688. }
  3689. if (typeof config.default !== "string" ||
  3690. !isValidDefaultColor(config.default)) {
  3691. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default value, or value is not in a valid color format")}`);
  3692. }
  3693. const value = settingsManager.getSetting(sectionId, config.id);
  3694. const swatches = [];
  3695. let pickr;
  3696. if (config.default) {
  3697. swatches.push(config.default);
  3698. }
  3699. if (value !== undefined) {
  3700. swatches.push(value);
  3701. }
  3702. new obsidian.Setting(containerEl)
  3703. .setName(getTitle(config))
  3704. .setDesc(createDescription(getDescription(config), config.default))
  3705. .then((setting) => {
  3706. setting.settingEl.dataset.id = opts.config.id;
  3707. pickr = Pickr.create(getPickrSettings({
  3708. isView,
  3709. el: setting.controlEl.createDiv({ cls: "picker" }),
  3710. containerEl,
  3711. swatches,
  3712. opacity: config.opacity,
  3713. defaultColor: value !== undefined ? value : config.default,
  3714. }))
  3715. .on("save", (color, instance) => {
  3716. if (!color)
  3717. return;
  3718. settingsManager.setSetting(sectionId, config.id, color.toHEXA().toString());
  3719. instance.hide();
  3720. instance.addSwatch(color.toHEXA().toString());
  3721. })
  3722. .on("show", () => {
  3723. const { result } = pickr.getRoot().interaction;
  3724. requestAnimationFrame(() => requestAnimationFrame(() => result.select()));
  3725. })
  3726. .on("cancel", onPickrCancel);
  3727. })
  3728. .addExtraButton((b) => {
  3729. b.setIcon("reset")
  3730. .onClick(() => {
  3731. pickr.setColor(config.default);
  3732. settingsManager.clearSetting(sectionId, config.id);
  3733. })
  3734. .setTooltip(resetTooltip);
  3735. });
  3736. return () => pickr.destroyAndRemove();
  3737. }
  3738. function createVariableThemedColor(opts) {
  3739. const { sectionId, isView, config, containerEl, settingsManager } = opts;
  3740. if (typeof config["default-light"] !== "string" ||
  3741. !isValidDefaultColor(config["default-light"])) {
  3742. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default light value, or value is not in a valid color format")}`);
  3743. }
  3744. if (typeof config["default-dark"] !== "string" ||
  3745. !isValidDefaultColor(config["default-dark"])) {
  3746. return console.error(`${t("Error:")} ${getTitle(config)} ${t("missing default dark value, or value is not in a valid color format")}`);
  3747. }
  3748. const idLight = `${config.id}@@light`;
  3749. const idDark = `${config.id}@@dark`;
  3750. const valueLight = settingsManager.getSetting(sectionId, idLight);
  3751. const valueDark = settingsManager.getSetting(sectionId, idDark);
  3752. const swatchesLight = [];
  3753. const swatchesDark = [];
  3754. let pickrLight;
  3755. let pickrDark;
  3756. if (config["default-light"]) {
  3757. swatchesLight.push(config["default-light"]);
  3758. }
  3759. if (valueLight !== undefined) {
  3760. swatchesLight.push(valueLight);
  3761. }
  3762. if (config["default-dark"]) {
  3763. swatchesDark.push(config["default-dark"]);
  3764. }
  3765. if (valueDark !== undefined) {
  3766. swatchesDark.push(valueDark);
  3767. }
  3768. const onSave = (id) => (color, instance) => {
  3769. if (!color)
  3770. return;
  3771. settingsManager.setSetting(sectionId, id, color.toHEXA().toString());
  3772. instance.hide();
  3773. instance.addSwatch(color.toHEXA().toString());
  3774. };
  3775. new obsidian.Setting(containerEl)
  3776. .setName(getTitle(config))
  3777. .then((setting) => {
  3778. setting.settingEl.dataset.id = opts.config.id;
  3779. // Construct description
  3780. setting.descEl.createSpan({}, (span) => {
  3781. if (getDescription(config)) {
  3782. span.appendChild(document.createTextNode(getDescription(config)));
  3783. }
  3784. });
  3785. setting.descEl.createDiv({}, (div) => {
  3786. div.createEl("small", {}, (sm) => {
  3787. sm.appendChild(createEl("strong", { text: "Default (light): " }));
  3788. sm.appendChild(document.createTextNode(config["default-light"]));
  3789. });
  3790. div.createEl("br");
  3791. div.createEl("small", {}, (sm) => {
  3792. sm.appendChild(createEl("strong", { text: "Default (dark): " }));
  3793. sm.appendChild(document.createTextNode(config["default-dark"]));
  3794. });
  3795. });
  3796. })
  3797. .then((setting) => {
  3798. setting.controlEl.createDiv({ cls: "themed-color-wrapper" }, (wrapper) => {
  3799. // Create light color picker
  3800. wrapper.createDiv({ cls: "theme-light" }, (themeWrapper) => {
  3801. pickrLight = Pickr.create(getPickrSettings({
  3802. isView,
  3803. el: themeWrapper.createDiv({ cls: "picker" }),
  3804. containerEl,
  3805. swatches: swatchesLight,
  3806. opacity: config.opacity,
  3807. defaultColor: valueLight !== undefined
  3808. ? valueLight
  3809. : config["default-light"],
  3810. }))
  3811. .on("show", () => {
  3812. const { result } = pickrLight.getRoot().interaction;
  3813. requestAnimationFrame(() => requestAnimationFrame(() => result.select()));
  3814. })
  3815. .on("save", onSave(idLight))
  3816. .on("cancel", onPickrCancel);
  3817. new obsidian.ButtonComponent(themeWrapper.createDiv({ cls: "pickr-reset" }))
  3818. .setIcon("reset")
  3819. .onClick(() => {
  3820. pickrLight.setColor(config["default-light"]);
  3821. settingsManager.clearSetting(sectionId, idLight);
  3822. })
  3823. .setTooltip(resetTooltip);
  3824. });
  3825. // Create dark color picker
  3826. wrapper.createDiv({ cls: "theme-dark" }, (themeWrapper) => {
  3827. pickrDark = Pickr.create(getPickrSettings({
  3828. isView,
  3829. el: themeWrapper.createDiv({ cls: "picker" }),
  3830. containerEl,
  3831. swatches: swatchesDark,
  3832. opacity: config.opacity,
  3833. defaultColor: valueDark !== undefined
  3834. ? valueDark
  3835. : config["default-dark"],
  3836. }))
  3837. .on("show", () => {
  3838. const { result } = pickrDark.getRoot().interaction;
  3839. requestAnimationFrame(() => requestAnimationFrame(() => result.select()));
  3840. })
  3841. .on("save", onSave(idDark))
  3842. .on("cancel", onPickrCancel);
  3843. new obsidian.ButtonComponent(themeWrapper.createDiv({ cls: "pickr-reset" }))
  3844. .setIcon("reset")
  3845. .onClick(() => {
  3846. pickrDark.setColor(config["default-dark"]);
  3847. settingsManager.clearSetting(sectionId, idDark);
  3848. })
  3849. .setTooltip(resetTooltip);
  3850. });
  3851. });
  3852. });
  3853. return () => {
  3854. pickrLight.destroyAndRemove();
  3855. pickrDark.destroyAndRemove();
  3856. };
  3857. }
  3858. function createSettings(opts) {
  3859. const { isView, containerEl, sectionId, settings, settingsManager, sectionName, } = opts;
  3860. const containerStack = [containerEl];
  3861. const idStack = [sectionId];
  3862. const cleanup = [];
  3863. const settingGroups = {
  3864. [sectionId]: [],
  3865. };
  3866. let containerLevel = 0;
  3867. function getTargetContainer(stack) {
  3868. if (!stack.length)
  3869. return containerEl;
  3870. return stack[stack.length - 1];
  3871. }
  3872. function pushId(id) {
  3873. idStack.forEach((containerId) => {
  3874. if (settingGroups[containerId]) {
  3875. settingGroups[containerId].push(id);
  3876. }
  3877. else {
  3878. settingGroups[containerId] = [id];
  3879. }
  3880. });
  3881. }
  3882. settings.forEach((setting) => {
  3883. switch (setting.type) {
  3884. case "heading": {
  3885. const config = setting;
  3886. settingGroups[config.id] = [];
  3887. let targetContainer = getTargetContainer(containerStack);
  3888. if (config.level > containerLevel) {
  3889. // Nest one level
  3890. createHeading({
  3891. config,
  3892. containerEl: targetContainer,
  3893. children: settingGroups[config.id],
  3894. settingsManager,
  3895. sectionName,
  3896. sectionId,
  3897. });
  3898. }
  3899. else if (config.level === containerLevel) {
  3900. // Same level
  3901. containerStack.pop();
  3902. idStack.pop();
  3903. targetContainer = getTargetContainer(containerStack);
  3904. createHeading({
  3905. config,
  3906. containerEl: targetContainer,
  3907. children: settingGroups[config.id],
  3908. settingsManager,
  3909. sectionName,
  3910. sectionId,
  3911. });
  3912. }
  3913. else {
  3914. // Step up to the appropriate level
  3915. while (containerStack.length > 1 &&
  3916. parseInt(containerStack[containerStack.length - 1].dataset.level) >=
  3917. config.level) {
  3918. containerStack.pop();
  3919. idStack.pop();
  3920. }
  3921. targetContainer = getTargetContainer(containerStack);
  3922. createHeading({
  3923. config,
  3924. containerEl: targetContainer,
  3925. children: settingGroups[config.id],
  3926. settingsManager,
  3927. sectionName,
  3928. sectionId,
  3929. });
  3930. }
  3931. targetContainer.createDiv({ cls: "style-settings-container" }, (container) => {
  3932. container.dataset.level = config.level.toString();
  3933. containerStack.push(container);
  3934. idStack.push(config.id);
  3935. });
  3936. containerLevel = config.level;
  3937. break;
  3938. }
  3939. case "class-toggle": {
  3940. pushId(setting.id);
  3941. createClassToggle({
  3942. sectionId,
  3943. config: setting,
  3944. containerEl: getTargetContainer(containerStack),
  3945. settingsManager,
  3946. });
  3947. break;
  3948. }
  3949. case "class-select": {
  3950. pushId(setting.id);
  3951. createClassMultiToggle({
  3952. sectionId,
  3953. config: setting,
  3954. containerEl: getTargetContainer(containerStack),
  3955. settingsManager,
  3956. });
  3957. break;
  3958. }
  3959. case "variable-text": {
  3960. pushId(setting.id);
  3961. createVariableText({
  3962. sectionId,
  3963. config: setting,
  3964. containerEl: getTargetContainer(containerStack),
  3965. settingsManager,
  3966. });
  3967. break;
  3968. }
  3969. case "variable-number": {
  3970. pushId(setting.id);
  3971. createVariableNumber({
  3972. sectionId,
  3973. config: setting,
  3974. containerEl: getTargetContainer(containerStack),
  3975. settingsManager,
  3976. });
  3977. break;
  3978. }
  3979. case "variable-number-slider": {
  3980. pushId(setting.id);
  3981. createVariableNumberSlider({
  3982. sectionId,
  3983. config: setting,
  3984. containerEl: getTargetContainer(containerStack),
  3985. settingsManager,
  3986. });
  3987. break;
  3988. }
  3989. case "variable-select": {
  3990. pushId(setting.id);
  3991. createVariableSelect({
  3992. sectionId,
  3993. config: setting,
  3994. containerEl: getTargetContainer(containerStack),
  3995. settingsManager,
  3996. });
  3997. break;
  3998. }
  3999. case "variable-color": {
  4000. pushId(setting.id);
  4001. cleanup.push(createVariableColor({
  4002. sectionId,
  4003. config: setting,
  4004. containerEl: getTargetContainer(containerStack),
  4005. settingsManager,
  4006. isView,
  4007. }));
  4008. break;
  4009. }
  4010. case "variable-themed-color": {
  4011. // TODO: multiple ids?
  4012. pushId(setting.id);
  4013. cleanup.push(createVariableThemedColor({
  4014. sectionId,
  4015. config: setting,
  4016. containerEl: getTargetContainer(containerStack),
  4017. settingsManager,
  4018. isView,
  4019. }));
  4020. break;
  4021. }
  4022. }
  4023. });
  4024. return cleanup;
  4025. }
  4026. /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
  4027. function isNothing(subject) {
  4028. return (typeof subject === 'undefined') || (subject === null);
  4029. }
  4030. function isObject(subject) {
  4031. return (typeof subject === 'object') && (subject !== null);
  4032. }
  4033. function toArray(sequence) {
  4034. if (Array.isArray(sequence)) return sequence;
  4035. else if (isNothing(sequence)) return [];
  4036. return [ sequence ];
  4037. }
  4038. function extend(target, source) {
  4039. var index, length, key, sourceKeys;
  4040. if (source) {
  4041. sourceKeys = Object.keys(source);
  4042. for (index = 0, length = sourceKeys.length; index < length; index += 1) {
  4043. key = sourceKeys[index];
  4044. target[key] = source[key];
  4045. }
  4046. }
  4047. return target;
  4048. }
  4049. function repeat(string, count) {
  4050. var result = '', cycle;
  4051. for (cycle = 0; cycle < count; cycle += 1) {
  4052. result += string;
  4053. }
  4054. return result;
  4055. }
  4056. function isNegativeZero(number) {
  4057. return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
  4058. }
  4059. var isNothing_1 = isNothing;
  4060. var isObject_1 = isObject;
  4061. var toArray_1 = toArray;
  4062. var repeat_1 = repeat;
  4063. var isNegativeZero_1 = isNegativeZero;
  4064. var extend_1 = extend;
  4065. var common = {
  4066. isNothing: isNothing_1,
  4067. isObject: isObject_1,
  4068. toArray: toArray_1,
  4069. repeat: repeat_1,
  4070. isNegativeZero: isNegativeZero_1,
  4071. extend: extend_1
  4072. };
  4073. // YAML error class. http://stackoverflow.com/questions/8458984
  4074. function formatError(exception, compact) {
  4075. var where = '', message = exception.reason || '(unknown reason)';
  4076. if (!exception.mark) return message;
  4077. if (exception.mark.name) {
  4078. where += 'in "' + exception.mark.name + '" ';
  4079. }
  4080. where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';
  4081. if (!compact && exception.mark.snippet) {
  4082. where += '\n\n' + exception.mark.snippet;
  4083. }
  4084. return message + ' ' + where;
  4085. }
  4086. function YAMLException$1(reason, mark) {
  4087. // Super constructor
  4088. Error.call(this);
  4089. this.name = 'YAMLException';
  4090. this.reason = reason;
  4091. this.mark = mark;
  4092. this.message = formatError(this, false);
  4093. // Include stack trace in error object
  4094. if (Error.captureStackTrace) {
  4095. // Chrome and NodeJS
  4096. Error.captureStackTrace(this, this.constructor);
  4097. } else {
  4098. // FF, IE 10+ and Safari 6+. Fallback for others
  4099. this.stack = (new Error()).stack || '';
  4100. }
  4101. }
  4102. // Inherit from Error
  4103. YAMLException$1.prototype = Object.create(Error.prototype);
  4104. YAMLException$1.prototype.constructor = YAMLException$1;
  4105. YAMLException$1.prototype.toString = function toString(compact) {
  4106. return this.name + ': ' + formatError(this, compact);
  4107. };
  4108. var exception = YAMLException$1;
  4109. // get snippet for a single line, respecting maxLength
  4110. function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
  4111. var head = '';
  4112. var tail = '';
  4113. var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
  4114. if (position - lineStart > maxHalfLength) {
  4115. head = ' ... ';
  4116. lineStart = position - maxHalfLength + head.length;
  4117. }
  4118. if (lineEnd - position > maxHalfLength) {
  4119. tail = ' ...';
  4120. lineEnd = position + maxHalfLength - tail.length;
  4121. }
  4122. return {
  4123. str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
  4124. pos: position - lineStart + head.length // relative position
  4125. };
  4126. }
  4127. function padStart(string, max) {
  4128. return common.repeat(' ', max - string.length) + string;
  4129. }
  4130. function makeSnippet(mark, options) {
  4131. options = Object.create(options || null);
  4132. if (!mark.buffer) return null;
  4133. if (!options.maxLength) options.maxLength = 79;
  4134. if (typeof options.indent !== 'number') options.indent = 1;
  4135. if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
  4136. if (typeof options.linesAfter !== 'number') options.linesAfter = 2;
  4137. var re = /\r?\n|\r|\0/g;
  4138. var lineStarts = [ 0 ];
  4139. var lineEnds = [];
  4140. var match;
  4141. var foundLineNo = -1;
  4142. while ((match = re.exec(mark.buffer))) {
  4143. lineEnds.push(match.index);
  4144. lineStarts.push(match.index + match[0].length);
  4145. if (mark.position <= match.index && foundLineNo < 0) {
  4146. foundLineNo = lineStarts.length - 2;
  4147. }
  4148. }
  4149. if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
  4150. var result = '', i, line;
  4151. var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
  4152. var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
  4153. for (i = 1; i <= options.linesBefore; i++) {
  4154. if (foundLineNo - i < 0) break;
  4155. line = getLine(
  4156. mark.buffer,
  4157. lineStarts[foundLineNo - i],
  4158. lineEnds[foundLineNo - i],
  4159. mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
  4160. maxLineLength
  4161. );
  4162. result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
  4163. ' | ' + line.str + '\n' + result;
  4164. }
  4165. line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
  4166. result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
  4167. ' | ' + line.str + '\n';
  4168. result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';
  4169. for (i = 1; i <= options.linesAfter; i++) {
  4170. if (foundLineNo + i >= lineEnds.length) break;
  4171. line = getLine(
  4172. mark.buffer,
  4173. lineStarts[foundLineNo + i],
  4174. lineEnds[foundLineNo + i],
  4175. mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
  4176. maxLineLength
  4177. );
  4178. result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
  4179. ' | ' + line.str + '\n';
  4180. }
  4181. return result.replace(/\n$/, '');
  4182. }
  4183. var snippet = makeSnippet;
  4184. var TYPE_CONSTRUCTOR_OPTIONS = [
  4185. 'kind',
  4186. 'multi',
  4187. 'resolve',
  4188. 'construct',
  4189. 'instanceOf',
  4190. 'predicate',
  4191. 'represent',
  4192. 'representName',
  4193. 'defaultStyle',
  4194. 'styleAliases'
  4195. ];
  4196. var YAML_NODE_KINDS = [
  4197. 'scalar',
  4198. 'sequence',
  4199. 'mapping'
  4200. ];
  4201. function compileStyleAliases(map) {
  4202. var result = {};
  4203. if (map !== null) {
  4204. Object.keys(map).forEach(function (style) {
  4205. map[style].forEach(function (alias) {
  4206. result[String(alias)] = style;
  4207. });
  4208. });
  4209. }
  4210. return result;
  4211. }
  4212. function Type$1(tag, options) {
  4213. options = options || {};
  4214. Object.keys(options).forEach(function (name) {
  4215. if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
  4216. throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
  4217. }
  4218. });
  4219. // TODO: Add tag format check.
  4220. this.options = options; // keep original options in case user wants to extend this type later
  4221. this.tag = tag;
  4222. this.kind = options['kind'] || null;
  4223. this.resolve = options['resolve'] || function () { return true; };
  4224. this.construct = options['construct'] || function (data) { return data; };
  4225. this.instanceOf = options['instanceOf'] || null;
  4226. this.predicate = options['predicate'] || null;
  4227. this.represent = options['represent'] || null;
  4228. this.representName = options['representName'] || null;
  4229. this.defaultStyle = options['defaultStyle'] || null;
  4230. this.multi = options['multi'] || false;
  4231. this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
  4232. if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
  4233. throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
  4234. }
  4235. }
  4236. var type = Type$1;
  4237. /*eslint-disable max-len*/
  4238. function compileList(schema, name) {
  4239. var result = [];
  4240. schema[name].forEach(function (currentType) {
  4241. var newIndex = result.length;
  4242. result.forEach(function (previousType, previousIndex) {
  4243. if (previousType.tag === currentType.tag &&
  4244. previousType.kind === currentType.kind &&
  4245. previousType.multi === currentType.multi) {
  4246. newIndex = previousIndex;
  4247. }
  4248. });
  4249. result[newIndex] = currentType;
  4250. });
  4251. return result;
  4252. }
  4253. function compileMap(/* lists... */) {
  4254. var result = {
  4255. scalar: {},
  4256. sequence: {},
  4257. mapping: {},
  4258. fallback: {},
  4259. multi: {
  4260. scalar: [],
  4261. sequence: [],
  4262. mapping: [],
  4263. fallback: []
  4264. }
  4265. }, index, length;
  4266. function collectType(type) {
  4267. if (type.multi) {
  4268. result.multi[type.kind].push(type);
  4269. result.multi['fallback'].push(type);
  4270. } else {
  4271. result[type.kind][type.tag] = result['fallback'][type.tag] = type;
  4272. }
  4273. }
  4274. for (index = 0, length = arguments.length; index < length; index += 1) {
  4275. arguments[index].forEach(collectType);
  4276. }
  4277. return result;
  4278. }
  4279. function Schema$1(definition) {
  4280. return this.extend(definition);
  4281. }
  4282. Schema$1.prototype.extend = function extend(definition) {
  4283. var implicit = [];
  4284. var explicit = [];
  4285. if (definition instanceof type) {
  4286. // Schema.extend(type)
  4287. explicit.push(definition);
  4288. } else if (Array.isArray(definition)) {
  4289. // Schema.extend([ type1, type2, ... ])
  4290. explicit = explicit.concat(definition);
  4291. } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
  4292. // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
  4293. if (definition.implicit) implicit = implicit.concat(definition.implicit);
  4294. if (definition.explicit) explicit = explicit.concat(definition.explicit);
  4295. } else {
  4296. throw new exception('Schema.extend argument should be a Type, [ Type ], ' +
  4297. 'or a schema definition ({ implicit: [...], explicit: [...] })');
  4298. }
  4299. implicit.forEach(function (type$1) {
  4300. if (!(type$1 instanceof type)) {
  4301. throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  4302. }
  4303. if (type$1.loadKind && type$1.loadKind !== 'scalar') {
  4304. throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
  4305. }
  4306. if (type$1.multi) {
  4307. throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
  4308. }
  4309. });
  4310. explicit.forEach(function (type$1) {
  4311. if (!(type$1 instanceof type)) {
  4312. throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  4313. }
  4314. });
  4315. var result = Object.create(Schema$1.prototype);
  4316. result.implicit = (this.implicit || []).concat(implicit);
  4317. result.explicit = (this.explicit || []).concat(explicit);
  4318. result.compiledImplicit = compileList(result, 'implicit');
  4319. result.compiledExplicit = compileList(result, 'explicit');
  4320. result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
  4321. return result;
  4322. };
  4323. var schema = Schema$1;
  4324. var str = new type('tag:yaml.org,2002:str', {
  4325. kind: 'scalar',
  4326. construct: function (data) { return data !== null ? data : ''; }
  4327. });
  4328. var seq = new type('tag:yaml.org,2002:seq', {
  4329. kind: 'sequence',
  4330. construct: function (data) { return data !== null ? data : []; }
  4331. });
  4332. var map = new type('tag:yaml.org,2002:map', {
  4333. kind: 'mapping',
  4334. construct: function (data) { return data !== null ? data : {}; }
  4335. });
  4336. var failsafe = new schema({
  4337. explicit: [
  4338. str,
  4339. seq,
  4340. map
  4341. ]
  4342. });
  4343. function resolveYamlNull(data) {
  4344. if (data === null) return true;
  4345. var max = data.length;
  4346. return (max === 1 && data === '~') ||
  4347. (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
  4348. }
  4349. function constructYamlNull() {
  4350. return null;
  4351. }
  4352. function isNull(object) {
  4353. return object === null;
  4354. }
  4355. var _null = new type('tag:yaml.org,2002:null', {
  4356. kind: 'scalar',
  4357. resolve: resolveYamlNull,
  4358. construct: constructYamlNull,
  4359. predicate: isNull,
  4360. represent: {
  4361. canonical: function () { return '~'; },
  4362. lowercase: function () { return 'null'; },
  4363. uppercase: function () { return 'NULL'; },
  4364. camelcase: function () { return 'Null'; },
  4365. empty: function () { return ''; }
  4366. },
  4367. defaultStyle: 'lowercase'
  4368. });
  4369. function resolveYamlBoolean(data) {
  4370. if (data === null) return false;
  4371. var max = data.length;
  4372. return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
  4373. (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
  4374. }
  4375. function constructYamlBoolean(data) {
  4376. return data === 'true' ||
  4377. data === 'True' ||
  4378. data === 'TRUE';
  4379. }
  4380. function isBoolean(object) {
  4381. return Object.prototype.toString.call(object) === '[object Boolean]';
  4382. }
  4383. var bool = new type('tag:yaml.org,2002:bool', {
  4384. kind: 'scalar',
  4385. resolve: resolveYamlBoolean,
  4386. construct: constructYamlBoolean,
  4387. predicate: isBoolean,
  4388. represent: {
  4389. lowercase: function (object) { return object ? 'true' : 'false'; },
  4390. uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
  4391. camelcase: function (object) { return object ? 'True' : 'False'; }
  4392. },
  4393. defaultStyle: 'lowercase'
  4394. });
  4395. function isHexCode(c) {
  4396. return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
  4397. ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
  4398. ((0x61/* a */ <= c) && (c <= 0x66/* f */));
  4399. }
  4400. function isOctCode(c) {
  4401. return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
  4402. }
  4403. function isDecCode(c) {
  4404. return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
  4405. }
  4406. function resolveYamlInteger(data) {
  4407. if (data === null) return false;
  4408. var max = data.length,
  4409. index = 0,
  4410. hasDigits = false,
  4411. ch;
  4412. if (!max) return false;
  4413. ch = data[index];
  4414. // sign
  4415. if (ch === '-' || ch === '+') {
  4416. ch = data[++index];
  4417. }
  4418. if (ch === '0') {
  4419. // 0
  4420. if (index + 1 === max) return true;
  4421. ch = data[++index];
  4422. // base 2, base 8, base 16
  4423. if (ch === 'b') {
  4424. // base 2
  4425. index++;
  4426. for (; index < max; index++) {
  4427. ch = data[index];
  4428. if (ch === '_') continue;
  4429. if (ch !== '0' && ch !== '1') return false;
  4430. hasDigits = true;
  4431. }
  4432. return hasDigits && ch !== '_';
  4433. }
  4434. if (ch === 'x') {
  4435. // base 16
  4436. index++;
  4437. for (; index < max; index++) {
  4438. ch = data[index];
  4439. if (ch === '_') continue;
  4440. if (!isHexCode(data.charCodeAt(index))) return false;
  4441. hasDigits = true;
  4442. }
  4443. return hasDigits && ch !== '_';
  4444. }
  4445. if (ch === 'o') {
  4446. // base 8
  4447. index++;
  4448. for (; index < max; index++) {
  4449. ch = data[index];
  4450. if (ch === '_') continue;
  4451. if (!isOctCode(data.charCodeAt(index))) return false;
  4452. hasDigits = true;
  4453. }
  4454. return hasDigits && ch !== '_';
  4455. }
  4456. }
  4457. // base 10 (except 0)
  4458. // value should not start with `_`;
  4459. if (ch === '_') return false;
  4460. for (; index < max; index++) {
  4461. ch = data[index];
  4462. if (ch === '_') continue;
  4463. if (!isDecCode(data.charCodeAt(index))) {
  4464. return false;
  4465. }
  4466. hasDigits = true;
  4467. }
  4468. // Should have digits and should not end with `_`
  4469. if (!hasDigits || ch === '_') return false;
  4470. return true;
  4471. }
  4472. function constructYamlInteger(data) {
  4473. var value = data, sign = 1, ch;
  4474. if (value.indexOf('_') !== -1) {
  4475. value = value.replace(/_/g, '');
  4476. }
  4477. ch = value[0];
  4478. if (ch === '-' || ch === '+') {
  4479. if (ch === '-') sign = -1;
  4480. value = value.slice(1);
  4481. ch = value[0];
  4482. }
  4483. if (value === '0') return 0;
  4484. if (ch === '0') {
  4485. if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
  4486. if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
  4487. if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
  4488. }
  4489. return sign * parseInt(value, 10);
  4490. }
  4491. function isInteger(object) {
  4492. return (Object.prototype.toString.call(object)) === '[object Number]' &&
  4493. (object % 1 === 0 && !common.isNegativeZero(object));
  4494. }
  4495. var int = new type('tag:yaml.org,2002:int', {
  4496. kind: 'scalar',
  4497. resolve: resolveYamlInteger,
  4498. construct: constructYamlInteger,
  4499. predicate: isInteger,
  4500. represent: {
  4501. binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
  4502. octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },
  4503. decimal: function (obj) { return obj.toString(10); },
  4504. /* eslint-disable max-len */
  4505. hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
  4506. },
  4507. defaultStyle: 'decimal',
  4508. styleAliases: {
  4509. binary: [ 2, 'bin' ],
  4510. octal: [ 8, 'oct' ],
  4511. decimal: [ 10, 'dec' ],
  4512. hexadecimal: [ 16, 'hex' ]
  4513. }
  4514. });
  4515. var YAML_FLOAT_PATTERN = new RegExp(
  4516. // 2.5e4, 2.5 and integers
  4517. '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
  4518. // .2e4, .2
  4519. // special case, seems not from spec
  4520. '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
  4521. // .inf
  4522. '|[-+]?\\.(?:inf|Inf|INF)' +
  4523. // .nan
  4524. '|\\.(?:nan|NaN|NAN))$');
  4525. function resolveYamlFloat(data) {
  4526. if (data === null) return false;
  4527. if (!YAML_FLOAT_PATTERN.test(data) ||
  4528. // Quick hack to not allow integers end with `_`
  4529. // Probably should update regexp & check speed
  4530. data[data.length - 1] === '_') {
  4531. return false;
  4532. }
  4533. return true;
  4534. }
  4535. function constructYamlFloat(data) {
  4536. var value, sign;
  4537. value = data.replace(/_/g, '').toLowerCase();
  4538. sign = value[0] === '-' ? -1 : 1;
  4539. if ('+-'.indexOf(value[0]) >= 0) {
  4540. value = value.slice(1);
  4541. }
  4542. if (value === '.inf') {
  4543. return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
  4544. } else if (value === '.nan') {
  4545. return NaN;
  4546. }
  4547. return sign * parseFloat(value, 10);
  4548. }
  4549. var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
  4550. function representYamlFloat(object, style) {
  4551. var res;
  4552. if (isNaN(object)) {
  4553. switch (style) {
  4554. case 'lowercase': return '.nan';
  4555. case 'uppercase': return '.NAN';
  4556. case 'camelcase': return '.NaN';
  4557. }
  4558. } else if (Number.POSITIVE_INFINITY === object) {
  4559. switch (style) {
  4560. case 'lowercase': return '.inf';
  4561. case 'uppercase': return '.INF';
  4562. case 'camelcase': return '.Inf';
  4563. }
  4564. } else if (Number.NEGATIVE_INFINITY === object) {
  4565. switch (style) {
  4566. case 'lowercase': return '-.inf';
  4567. case 'uppercase': return '-.INF';
  4568. case 'camelcase': return '-.Inf';
  4569. }
  4570. } else if (common.isNegativeZero(object)) {
  4571. return '-0.0';
  4572. }
  4573. res = object.toString(10);
  4574. // JS stringifier can build scientific format without dots: 5e-100,
  4575. // while YAML requres dot: 5.e-100. Fix it with simple hack
  4576. return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
  4577. }
  4578. function isFloat(object) {
  4579. return (Object.prototype.toString.call(object) === '[object Number]') &&
  4580. (object % 1 !== 0 || common.isNegativeZero(object));
  4581. }
  4582. var float = new type('tag:yaml.org,2002:float', {
  4583. kind: 'scalar',
  4584. resolve: resolveYamlFloat,
  4585. construct: constructYamlFloat,
  4586. predicate: isFloat,
  4587. represent: representYamlFloat,
  4588. defaultStyle: 'lowercase'
  4589. });
  4590. var json = failsafe.extend({
  4591. implicit: [
  4592. _null,
  4593. bool,
  4594. int,
  4595. float
  4596. ]
  4597. });
  4598. var core = json;
  4599. var YAML_DATE_REGEXP = new RegExp(
  4600. '^([0-9][0-9][0-9][0-9])' + // [1] year
  4601. '-([0-9][0-9])' + // [2] month
  4602. '-([0-9][0-9])$'); // [3] day
  4603. var YAML_TIMESTAMP_REGEXP = new RegExp(
  4604. '^([0-9][0-9][0-9][0-9])' + // [1] year
  4605. '-([0-9][0-9]?)' + // [2] month
  4606. '-([0-9][0-9]?)' + // [3] day
  4607. '(?:[Tt]|[ \\t]+)' + // ...
  4608. '([0-9][0-9]?)' + // [4] hour
  4609. ':([0-9][0-9])' + // [5] minute
  4610. ':([0-9][0-9])' + // [6] second
  4611. '(?:\\.([0-9]*))?' + // [7] fraction
  4612. '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
  4613. '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
  4614. function resolveYamlTimestamp(data) {
  4615. if (data === null) return false;
  4616. if (YAML_DATE_REGEXP.exec(data) !== null) return true;
  4617. if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
  4618. return false;
  4619. }
  4620. function constructYamlTimestamp(data) {
  4621. var match, year, month, day, hour, minute, second, fraction = 0,
  4622. delta = null, tz_hour, tz_minute, date;
  4623. match = YAML_DATE_REGEXP.exec(data);
  4624. if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
  4625. if (match === null) throw new Error('Date resolve error');
  4626. // match: [1] year [2] month [3] day
  4627. year = +(match[1]);
  4628. month = +(match[2]) - 1; // JS month starts with 0
  4629. day = +(match[3]);
  4630. if (!match[4]) { // no hour
  4631. return new Date(Date.UTC(year, month, day));
  4632. }
  4633. // match: [4] hour [5] minute [6] second [7] fraction
  4634. hour = +(match[4]);
  4635. minute = +(match[5]);
  4636. second = +(match[6]);
  4637. if (match[7]) {
  4638. fraction = match[7].slice(0, 3);
  4639. while (fraction.length < 3) { // milli-seconds
  4640. fraction += '0';
  4641. }
  4642. fraction = +fraction;
  4643. }
  4644. // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
  4645. if (match[9]) {
  4646. tz_hour = +(match[10]);
  4647. tz_minute = +(match[11] || 0);
  4648. delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
  4649. if (match[9] === '-') delta = -delta;
  4650. }
  4651. date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
  4652. if (delta) date.setTime(date.getTime() - delta);
  4653. return date;
  4654. }
  4655. function representYamlTimestamp(object /*, style*/) {
  4656. return object.toISOString();
  4657. }
  4658. var timestamp = new type('tag:yaml.org,2002:timestamp', {
  4659. kind: 'scalar',
  4660. resolve: resolveYamlTimestamp,
  4661. construct: constructYamlTimestamp,
  4662. instanceOf: Date,
  4663. represent: representYamlTimestamp
  4664. });
  4665. function resolveYamlMerge(data) {
  4666. return data === '<<' || data === null;
  4667. }
  4668. var merge = new type('tag:yaml.org,2002:merge', {
  4669. kind: 'scalar',
  4670. resolve: resolveYamlMerge
  4671. });
  4672. /*eslint-disable no-bitwise*/
  4673. // [ 64, 65, 66 ] -> [ padding, CR, LF ]
  4674. var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
  4675. function resolveYamlBinary(data) {
  4676. if (data === null) return false;
  4677. var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
  4678. // Convert one by one.
  4679. for (idx = 0; idx < max; idx++) {
  4680. code = map.indexOf(data.charAt(idx));
  4681. // Skip CR/LF
  4682. if (code > 64) continue;
  4683. // Fail on illegal characters
  4684. if (code < 0) return false;
  4685. bitlen += 6;
  4686. }
  4687. // If there are any bits left, source was corrupted
  4688. return (bitlen % 8) === 0;
  4689. }
  4690. function constructYamlBinary(data) {
  4691. var idx, tailbits,
  4692. input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
  4693. max = input.length,
  4694. map = BASE64_MAP,
  4695. bits = 0,
  4696. result = [];
  4697. // Collect by 6*4 bits (3 bytes)
  4698. for (idx = 0; idx < max; idx++) {
  4699. if ((idx % 4 === 0) && idx) {
  4700. result.push((bits >> 16) & 0xFF);
  4701. result.push((bits >> 8) & 0xFF);
  4702. result.push(bits & 0xFF);
  4703. }
  4704. bits = (bits << 6) | map.indexOf(input.charAt(idx));
  4705. }
  4706. // Dump tail
  4707. tailbits = (max % 4) * 6;
  4708. if (tailbits === 0) {
  4709. result.push((bits >> 16) & 0xFF);
  4710. result.push((bits >> 8) & 0xFF);
  4711. result.push(bits & 0xFF);
  4712. } else if (tailbits === 18) {
  4713. result.push((bits >> 10) & 0xFF);
  4714. result.push((bits >> 2) & 0xFF);
  4715. } else if (tailbits === 12) {
  4716. result.push((bits >> 4) & 0xFF);
  4717. }
  4718. return new Uint8Array(result);
  4719. }
  4720. function representYamlBinary(object /*, style*/) {
  4721. var result = '', bits = 0, idx, tail,
  4722. max = object.length,
  4723. map = BASE64_MAP;
  4724. // Convert every three bytes to 4 ASCII characters.
  4725. for (idx = 0; idx < max; idx++) {
  4726. if ((idx % 3 === 0) && idx) {
  4727. result += map[(bits >> 18) & 0x3F];
  4728. result += map[(bits >> 12) & 0x3F];
  4729. result += map[(bits >> 6) & 0x3F];
  4730. result += map[bits & 0x3F];
  4731. }
  4732. bits = (bits << 8) + object[idx];
  4733. }
  4734. // Dump tail
  4735. tail = max % 3;
  4736. if (tail === 0) {
  4737. result += map[(bits >> 18) & 0x3F];
  4738. result += map[(bits >> 12) & 0x3F];
  4739. result += map[(bits >> 6) & 0x3F];
  4740. result += map[bits & 0x3F];
  4741. } else if (tail === 2) {
  4742. result += map[(bits >> 10) & 0x3F];
  4743. result += map[(bits >> 4) & 0x3F];
  4744. result += map[(bits << 2) & 0x3F];
  4745. result += map[64];
  4746. } else if (tail === 1) {
  4747. result += map[(bits >> 2) & 0x3F];
  4748. result += map[(bits << 4) & 0x3F];
  4749. result += map[64];
  4750. result += map[64];
  4751. }
  4752. return result;
  4753. }
  4754. function isBinary(obj) {
  4755. return Object.prototype.toString.call(obj) === '[object Uint8Array]';
  4756. }
  4757. var binary = new type('tag:yaml.org,2002:binary', {
  4758. kind: 'scalar',
  4759. resolve: resolveYamlBinary,
  4760. construct: constructYamlBinary,
  4761. predicate: isBinary,
  4762. represent: representYamlBinary
  4763. });
  4764. var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  4765. var _toString$2 = Object.prototype.toString;
  4766. function resolveYamlOmap(data) {
  4767. if (data === null) return true;
  4768. var objectKeys = [], index, length, pair, pairKey, pairHasKey,
  4769. object = data;
  4770. for (index = 0, length = object.length; index < length; index += 1) {
  4771. pair = object[index];
  4772. pairHasKey = false;
  4773. if (_toString$2.call(pair) !== '[object Object]') return false;
  4774. for (pairKey in pair) {
  4775. if (_hasOwnProperty$3.call(pair, pairKey)) {
  4776. if (!pairHasKey) pairHasKey = true;
  4777. else return false;
  4778. }
  4779. }
  4780. if (!pairHasKey) return false;
  4781. if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
  4782. else return false;
  4783. }
  4784. return true;
  4785. }
  4786. function constructYamlOmap(data) {
  4787. return data !== null ? data : [];
  4788. }
  4789. var omap = new type('tag:yaml.org,2002:omap', {
  4790. kind: 'sequence',
  4791. resolve: resolveYamlOmap,
  4792. construct: constructYamlOmap
  4793. });
  4794. var _toString$1 = Object.prototype.toString;
  4795. function resolveYamlPairs(data) {
  4796. if (data === null) return true;
  4797. var index, length, pair, keys, result,
  4798. object = data;
  4799. result = new Array(object.length);
  4800. for (index = 0, length = object.length; index < length; index += 1) {
  4801. pair = object[index];
  4802. if (_toString$1.call(pair) !== '[object Object]') return false;
  4803. keys = Object.keys(pair);
  4804. if (keys.length !== 1) return false;
  4805. result[index] = [ keys[0], pair[keys[0]] ];
  4806. }
  4807. return true;
  4808. }
  4809. function constructYamlPairs(data) {
  4810. if (data === null) return [];
  4811. var index, length, pair, keys, result,
  4812. object = data;
  4813. result = new Array(object.length);
  4814. for (index = 0, length = object.length; index < length; index += 1) {
  4815. pair = object[index];
  4816. keys = Object.keys(pair);
  4817. result[index] = [ keys[0], pair[keys[0]] ];
  4818. }
  4819. return result;
  4820. }
  4821. var pairs = new type('tag:yaml.org,2002:pairs', {
  4822. kind: 'sequence',
  4823. resolve: resolveYamlPairs,
  4824. construct: constructYamlPairs
  4825. });
  4826. var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  4827. function resolveYamlSet(data) {
  4828. if (data === null) return true;
  4829. var key, object = data;
  4830. for (key in object) {
  4831. if (_hasOwnProperty$2.call(object, key)) {
  4832. if (object[key] !== null) return false;
  4833. }
  4834. }
  4835. return true;
  4836. }
  4837. function constructYamlSet(data) {
  4838. return data !== null ? data : {};
  4839. }
  4840. var set = new type('tag:yaml.org,2002:set', {
  4841. kind: 'mapping',
  4842. resolve: resolveYamlSet,
  4843. construct: constructYamlSet
  4844. });
  4845. var _default = core.extend({
  4846. implicit: [
  4847. timestamp,
  4848. merge
  4849. ],
  4850. explicit: [
  4851. binary,
  4852. omap,
  4853. pairs,
  4854. set
  4855. ]
  4856. });
  4857. /*eslint-disable max-len,no-use-before-define*/
  4858. var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  4859. var CONTEXT_FLOW_IN = 1;
  4860. var CONTEXT_FLOW_OUT = 2;
  4861. var CONTEXT_BLOCK_IN = 3;
  4862. var CONTEXT_BLOCK_OUT = 4;
  4863. var CHOMPING_CLIP = 1;
  4864. var CHOMPING_STRIP = 2;
  4865. var CHOMPING_KEEP = 3;
  4866. var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  4867. var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
  4868. var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
  4869. var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
  4870. var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
  4871. function _class(obj) { return Object.prototype.toString.call(obj); }
  4872. function is_EOL(c) {
  4873. return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
  4874. }
  4875. function is_WHITE_SPACE(c) {
  4876. return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
  4877. }
  4878. function is_WS_OR_EOL(c) {
  4879. return (c === 0x09/* Tab */) ||
  4880. (c === 0x20/* Space */) ||
  4881. (c === 0x0A/* LF */) ||
  4882. (c === 0x0D/* CR */);
  4883. }
  4884. function is_FLOW_INDICATOR(c) {
  4885. return c === 0x2C/* , */ ||
  4886. c === 0x5B/* [ */ ||
  4887. c === 0x5D/* ] */ ||
  4888. c === 0x7B/* { */ ||
  4889. c === 0x7D/* } */;
  4890. }
  4891. function fromHexCode(c) {
  4892. var lc;
  4893. if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
  4894. return c - 0x30;
  4895. }
  4896. /*eslint-disable no-bitwise*/
  4897. lc = c | 0x20;
  4898. if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
  4899. return lc - 0x61 + 10;
  4900. }
  4901. return -1;
  4902. }
  4903. function escapedHexLen(c) {
  4904. if (c === 0x78/* x */) { return 2; }
  4905. if (c === 0x75/* u */) { return 4; }
  4906. if (c === 0x55/* U */) { return 8; }
  4907. return 0;
  4908. }
  4909. function fromDecimalCode(c) {
  4910. if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
  4911. return c - 0x30;
  4912. }
  4913. return -1;
  4914. }
  4915. function simpleEscapeSequence(c) {
  4916. /* eslint-disable indent */
  4917. return (c === 0x30/* 0 */) ? '\x00' :
  4918. (c === 0x61/* a */) ? '\x07' :
  4919. (c === 0x62/* b */) ? '\x08' :
  4920. (c === 0x74/* t */) ? '\x09' :
  4921. (c === 0x09/* Tab */) ? '\x09' :
  4922. (c === 0x6E/* n */) ? '\x0A' :
  4923. (c === 0x76/* v */) ? '\x0B' :
  4924. (c === 0x66/* f */) ? '\x0C' :
  4925. (c === 0x72/* r */) ? '\x0D' :
  4926. (c === 0x65/* e */) ? '\x1B' :
  4927. (c === 0x20/* Space */) ? ' ' :
  4928. (c === 0x22/* " */) ? '\x22' :
  4929. (c === 0x2F/* / */) ? '/' :
  4930. (c === 0x5C/* \ */) ? '\x5C' :
  4931. (c === 0x4E/* N */) ? '\x85' :
  4932. (c === 0x5F/* _ */) ? '\xA0' :
  4933. (c === 0x4C/* L */) ? '\u2028' :
  4934. (c === 0x50/* P */) ? '\u2029' : '';
  4935. }
  4936. function charFromCodepoint(c) {
  4937. if (c <= 0xFFFF) {
  4938. return String.fromCharCode(c);
  4939. }
  4940. // Encode UTF-16 surrogate pair
  4941. // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
  4942. return String.fromCharCode(
  4943. ((c - 0x010000) >> 10) + 0xD800,
  4944. ((c - 0x010000) & 0x03FF) + 0xDC00
  4945. );
  4946. }
  4947. var simpleEscapeCheck = new Array(256); // integer, for fast access
  4948. var simpleEscapeMap = new Array(256);
  4949. for (var i = 0; i < 256; i++) {
  4950. simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
  4951. simpleEscapeMap[i] = simpleEscapeSequence(i);
  4952. }
  4953. function State$1(input, options) {
  4954. this.input = input;
  4955. this.filename = options['filename'] || null;
  4956. this.schema = options['schema'] || _default;
  4957. this.onWarning = options['onWarning'] || null;
  4958. // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
  4959. // if such documents have no explicit %YAML directive
  4960. this.legacy = options['legacy'] || false;
  4961. this.json = options['json'] || false;
  4962. this.listener = options['listener'] || null;
  4963. this.implicitTypes = this.schema.compiledImplicit;
  4964. this.typeMap = this.schema.compiledTypeMap;
  4965. this.length = input.length;
  4966. this.position = 0;
  4967. this.line = 0;
  4968. this.lineStart = 0;
  4969. this.lineIndent = 0;
  4970. // position of first leading tab in the current line,
  4971. // used to make sure there are no tabs in the indentation
  4972. this.firstTabInLine = -1;
  4973. this.documents = [];
  4974. /*
  4975. this.version;
  4976. this.checkLineBreaks;
  4977. this.tagMap;
  4978. this.anchorMap;
  4979. this.tag;
  4980. this.anchor;
  4981. this.kind;
  4982. this.result;*/
  4983. }
  4984. function generateError(state, message) {
  4985. var mark = {
  4986. name: state.filename,
  4987. buffer: state.input.slice(0, -1), // omit trailing \0
  4988. position: state.position,
  4989. line: state.line,
  4990. column: state.position - state.lineStart
  4991. };
  4992. mark.snippet = snippet(mark);
  4993. return new exception(message, mark);
  4994. }
  4995. function throwError(state, message) {
  4996. throw generateError(state, message);
  4997. }
  4998. function throwWarning(state, message) {
  4999. if (state.onWarning) {
  5000. state.onWarning.call(null, generateError(state, message));
  5001. }
  5002. }
  5003. var directiveHandlers = {
  5004. YAML: function handleYamlDirective(state, name, args) {
  5005. var match, major, minor;
  5006. if (state.version !== null) {
  5007. throwError(state, 'duplication of %YAML directive');
  5008. }
  5009. if (args.length !== 1) {
  5010. throwError(state, 'YAML directive accepts exactly one argument');
  5011. }
  5012. match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
  5013. if (match === null) {
  5014. throwError(state, 'ill-formed argument of the YAML directive');
  5015. }
  5016. major = parseInt(match[1], 10);
  5017. minor = parseInt(match[2], 10);
  5018. if (major !== 1) {
  5019. throwError(state, 'unacceptable YAML version of the document');
  5020. }
  5021. state.version = args[0];
  5022. state.checkLineBreaks = (minor < 2);
  5023. if (minor !== 1 && minor !== 2) {
  5024. throwWarning(state, 'unsupported YAML version of the document');
  5025. }
  5026. },
  5027. TAG: function handleTagDirective(state, name, args) {
  5028. var handle, prefix;
  5029. if (args.length !== 2) {
  5030. throwError(state, 'TAG directive accepts exactly two arguments');
  5031. }
  5032. handle = args[0];
  5033. prefix = args[1];
  5034. if (!PATTERN_TAG_HANDLE.test(handle)) {
  5035. throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
  5036. }
  5037. if (_hasOwnProperty$1.call(state.tagMap, handle)) {
  5038. throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
  5039. }
  5040. if (!PATTERN_TAG_URI.test(prefix)) {
  5041. throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
  5042. }
  5043. try {
  5044. prefix = decodeURIComponent(prefix);
  5045. } catch (err) {
  5046. throwError(state, 'tag prefix is malformed: ' + prefix);
  5047. }
  5048. state.tagMap[handle] = prefix;
  5049. }
  5050. };
  5051. function captureSegment(state, start, end, checkJson) {
  5052. var _position, _length, _character, _result;
  5053. if (start < end) {
  5054. _result = state.input.slice(start, end);
  5055. if (checkJson) {
  5056. for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
  5057. _character = _result.charCodeAt(_position);
  5058. if (!(_character === 0x09 ||
  5059. (0x20 <= _character && _character <= 0x10FFFF))) {
  5060. throwError(state, 'expected valid JSON character');
  5061. }
  5062. }
  5063. } else if (PATTERN_NON_PRINTABLE.test(_result)) {
  5064. throwError(state, 'the stream contains non-printable characters');
  5065. }
  5066. state.result += _result;
  5067. }
  5068. }
  5069. function mergeMappings(state, destination, source, overridableKeys) {
  5070. var sourceKeys, key, index, quantity;
  5071. if (!common.isObject(source)) {
  5072. throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
  5073. }
  5074. sourceKeys = Object.keys(source);
  5075. for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
  5076. key = sourceKeys[index];
  5077. if (!_hasOwnProperty$1.call(destination, key)) {
  5078. destination[key] = source[key];
  5079. overridableKeys[key] = true;
  5080. }
  5081. }
  5082. }
  5083. function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
  5084. startLine, startLineStart, startPos) {
  5085. var index, quantity;
  5086. // The output is a plain object here, so keys can only be strings.
  5087. // We need to convert keyNode to a string, but doing so can hang the process
  5088. // (deeply nested arrays that explode exponentially using aliases).
  5089. if (Array.isArray(keyNode)) {
  5090. keyNode = Array.prototype.slice.call(keyNode);
  5091. for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
  5092. if (Array.isArray(keyNode[index])) {
  5093. throwError(state, 'nested arrays are not supported inside keys');
  5094. }
  5095. if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
  5096. keyNode[index] = '[object Object]';
  5097. }
  5098. }
  5099. }
  5100. // Avoid code execution in load() via toString property
  5101. // (still use its own toString for arrays, timestamps,
  5102. // and whatever user schema extensions happen to have @@toStringTag)
  5103. if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
  5104. keyNode = '[object Object]';
  5105. }
  5106. keyNode = String(keyNode);
  5107. if (_result === null) {
  5108. _result = {};
  5109. }
  5110. if (keyTag === 'tag:yaml.org,2002:merge') {
  5111. if (Array.isArray(valueNode)) {
  5112. for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
  5113. mergeMappings(state, _result, valueNode[index], overridableKeys);
  5114. }
  5115. } else {
  5116. mergeMappings(state, _result, valueNode, overridableKeys);
  5117. }
  5118. } else {
  5119. if (!state.json &&
  5120. !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
  5121. _hasOwnProperty$1.call(_result, keyNode)) {
  5122. state.line = startLine || state.line;
  5123. state.lineStart = startLineStart || state.lineStart;
  5124. state.position = startPos || state.position;
  5125. throwError(state, 'duplicated mapping key');
  5126. }
  5127. // used for this specific key only because Object.defineProperty is slow
  5128. if (keyNode === '__proto__') {
  5129. Object.defineProperty(_result, keyNode, {
  5130. configurable: true,
  5131. enumerable: true,
  5132. writable: true,
  5133. value: valueNode
  5134. });
  5135. } else {
  5136. _result[keyNode] = valueNode;
  5137. }
  5138. delete overridableKeys[keyNode];
  5139. }
  5140. return _result;
  5141. }
  5142. function readLineBreak(state) {
  5143. var ch;
  5144. ch = state.input.charCodeAt(state.position);
  5145. if (ch === 0x0A/* LF */) {
  5146. state.position++;
  5147. } else if (ch === 0x0D/* CR */) {
  5148. state.position++;
  5149. if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
  5150. state.position++;
  5151. }
  5152. } else {
  5153. throwError(state, 'a line break is expected');
  5154. }
  5155. state.line += 1;
  5156. state.lineStart = state.position;
  5157. state.firstTabInLine = -1;
  5158. }
  5159. function skipSeparationSpace(state, allowComments, checkIndent) {
  5160. var lineBreaks = 0,
  5161. ch = state.input.charCodeAt(state.position);
  5162. while (ch !== 0) {
  5163. while (is_WHITE_SPACE(ch)) {
  5164. if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
  5165. state.firstTabInLine = state.position;
  5166. }
  5167. ch = state.input.charCodeAt(++state.position);
  5168. }
  5169. if (allowComments && ch === 0x23/* # */) {
  5170. do {
  5171. ch = state.input.charCodeAt(++state.position);
  5172. } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
  5173. }
  5174. if (is_EOL(ch)) {
  5175. readLineBreak(state);
  5176. ch = state.input.charCodeAt(state.position);
  5177. lineBreaks++;
  5178. state.lineIndent = 0;
  5179. while (ch === 0x20/* Space */) {
  5180. state.lineIndent++;
  5181. ch = state.input.charCodeAt(++state.position);
  5182. }
  5183. } else {
  5184. break;
  5185. }
  5186. }
  5187. if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
  5188. throwWarning(state, 'deficient indentation');
  5189. }
  5190. return lineBreaks;
  5191. }
  5192. function testDocumentSeparator(state) {
  5193. var _position = state.position,
  5194. ch;
  5195. ch = state.input.charCodeAt(_position);
  5196. // Condition state.position === state.lineStart is tested
  5197. // in parent on each call, for efficiency. No needs to test here again.
  5198. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
  5199. ch === state.input.charCodeAt(_position + 1) &&
  5200. ch === state.input.charCodeAt(_position + 2)) {
  5201. _position += 3;
  5202. ch = state.input.charCodeAt(_position);
  5203. if (ch === 0 || is_WS_OR_EOL(ch)) {
  5204. return true;
  5205. }
  5206. }
  5207. return false;
  5208. }
  5209. function writeFoldedLines(state, count) {
  5210. if (count === 1) {
  5211. state.result += ' ';
  5212. } else if (count > 1) {
  5213. state.result += common.repeat('\n', count - 1);
  5214. }
  5215. }
  5216. function readPlainScalar(state, nodeIndent, withinFlowCollection) {
  5217. var preceding,
  5218. following,
  5219. captureStart,
  5220. captureEnd,
  5221. hasPendingContent,
  5222. _line,
  5223. _lineStart,
  5224. _lineIndent,
  5225. _kind = state.kind,
  5226. _result = state.result,
  5227. ch;
  5228. ch = state.input.charCodeAt(state.position);
  5229. if (is_WS_OR_EOL(ch) ||
  5230. is_FLOW_INDICATOR(ch) ||
  5231. ch === 0x23/* # */ ||
  5232. ch === 0x26/* & */ ||
  5233. ch === 0x2A/* * */ ||
  5234. ch === 0x21/* ! */ ||
  5235. ch === 0x7C/* | */ ||
  5236. ch === 0x3E/* > */ ||
  5237. ch === 0x27/* ' */ ||
  5238. ch === 0x22/* " */ ||
  5239. ch === 0x25/* % */ ||
  5240. ch === 0x40/* @ */ ||
  5241. ch === 0x60/* ` */) {
  5242. return false;
  5243. }
  5244. if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
  5245. following = state.input.charCodeAt(state.position + 1);
  5246. if (is_WS_OR_EOL(following) ||
  5247. withinFlowCollection && is_FLOW_INDICATOR(following)) {
  5248. return false;
  5249. }
  5250. }
  5251. state.kind = 'scalar';
  5252. state.result = '';
  5253. captureStart = captureEnd = state.position;
  5254. hasPendingContent = false;
  5255. while (ch !== 0) {
  5256. if (ch === 0x3A/* : */) {
  5257. following = state.input.charCodeAt(state.position + 1);
  5258. if (is_WS_OR_EOL(following) ||
  5259. withinFlowCollection && is_FLOW_INDICATOR(following)) {
  5260. break;
  5261. }
  5262. } else if (ch === 0x23/* # */) {
  5263. preceding = state.input.charCodeAt(state.position - 1);
  5264. if (is_WS_OR_EOL(preceding)) {
  5265. break;
  5266. }
  5267. } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
  5268. withinFlowCollection && is_FLOW_INDICATOR(ch)) {
  5269. break;
  5270. } else if (is_EOL(ch)) {
  5271. _line = state.line;
  5272. _lineStart = state.lineStart;
  5273. _lineIndent = state.lineIndent;
  5274. skipSeparationSpace(state, false, -1);
  5275. if (state.lineIndent >= nodeIndent) {
  5276. hasPendingContent = true;
  5277. ch = state.input.charCodeAt(state.position);
  5278. continue;
  5279. } else {
  5280. state.position = captureEnd;
  5281. state.line = _line;
  5282. state.lineStart = _lineStart;
  5283. state.lineIndent = _lineIndent;
  5284. break;
  5285. }
  5286. }
  5287. if (hasPendingContent) {
  5288. captureSegment(state, captureStart, captureEnd, false);
  5289. writeFoldedLines(state, state.line - _line);
  5290. captureStart = captureEnd = state.position;
  5291. hasPendingContent = false;
  5292. }
  5293. if (!is_WHITE_SPACE(ch)) {
  5294. captureEnd = state.position + 1;
  5295. }
  5296. ch = state.input.charCodeAt(++state.position);
  5297. }
  5298. captureSegment(state, captureStart, captureEnd, false);
  5299. if (state.result) {
  5300. return true;
  5301. }
  5302. state.kind = _kind;
  5303. state.result = _result;
  5304. return false;
  5305. }
  5306. function readSingleQuotedScalar(state, nodeIndent) {
  5307. var ch,
  5308. captureStart, captureEnd;
  5309. ch = state.input.charCodeAt(state.position);
  5310. if (ch !== 0x27/* ' */) {
  5311. return false;
  5312. }
  5313. state.kind = 'scalar';
  5314. state.result = '';
  5315. state.position++;
  5316. captureStart = captureEnd = state.position;
  5317. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  5318. if (ch === 0x27/* ' */) {
  5319. captureSegment(state, captureStart, state.position, true);
  5320. ch = state.input.charCodeAt(++state.position);
  5321. if (ch === 0x27/* ' */) {
  5322. captureStart = state.position;
  5323. state.position++;
  5324. captureEnd = state.position;
  5325. } else {
  5326. return true;
  5327. }
  5328. } else if (is_EOL(ch)) {
  5329. captureSegment(state, captureStart, captureEnd, true);
  5330. writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
  5331. captureStart = captureEnd = state.position;
  5332. } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
  5333. throwError(state, 'unexpected end of the document within a single quoted scalar');
  5334. } else {
  5335. state.position++;
  5336. captureEnd = state.position;
  5337. }
  5338. }
  5339. throwError(state, 'unexpected end of the stream within a single quoted scalar');
  5340. }
  5341. function readDoubleQuotedScalar(state, nodeIndent) {
  5342. var captureStart,
  5343. captureEnd,
  5344. hexLength,
  5345. hexResult,
  5346. tmp,
  5347. ch;
  5348. ch = state.input.charCodeAt(state.position);
  5349. if (ch !== 0x22/* " */) {
  5350. return false;
  5351. }
  5352. state.kind = 'scalar';
  5353. state.result = '';
  5354. state.position++;
  5355. captureStart = captureEnd = state.position;
  5356. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  5357. if (ch === 0x22/* " */) {
  5358. captureSegment(state, captureStart, state.position, true);
  5359. state.position++;
  5360. return true;
  5361. } else if (ch === 0x5C/* \ */) {
  5362. captureSegment(state, captureStart, state.position, true);
  5363. ch = state.input.charCodeAt(++state.position);
  5364. if (is_EOL(ch)) {
  5365. skipSeparationSpace(state, false, nodeIndent);
  5366. // TODO: rework to inline fn with no type cast?
  5367. } else if (ch < 256 && simpleEscapeCheck[ch]) {
  5368. state.result += simpleEscapeMap[ch];
  5369. state.position++;
  5370. } else if ((tmp = escapedHexLen(ch)) > 0) {
  5371. hexLength = tmp;
  5372. hexResult = 0;
  5373. for (; hexLength > 0; hexLength--) {
  5374. ch = state.input.charCodeAt(++state.position);
  5375. if ((tmp = fromHexCode(ch)) >= 0) {
  5376. hexResult = (hexResult << 4) + tmp;
  5377. } else {
  5378. throwError(state, 'expected hexadecimal character');
  5379. }
  5380. }
  5381. state.result += charFromCodepoint(hexResult);
  5382. state.position++;
  5383. } else {
  5384. throwError(state, 'unknown escape sequence');
  5385. }
  5386. captureStart = captureEnd = state.position;
  5387. } else if (is_EOL(ch)) {
  5388. captureSegment(state, captureStart, captureEnd, true);
  5389. writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
  5390. captureStart = captureEnd = state.position;
  5391. } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
  5392. throwError(state, 'unexpected end of the document within a double quoted scalar');
  5393. } else {
  5394. state.position++;
  5395. captureEnd = state.position;
  5396. }
  5397. }
  5398. throwError(state, 'unexpected end of the stream within a double quoted scalar');
  5399. }
  5400. function readFlowCollection(state, nodeIndent) {
  5401. var readNext = true,
  5402. _line,
  5403. _lineStart,
  5404. _pos,
  5405. _tag = state.tag,
  5406. _result,
  5407. _anchor = state.anchor,
  5408. following,
  5409. terminator,
  5410. isPair,
  5411. isExplicitPair,
  5412. isMapping,
  5413. overridableKeys = Object.create(null),
  5414. keyNode,
  5415. keyTag,
  5416. valueNode,
  5417. ch;
  5418. ch = state.input.charCodeAt(state.position);
  5419. if (ch === 0x5B/* [ */) {
  5420. terminator = 0x5D;/* ] */
  5421. isMapping = false;
  5422. _result = [];
  5423. } else if (ch === 0x7B/* { */) {
  5424. terminator = 0x7D;/* } */
  5425. isMapping = true;
  5426. _result = {};
  5427. } else {
  5428. return false;
  5429. }
  5430. if (state.anchor !== null) {
  5431. state.anchorMap[state.anchor] = _result;
  5432. }
  5433. ch = state.input.charCodeAt(++state.position);
  5434. while (ch !== 0) {
  5435. skipSeparationSpace(state, true, nodeIndent);
  5436. ch = state.input.charCodeAt(state.position);
  5437. if (ch === terminator) {
  5438. state.position++;
  5439. state.tag = _tag;
  5440. state.anchor = _anchor;
  5441. state.kind = isMapping ? 'mapping' : 'sequence';
  5442. state.result = _result;
  5443. return true;
  5444. } else if (!readNext) {
  5445. throwError(state, 'missed comma between flow collection entries');
  5446. } else if (ch === 0x2C/* , */) {
  5447. // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
  5448. throwError(state, "expected the node content, but found ','");
  5449. }
  5450. keyTag = keyNode = valueNode = null;
  5451. isPair = isExplicitPair = false;
  5452. if (ch === 0x3F/* ? */) {
  5453. following = state.input.charCodeAt(state.position + 1);
  5454. if (is_WS_OR_EOL(following)) {
  5455. isPair = isExplicitPair = true;
  5456. state.position++;
  5457. skipSeparationSpace(state, true, nodeIndent);
  5458. }
  5459. }
  5460. _line = state.line; // Save the current line.
  5461. _lineStart = state.lineStart;
  5462. _pos = state.position;
  5463. composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
  5464. keyTag = state.tag;
  5465. keyNode = state.result;
  5466. skipSeparationSpace(state, true, nodeIndent);
  5467. ch = state.input.charCodeAt(state.position);
  5468. if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
  5469. isPair = true;
  5470. ch = state.input.charCodeAt(++state.position);
  5471. skipSeparationSpace(state, true, nodeIndent);
  5472. composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
  5473. valueNode = state.result;
  5474. }
  5475. if (isMapping) {
  5476. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
  5477. } else if (isPair) {
  5478. _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
  5479. } else {
  5480. _result.push(keyNode);
  5481. }
  5482. skipSeparationSpace(state, true, nodeIndent);
  5483. ch = state.input.charCodeAt(state.position);
  5484. if (ch === 0x2C/* , */) {
  5485. readNext = true;
  5486. ch = state.input.charCodeAt(++state.position);
  5487. } else {
  5488. readNext = false;
  5489. }
  5490. }
  5491. throwError(state, 'unexpected end of the stream within a flow collection');
  5492. }
  5493. function readBlockScalar(state, nodeIndent) {
  5494. var captureStart,
  5495. folding,
  5496. chomping = CHOMPING_CLIP,
  5497. didReadContent = false,
  5498. detectedIndent = false,
  5499. textIndent = nodeIndent,
  5500. emptyLines = 0,
  5501. atMoreIndented = false,
  5502. tmp,
  5503. ch;
  5504. ch = state.input.charCodeAt(state.position);
  5505. if (ch === 0x7C/* | */) {
  5506. folding = false;
  5507. } else if (ch === 0x3E/* > */) {
  5508. folding = true;
  5509. } else {
  5510. return false;
  5511. }
  5512. state.kind = 'scalar';
  5513. state.result = '';
  5514. while (ch !== 0) {
  5515. ch = state.input.charCodeAt(++state.position);
  5516. if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
  5517. if (CHOMPING_CLIP === chomping) {
  5518. chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
  5519. } else {
  5520. throwError(state, 'repeat of a chomping mode identifier');
  5521. }
  5522. } else if ((tmp = fromDecimalCode(ch)) >= 0) {
  5523. if (tmp === 0) {
  5524. throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
  5525. } else if (!detectedIndent) {
  5526. textIndent = nodeIndent + tmp - 1;
  5527. detectedIndent = true;
  5528. } else {
  5529. throwError(state, 'repeat of an indentation width identifier');
  5530. }
  5531. } else {
  5532. break;
  5533. }
  5534. }
  5535. if (is_WHITE_SPACE(ch)) {
  5536. do { ch = state.input.charCodeAt(++state.position); }
  5537. while (is_WHITE_SPACE(ch));
  5538. if (ch === 0x23/* # */) {
  5539. do { ch = state.input.charCodeAt(++state.position); }
  5540. while (!is_EOL(ch) && (ch !== 0));
  5541. }
  5542. }
  5543. while (ch !== 0) {
  5544. readLineBreak(state);
  5545. state.lineIndent = 0;
  5546. ch = state.input.charCodeAt(state.position);
  5547. while ((!detectedIndent || state.lineIndent < textIndent) &&
  5548. (ch === 0x20/* Space */)) {
  5549. state.lineIndent++;
  5550. ch = state.input.charCodeAt(++state.position);
  5551. }
  5552. if (!detectedIndent && state.lineIndent > textIndent) {
  5553. textIndent = state.lineIndent;
  5554. }
  5555. if (is_EOL(ch)) {
  5556. emptyLines++;
  5557. continue;
  5558. }
  5559. // End of the scalar.
  5560. if (state.lineIndent < textIndent) {
  5561. // Perform the chomping.
  5562. if (chomping === CHOMPING_KEEP) {
  5563. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  5564. } else if (chomping === CHOMPING_CLIP) {
  5565. if (didReadContent) { // i.e. only if the scalar is not empty.
  5566. state.result += '\n';
  5567. }
  5568. }
  5569. // Break this `while` cycle and go to the funciton's epilogue.
  5570. break;
  5571. }
  5572. // Folded style: use fancy rules to handle line breaks.
  5573. if (folding) {
  5574. // Lines starting with white space characters (more-indented lines) are not folded.
  5575. if (is_WHITE_SPACE(ch)) {
  5576. atMoreIndented = true;
  5577. // except for the first content line (cf. Example 8.1)
  5578. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  5579. // End of more-indented block.
  5580. } else if (atMoreIndented) {
  5581. atMoreIndented = false;
  5582. state.result += common.repeat('\n', emptyLines + 1);
  5583. // Just one line break - perceive as the same line.
  5584. } else if (emptyLines === 0) {
  5585. if (didReadContent) { // i.e. only if we have already read some scalar content.
  5586. state.result += ' ';
  5587. }
  5588. // Several line breaks - perceive as different lines.
  5589. } else {
  5590. state.result += common.repeat('\n', emptyLines);
  5591. }
  5592. // Literal style: just add exact number of line breaks between content lines.
  5593. } else {
  5594. // Keep all line breaks except the header line break.
  5595. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
  5596. }
  5597. didReadContent = true;
  5598. detectedIndent = true;
  5599. emptyLines = 0;
  5600. captureStart = state.position;
  5601. while (!is_EOL(ch) && (ch !== 0)) {
  5602. ch = state.input.charCodeAt(++state.position);
  5603. }
  5604. captureSegment(state, captureStart, state.position, false);
  5605. }
  5606. return true;
  5607. }
  5608. function readBlockSequence(state, nodeIndent) {
  5609. var _line,
  5610. _tag = state.tag,
  5611. _anchor = state.anchor,
  5612. _result = [],
  5613. following,
  5614. detected = false,
  5615. ch;
  5616. // there is a leading tab before this token, so it can't be a block sequence/mapping;
  5617. // it can still be flow sequence/mapping or a scalar
  5618. if (state.firstTabInLine !== -1) return false;
  5619. if (state.anchor !== null) {
  5620. state.anchorMap[state.anchor] = _result;
  5621. }
  5622. ch = state.input.charCodeAt(state.position);
  5623. while (ch !== 0) {
  5624. if (state.firstTabInLine !== -1) {
  5625. state.position = state.firstTabInLine;
  5626. throwError(state, 'tab characters must not be used in indentation');
  5627. }
  5628. if (ch !== 0x2D/* - */) {
  5629. break;
  5630. }
  5631. following = state.input.charCodeAt(state.position + 1);
  5632. if (!is_WS_OR_EOL(following)) {
  5633. break;
  5634. }
  5635. detected = true;
  5636. state.position++;
  5637. if (skipSeparationSpace(state, true, -1)) {
  5638. if (state.lineIndent <= nodeIndent) {
  5639. _result.push(null);
  5640. ch = state.input.charCodeAt(state.position);
  5641. continue;
  5642. }
  5643. }
  5644. _line = state.line;
  5645. composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
  5646. _result.push(state.result);
  5647. skipSeparationSpace(state, true, -1);
  5648. ch = state.input.charCodeAt(state.position);
  5649. if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
  5650. throwError(state, 'bad indentation of a sequence entry');
  5651. } else if (state.lineIndent < nodeIndent) {
  5652. break;
  5653. }
  5654. }
  5655. if (detected) {
  5656. state.tag = _tag;
  5657. state.anchor = _anchor;
  5658. state.kind = 'sequence';
  5659. state.result = _result;
  5660. return true;
  5661. }
  5662. return false;
  5663. }
  5664. function readBlockMapping(state, nodeIndent, flowIndent) {
  5665. var following,
  5666. allowCompact,
  5667. _line,
  5668. _keyLine,
  5669. _keyLineStart,
  5670. _keyPos,
  5671. _tag = state.tag,
  5672. _anchor = state.anchor,
  5673. _result = {},
  5674. overridableKeys = Object.create(null),
  5675. keyTag = null,
  5676. keyNode = null,
  5677. valueNode = null,
  5678. atExplicitKey = false,
  5679. detected = false,
  5680. ch;
  5681. // there is a leading tab before this token, so it can't be a block sequence/mapping;
  5682. // it can still be flow sequence/mapping or a scalar
  5683. if (state.firstTabInLine !== -1) return false;
  5684. if (state.anchor !== null) {
  5685. state.anchorMap[state.anchor] = _result;
  5686. }
  5687. ch = state.input.charCodeAt(state.position);
  5688. while (ch !== 0) {
  5689. if (!atExplicitKey && state.firstTabInLine !== -1) {
  5690. state.position = state.firstTabInLine;
  5691. throwError(state, 'tab characters must not be used in indentation');
  5692. }
  5693. following = state.input.charCodeAt(state.position + 1);
  5694. _line = state.line; // Save the current line.
  5695. //
  5696. // Explicit notation case. There are two separate blocks:
  5697. // first for the key (denoted by "?") and second for the value (denoted by ":")
  5698. //
  5699. if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
  5700. if (ch === 0x3F/* ? */) {
  5701. if (atExplicitKey) {
  5702. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  5703. keyTag = keyNode = valueNode = null;
  5704. }
  5705. detected = true;
  5706. atExplicitKey = true;
  5707. allowCompact = true;
  5708. } else if (atExplicitKey) {
  5709. // i.e. 0x3A/* : */ === character after the explicit key.
  5710. atExplicitKey = false;
  5711. allowCompact = true;
  5712. } else {
  5713. throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
  5714. }
  5715. state.position += 1;
  5716. ch = following;
  5717. //
  5718. // Implicit notation case. Flow-style node as the key first, then ":", and the value.
  5719. //
  5720. } else {
  5721. _keyLine = state.line;
  5722. _keyLineStart = state.lineStart;
  5723. _keyPos = state.position;
  5724. if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
  5725. // Neither implicit nor explicit notation.
  5726. // Reading is done. Go to the epilogue.
  5727. break;
  5728. }
  5729. if (state.line === _line) {
  5730. ch = state.input.charCodeAt(state.position);
  5731. while (is_WHITE_SPACE(ch)) {
  5732. ch = state.input.charCodeAt(++state.position);
  5733. }
  5734. if (ch === 0x3A/* : */) {
  5735. ch = state.input.charCodeAt(++state.position);
  5736. if (!is_WS_OR_EOL(ch)) {
  5737. throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
  5738. }
  5739. if (atExplicitKey) {
  5740. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  5741. keyTag = keyNode = valueNode = null;
  5742. }
  5743. detected = true;
  5744. atExplicitKey = false;
  5745. allowCompact = false;
  5746. keyTag = state.tag;
  5747. keyNode = state.result;
  5748. } else if (detected) {
  5749. throwError(state, 'can not read an implicit mapping pair; a colon is missed');
  5750. } else {
  5751. state.tag = _tag;
  5752. state.anchor = _anchor;
  5753. return true; // Keep the result of `composeNode`.
  5754. }
  5755. } else if (detected) {
  5756. throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
  5757. } else {
  5758. state.tag = _tag;
  5759. state.anchor = _anchor;
  5760. return true; // Keep the result of `composeNode`.
  5761. }
  5762. }
  5763. //
  5764. // Common reading code for both explicit and implicit notations.
  5765. //
  5766. if (state.line === _line || state.lineIndent > nodeIndent) {
  5767. if (atExplicitKey) {
  5768. _keyLine = state.line;
  5769. _keyLineStart = state.lineStart;
  5770. _keyPos = state.position;
  5771. }
  5772. if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
  5773. if (atExplicitKey) {
  5774. keyNode = state.result;
  5775. } else {
  5776. valueNode = state.result;
  5777. }
  5778. }
  5779. if (!atExplicitKey) {
  5780. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
  5781. keyTag = keyNode = valueNode = null;
  5782. }
  5783. skipSeparationSpace(state, true, -1);
  5784. ch = state.input.charCodeAt(state.position);
  5785. }
  5786. if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
  5787. throwError(state, 'bad indentation of a mapping entry');
  5788. } else if (state.lineIndent < nodeIndent) {
  5789. break;
  5790. }
  5791. }
  5792. //
  5793. // Epilogue.
  5794. //
  5795. // Special case: last mapping's node contains only the key in explicit notation.
  5796. if (atExplicitKey) {
  5797. storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
  5798. }
  5799. // Expose the resulting mapping.
  5800. if (detected) {
  5801. state.tag = _tag;
  5802. state.anchor = _anchor;
  5803. state.kind = 'mapping';
  5804. state.result = _result;
  5805. }
  5806. return detected;
  5807. }
  5808. function readTagProperty(state) {
  5809. var _position,
  5810. isVerbatim = false,
  5811. isNamed = false,
  5812. tagHandle,
  5813. tagName,
  5814. ch;
  5815. ch = state.input.charCodeAt(state.position);
  5816. if (ch !== 0x21/* ! */) return false;
  5817. if (state.tag !== null) {
  5818. throwError(state, 'duplication of a tag property');
  5819. }
  5820. ch = state.input.charCodeAt(++state.position);
  5821. if (ch === 0x3C/* < */) {
  5822. isVerbatim = true;
  5823. ch = state.input.charCodeAt(++state.position);
  5824. } else if (ch === 0x21/* ! */) {
  5825. isNamed = true;
  5826. tagHandle = '!!';
  5827. ch = state.input.charCodeAt(++state.position);
  5828. } else {
  5829. tagHandle = '!';
  5830. }
  5831. _position = state.position;
  5832. if (isVerbatim) {
  5833. do { ch = state.input.charCodeAt(++state.position); }
  5834. while (ch !== 0 && ch !== 0x3E/* > */);
  5835. if (state.position < state.length) {
  5836. tagName = state.input.slice(_position, state.position);
  5837. ch = state.input.charCodeAt(++state.position);
  5838. } else {
  5839. throwError(state, 'unexpected end of the stream within a verbatim tag');
  5840. }
  5841. } else {
  5842. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  5843. if (ch === 0x21/* ! */) {
  5844. if (!isNamed) {
  5845. tagHandle = state.input.slice(_position - 1, state.position + 1);
  5846. if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
  5847. throwError(state, 'named tag handle cannot contain such characters');
  5848. }
  5849. isNamed = true;
  5850. _position = state.position + 1;
  5851. } else {
  5852. throwError(state, 'tag suffix cannot contain exclamation marks');
  5853. }
  5854. }
  5855. ch = state.input.charCodeAt(++state.position);
  5856. }
  5857. tagName = state.input.slice(_position, state.position);
  5858. if (PATTERN_FLOW_INDICATORS.test(tagName)) {
  5859. throwError(state, 'tag suffix cannot contain flow indicator characters');
  5860. }
  5861. }
  5862. if (tagName && !PATTERN_TAG_URI.test(tagName)) {
  5863. throwError(state, 'tag name cannot contain such characters: ' + tagName);
  5864. }
  5865. try {
  5866. tagName = decodeURIComponent(tagName);
  5867. } catch (err) {
  5868. throwError(state, 'tag name is malformed: ' + tagName);
  5869. }
  5870. if (isVerbatim) {
  5871. state.tag = tagName;
  5872. } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
  5873. state.tag = state.tagMap[tagHandle] + tagName;
  5874. } else if (tagHandle === '!') {
  5875. state.tag = '!' + tagName;
  5876. } else if (tagHandle === '!!') {
  5877. state.tag = 'tag:yaml.org,2002:' + tagName;
  5878. } else {
  5879. throwError(state, 'undeclared tag handle "' + tagHandle + '"');
  5880. }
  5881. return true;
  5882. }
  5883. function readAnchorProperty(state) {
  5884. var _position,
  5885. ch;
  5886. ch = state.input.charCodeAt(state.position);
  5887. if (ch !== 0x26/* & */) return false;
  5888. if (state.anchor !== null) {
  5889. throwError(state, 'duplication of an anchor property');
  5890. }
  5891. ch = state.input.charCodeAt(++state.position);
  5892. _position = state.position;
  5893. while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
  5894. ch = state.input.charCodeAt(++state.position);
  5895. }
  5896. if (state.position === _position) {
  5897. throwError(state, 'name of an anchor node must contain at least one character');
  5898. }
  5899. state.anchor = state.input.slice(_position, state.position);
  5900. return true;
  5901. }
  5902. function readAlias(state) {
  5903. var _position, alias,
  5904. ch;
  5905. ch = state.input.charCodeAt(state.position);
  5906. if (ch !== 0x2A/* * */) return false;
  5907. ch = state.input.charCodeAt(++state.position);
  5908. _position = state.position;
  5909. while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
  5910. ch = state.input.charCodeAt(++state.position);
  5911. }
  5912. if (state.position === _position) {
  5913. throwError(state, 'name of an alias node must contain at least one character');
  5914. }
  5915. alias = state.input.slice(_position, state.position);
  5916. if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
  5917. throwError(state, 'unidentified alias "' + alias + '"');
  5918. }
  5919. state.result = state.anchorMap[alias];
  5920. skipSeparationSpace(state, true, -1);
  5921. return true;
  5922. }
  5923. function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
  5924. var allowBlockStyles,
  5925. allowBlockScalars,
  5926. allowBlockCollections,
  5927. indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
  5928. atNewLine = false,
  5929. hasContent = false,
  5930. typeIndex,
  5931. typeQuantity,
  5932. typeList,
  5933. type,
  5934. flowIndent,
  5935. blockIndent;
  5936. if (state.listener !== null) {
  5937. state.listener('open', state);
  5938. }
  5939. state.tag = null;
  5940. state.anchor = null;
  5941. state.kind = null;
  5942. state.result = null;
  5943. allowBlockStyles = allowBlockScalars = allowBlockCollections =
  5944. CONTEXT_BLOCK_OUT === nodeContext ||
  5945. CONTEXT_BLOCK_IN === nodeContext;
  5946. if (allowToSeek) {
  5947. if (skipSeparationSpace(state, true, -1)) {
  5948. atNewLine = true;
  5949. if (state.lineIndent > parentIndent) {
  5950. indentStatus = 1;
  5951. } else if (state.lineIndent === parentIndent) {
  5952. indentStatus = 0;
  5953. } else if (state.lineIndent < parentIndent) {
  5954. indentStatus = -1;
  5955. }
  5956. }
  5957. }
  5958. if (indentStatus === 1) {
  5959. while (readTagProperty(state) || readAnchorProperty(state)) {
  5960. if (skipSeparationSpace(state, true, -1)) {
  5961. atNewLine = true;
  5962. allowBlockCollections = allowBlockStyles;
  5963. if (state.lineIndent > parentIndent) {
  5964. indentStatus = 1;
  5965. } else if (state.lineIndent === parentIndent) {
  5966. indentStatus = 0;
  5967. } else if (state.lineIndent < parentIndent) {
  5968. indentStatus = -1;
  5969. }
  5970. } else {
  5971. allowBlockCollections = false;
  5972. }
  5973. }
  5974. }
  5975. if (allowBlockCollections) {
  5976. allowBlockCollections = atNewLine || allowCompact;
  5977. }
  5978. if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
  5979. if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
  5980. flowIndent = parentIndent;
  5981. } else {
  5982. flowIndent = parentIndent + 1;
  5983. }
  5984. blockIndent = state.position - state.lineStart;
  5985. if (indentStatus === 1) {
  5986. if (allowBlockCollections &&
  5987. (readBlockSequence(state, blockIndent) ||
  5988. readBlockMapping(state, blockIndent, flowIndent)) ||
  5989. readFlowCollection(state, flowIndent)) {
  5990. hasContent = true;
  5991. } else {
  5992. if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
  5993. readSingleQuotedScalar(state, flowIndent) ||
  5994. readDoubleQuotedScalar(state, flowIndent)) {
  5995. hasContent = true;
  5996. } else if (readAlias(state)) {
  5997. hasContent = true;
  5998. if (state.tag !== null || state.anchor !== null) {
  5999. throwError(state, 'alias node should not have any properties');
  6000. }
  6001. } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
  6002. hasContent = true;
  6003. if (state.tag === null) {
  6004. state.tag = '?';
  6005. }
  6006. }
  6007. if (state.anchor !== null) {
  6008. state.anchorMap[state.anchor] = state.result;
  6009. }
  6010. }
  6011. } else if (indentStatus === 0) {
  6012. // Special case: block sequences are allowed to have same indentation level as the parent.
  6013. // http://www.yaml.org/spec/1.2/spec.html#id2799784
  6014. hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
  6015. }
  6016. }
  6017. if (state.tag === null) {
  6018. if (state.anchor !== null) {
  6019. state.anchorMap[state.anchor] = state.result;
  6020. }
  6021. } else if (state.tag === '?') {
  6022. // Implicit resolving is not allowed for non-scalar types, and '?'
  6023. // non-specific tag is only automatically assigned to plain scalars.
  6024. //
  6025. // We only need to check kind conformity in case user explicitly assigns '?'
  6026. // tag, for example like this: "!<?> [0]"
  6027. //
  6028. if (state.result !== null && state.kind !== 'scalar') {
  6029. throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
  6030. }
  6031. for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
  6032. type = state.implicitTypes[typeIndex];
  6033. if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
  6034. state.result = type.construct(state.result);
  6035. state.tag = type.tag;
  6036. if (state.anchor !== null) {
  6037. state.anchorMap[state.anchor] = state.result;
  6038. }
  6039. break;
  6040. }
  6041. }
  6042. } else if (state.tag !== '!') {
  6043. if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
  6044. type = state.typeMap[state.kind || 'fallback'][state.tag];
  6045. } else {
  6046. // looking for multi type
  6047. type = null;
  6048. typeList = state.typeMap.multi[state.kind || 'fallback'];
  6049. for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
  6050. if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
  6051. type = typeList[typeIndex];
  6052. break;
  6053. }
  6054. }
  6055. }
  6056. if (!type) {
  6057. throwError(state, 'unknown tag !<' + state.tag + '>');
  6058. }
  6059. if (state.result !== null && type.kind !== state.kind) {
  6060. throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
  6061. }
  6062. if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
  6063. throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
  6064. } else {
  6065. state.result = type.construct(state.result, state.tag);
  6066. if (state.anchor !== null) {
  6067. state.anchorMap[state.anchor] = state.result;
  6068. }
  6069. }
  6070. }
  6071. if (state.listener !== null) {
  6072. state.listener('close', state);
  6073. }
  6074. return state.tag !== null || state.anchor !== null || hasContent;
  6075. }
  6076. function readDocument(state) {
  6077. var documentStart = state.position,
  6078. _position,
  6079. directiveName,
  6080. directiveArgs,
  6081. hasDirectives = false,
  6082. ch;
  6083. state.version = null;
  6084. state.checkLineBreaks = state.legacy;
  6085. state.tagMap = Object.create(null);
  6086. state.anchorMap = Object.create(null);
  6087. while ((ch = state.input.charCodeAt(state.position)) !== 0) {
  6088. skipSeparationSpace(state, true, -1);
  6089. ch = state.input.charCodeAt(state.position);
  6090. if (state.lineIndent > 0 || ch !== 0x25/* % */) {
  6091. break;
  6092. }
  6093. hasDirectives = true;
  6094. ch = state.input.charCodeAt(++state.position);
  6095. _position = state.position;
  6096. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  6097. ch = state.input.charCodeAt(++state.position);
  6098. }
  6099. directiveName = state.input.slice(_position, state.position);
  6100. directiveArgs = [];
  6101. if (directiveName.length < 1) {
  6102. throwError(state, 'directive name must not be less than one character in length');
  6103. }
  6104. while (ch !== 0) {
  6105. while (is_WHITE_SPACE(ch)) {
  6106. ch = state.input.charCodeAt(++state.position);
  6107. }
  6108. if (ch === 0x23/* # */) {
  6109. do { ch = state.input.charCodeAt(++state.position); }
  6110. while (ch !== 0 && !is_EOL(ch));
  6111. break;
  6112. }
  6113. if (is_EOL(ch)) break;
  6114. _position = state.position;
  6115. while (ch !== 0 && !is_WS_OR_EOL(ch)) {
  6116. ch = state.input.charCodeAt(++state.position);
  6117. }
  6118. directiveArgs.push(state.input.slice(_position, state.position));
  6119. }
  6120. if (ch !== 0) readLineBreak(state);
  6121. if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
  6122. directiveHandlers[directiveName](state, directiveName, directiveArgs);
  6123. } else {
  6124. throwWarning(state, 'unknown document directive "' + directiveName + '"');
  6125. }
  6126. }
  6127. skipSeparationSpace(state, true, -1);
  6128. if (state.lineIndent === 0 &&
  6129. state.input.charCodeAt(state.position) === 0x2D/* - */ &&
  6130. state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
  6131. state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
  6132. state.position += 3;
  6133. skipSeparationSpace(state, true, -1);
  6134. } else if (hasDirectives) {
  6135. throwError(state, 'directives end mark is expected');
  6136. }
  6137. composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
  6138. skipSeparationSpace(state, true, -1);
  6139. if (state.checkLineBreaks &&
  6140. PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
  6141. throwWarning(state, 'non-ASCII line breaks are interpreted as content');
  6142. }
  6143. state.documents.push(state.result);
  6144. if (state.position === state.lineStart && testDocumentSeparator(state)) {
  6145. if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
  6146. state.position += 3;
  6147. skipSeparationSpace(state, true, -1);
  6148. }
  6149. return;
  6150. }
  6151. if (state.position < (state.length - 1)) {
  6152. throwError(state, 'end of the stream or a document separator is expected');
  6153. } else {
  6154. return;
  6155. }
  6156. }
  6157. function loadDocuments(input, options) {
  6158. input = String(input);
  6159. options = options || {};
  6160. if (input.length !== 0) {
  6161. // Add tailing `\n` if not exists
  6162. if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
  6163. input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
  6164. input += '\n';
  6165. }
  6166. // Strip BOM
  6167. if (input.charCodeAt(0) === 0xFEFF) {
  6168. input = input.slice(1);
  6169. }
  6170. }
  6171. var state = new State$1(input, options);
  6172. var nullpos = input.indexOf('\0');
  6173. if (nullpos !== -1) {
  6174. state.position = nullpos;
  6175. throwError(state, 'null byte is not allowed in input');
  6176. }
  6177. // Use 0 as string terminator. That significantly simplifies bounds check.
  6178. state.input += '\0';
  6179. while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
  6180. state.lineIndent += 1;
  6181. state.position += 1;
  6182. }
  6183. while (state.position < (state.length - 1)) {
  6184. readDocument(state);
  6185. }
  6186. return state.documents;
  6187. }
  6188. function loadAll$1(input, iterator, options) {
  6189. if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
  6190. options = iterator;
  6191. iterator = null;
  6192. }
  6193. var documents = loadDocuments(input, options);
  6194. if (typeof iterator !== 'function') {
  6195. return documents;
  6196. }
  6197. for (var index = 0, length = documents.length; index < length; index += 1) {
  6198. iterator(documents[index]);
  6199. }
  6200. }
  6201. function load$1(input, options) {
  6202. var documents = loadDocuments(input, options);
  6203. if (documents.length === 0) {
  6204. /*eslint-disable no-undefined*/
  6205. return undefined;
  6206. } else if (documents.length === 1) {
  6207. return documents[0];
  6208. }
  6209. throw new exception('expected a single document in the stream, but found more');
  6210. }
  6211. var loadAll_1 = loadAll$1;
  6212. var load_1 = load$1;
  6213. var loader = {
  6214. loadAll: loadAll_1,
  6215. load: load_1
  6216. };
  6217. /*eslint-disable no-use-before-define*/
  6218. var _toString = Object.prototype.toString;
  6219. var _hasOwnProperty = Object.prototype.hasOwnProperty;
  6220. var CHAR_BOM = 0xFEFF;
  6221. var CHAR_TAB = 0x09; /* Tab */
  6222. var CHAR_LINE_FEED = 0x0A; /* LF */
  6223. var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
  6224. var CHAR_SPACE = 0x20; /* Space */
  6225. var CHAR_EXCLAMATION = 0x21; /* ! */
  6226. var CHAR_DOUBLE_QUOTE = 0x22; /* " */
  6227. var CHAR_SHARP = 0x23; /* # */
  6228. var CHAR_PERCENT = 0x25; /* % */
  6229. var CHAR_AMPERSAND = 0x26; /* & */
  6230. var CHAR_SINGLE_QUOTE = 0x27; /* ' */
  6231. var CHAR_ASTERISK = 0x2A; /* * */
  6232. var CHAR_COMMA = 0x2C; /* , */
  6233. var CHAR_MINUS = 0x2D; /* - */
  6234. var CHAR_COLON = 0x3A; /* : */
  6235. var CHAR_EQUALS = 0x3D; /* = */
  6236. var CHAR_GREATER_THAN = 0x3E; /* > */
  6237. var CHAR_QUESTION = 0x3F; /* ? */
  6238. var CHAR_COMMERCIAL_AT = 0x40; /* @ */
  6239. var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
  6240. var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
  6241. var CHAR_GRAVE_ACCENT = 0x60; /* ` */
  6242. var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
  6243. var CHAR_VERTICAL_LINE = 0x7C; /* | */
  6244. var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
  6245. var ESCAPE_SEQUENCES = {};
  6246. ESCAPE_SEQUENCES[0x00] = '\\0';
  6247. ESCAPE_SEQUENCES[0x07] = '\\a';
  6248. ESCAPE_SEQUENCES[0x08] = '\\b';
  6249. ESCAPE_SEQUENCES[0x09] = '\\t';
  6250. ESCAPE_SEQUENCES[0x0A] = '\\n';
  6251. ESCAPE_SEQUENCES[0x0B] = '\\v';
  6252. ESCAPE_SEQUENCES[0x0C] = '\\f';
  6253. ESCAPE_SEQUENCES[0x0D] = '\\r';
  6254. ESCAPE_SEQUENCES[0x1B] = '\\e';
  6255. ESCAPE_SEQUENCES[0x22] = '\\"';
  6256. ESCAPE_SEQUENCES[0x5C] = '\\\\';
  6257. ESCAPE_SEQUENCES[0x85] = '\\N';
  6258. ESCAPE_SEQUENCES[0xA0] = '\\_';
  6259. ESCAPE_SEQUENCES[0x2028] = '\\L';
  6260. ESCAPE_SEQUENCES[0x2029] = '\\P';
  6261. var DEPRECATED_BOOLEANS_SYNTAX = [
  6262. 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
  6263. 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
  6264. ];
  6265. var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
  6266. function compileStyleMap(schema, map) {
  6267. var result, keys, index, length, tag, style, type;
  6268. if (map === null) return {};
  6269. result = {};
  6270. keys = Object.keys(map);
  6271. for (index = 0, length = keys.length; index < length; index += 1) {
  6272. tag = keys[index];
  6273. style = String(map[tag]);
  6274. if (tag.slice(0, 2) === '!!') {
  6275. tag = 'tag:yaml.org,2002:' + tag.slice(2);
  6276. }
  6277. type = schema.compiledTypeMap['fallback'][tag];
  6278. if (type && _hasOwnProperty.call(type.styleAliases, style)) {
  6279. style = type.styleAliases[style];
  6280. }
  6281. result[tag] = style;
  6282. }
  6283. return result;
  6284. }
  6285. function encodeHex(character) {
  6286. var string, handle, length;
  6287. string = character.toString(16).toUpperCase();
  6288. if (character <= 0xFF) {
  6289. handle = 'x';
  6290. length = 2;
  6291. } else if (character <= 0xFFFF) {
  6292. handle = 'u';
  6293. length = 4;
  6294. } else if (character <= 0xFFFFFFFF) {
  6295. handle = 'U';
  6296. length = 8;
  6297. } else {
  6298. throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
  6299. }
  6300. return '\\' + handle + common.repeat('0', length - string.length) + string;
  6301. }
  6302. var QUOTING_TYPE_SINGLE = 1,
  6303. QUOTING_TYPE_DOUBLE = 2;
  6304. function State(options) {
  6305. this.schema = options['schema'] || _default;
  6306. this.indent = Math.max(1, (options['indent'] || 2));
  6307. this.noArrayIndent = options['noArrayIndent'] || false;
  6308. this.skipInvalid = options['skipInvalid'] || false;
  6309. this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
  6310. this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
  6311. this.sortKeys = options['sortKeys'] || false;
  6312. this.lineWidth = options['lineWidth'] || 80;
  6313. this.noRefs = options['noRefs'] || false;
  6314. this.noCompatMode = options['noCompatMode'] || false;
  6315. this.condenseFlow = options['condenseFlow'] || false;
  6316. this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
  6317. this.forceQuotes = options['forceQuotes'] || false;
  6318. this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;
  6319. this.implicitTypes = this.schema.compiledImplicit;
  6320. this.explicitTypes = this.schema.compiledExplicit;
  6321. this.tag = null;
  6322. this.result = '';
  6323. this.duplicates = [];
  6324. this.usedDuplicates = null;
  6325. }
  6326. // Indents every line in a string. Empty lines (\n only) are not indented.
  6327. function indentString(string, spaces) {
  6328. var ind = common.repeat(' ', spaces),
  6329. position = 0,
  6330. next = -1,
  6331. result = '',
  6332. line,
  6333. length = string.length;
  6334. while (position < length) {
  6335. next = string.indexOf('\n', position);
  6336. if (next === -1) {
  6337. line = string.slice(position);
  6338. position = length;
  6339. } else {
  6340. line = string.slice(position, next + 1);
  6341. position = next + 1;
  6342. }
  6343. if (line.length && line !== '\n') result += ind;
  6344. result += line;
  6345. }
  6346. return result;
  6347. }
  6348. function generateNextLine(state, level) {
  6349. return '\n' + common.repeat(' ', state.indent * level);
  6350. }
  6351. function testImplicitResolving(state, str) {
  6352. var index, length, type;
  6353. for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
  6354. type = state.implicitTypes[index];
  6355. if (type.resolve(str)) {
  6356. return true;
  6357. }
  6358. }
  6359. return false;
  6360. }
  6361. // [33] s-white ::= s-space | s-tab
  6362. function isWhitespace(c) {
  6363. return c === CHAR_SPACE || c === CHAR_TAB;
  6364. }
  6365. // Returns true if the character can be printed without escaping.
  6366. // From YAML 1.2: "any allowed characters known to be non-printable
  6367. // should also be escaped. [However,] This isn’t mandatory"
  6368. // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
  6369. function isPrintable(c) {
  6370. return (0x00020 <= c && c <= 0x00007E)
  6371. || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
  6372. || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
  6373. || (0x10000 <= c && c <= 0x10FFFF);
  6374. }
  6375. // [34] ns-char ::= nb-char - s-white
  6376. // [27] nb-char ::= c-printable - b-char - c-byte-order-mark
  6377. // [26] b-char ::= b-line-feed | b-carriage-return
  6378. // Including s-white (for some reason, examples doesn't match specs in this aspect)
  6379. // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
  6380. function isNsCharOrWhitespace(c) {
  6381. return isPrintable(c)
  6382. && c !== CHAR_BOM
  6383. // - b-char
  6384. && c !== CHAR_CARRIAGE_RETURN
  6385. && c !== CHAR_LINE_FEED;
  6386. }
  6387. // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out
  6388. // c = flow-in ⇒ ns-plain-safe-in
  6389. // c = block-key ⇒ ns-plain-safe-out
  6390. // c = flow-key ⇒ ns-plain-safe-in
  6391. // [128] ns-plain-safe-out ::= ns-char
  6392. // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator
  6393. // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )
  6394. // | ( /* An ns-char preceding */ “#” )
  6395. // | ( “:” /* Followed by an ns-plain-safe(c) */ )
  6396. function isPlainSafe(c, prev, inblock) {
  6397. var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
  6398. var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
  6399. return (
  6400. // ns-plain-safe
  6401. inblock ? // c = flow-in
  6402. cIsNsCharOrWhitespace
  6403. : cIsNsCharOrWhitespace
  6404. // - c-flow-indicator
  6405. && c !== CHAR_COMMA
  6406. && c !== CHAR_LEFT_SQUARE_BRACKET
  6407. && c !== CHAR_RIGHT_SQUARE_BRACKET
  6408. && c !== CHAR_LEFT_CURLY_BRACKET
  6409. && c !== CHAR_RIGHT_CURLY_BRACKET
  6410. )
  6411. // ns-plain-char
  6412. && c !== CHAR_SHARP // false on '#'
  6413. && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
  6414. || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
  6415. || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
  6416. }
  6417. // Simplified test for values allowed as the first character in plain style.
  6418. function isPlainSafeFirst(c) {
  6419. // Uses a subset of ns-char - c-indicator
  6420. // where ns-char = nb-char - s-white.
  6421. // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
  6422. return isPrintable(c) && c !== CHAR_BOM
  6423. && !isWhitespace(c) // - s-white
  6424. // - (c-indicator ::=
  6425. // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
  6426. && c !== CHAR_MINUS
  6427. && c !== CHAR_QUESTION
  6428. && c !== CHAR_COLON
  6429. && c !== CHAR_COMMA
  6430. && c !== CHAR_LEFT_SQUARE_BRACKET
  6431. && c !== CHAR_RIGHT_SQUARE_BRACKET
  6432. && c !== CHAR_LEFT_CURLY_BRACKET
  6433. && c !== CHAR_RIGHT_CURLY_BRACKET
  6434. // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
  6435. && c !== CHAR_SHARP
  6436. && c !== CHAR_AMPERSAND
  6437. && c !== CHAR_ASTERISK
  6438. && c !== CHAR_EXCLAMATION
  6439. && c !== CHAR_VERTICAL_LINE
  6440. && c !== CHAR_EQUALS
  6441. && c !== CHAR_GREATER_THAN
  6442. && c !== CHAR_SINGLE_QUOTE
  6443. && c !== CHAR_DOUBLE_QUOTE
  6444. // | “%” | “@” | “`”)
  6445. && c !== CHAR_PERCENT
  6446. && c !== CHAR_COMMERCIAL_AT
  6447. && c !== CHAR_GRAVE_ACCENT;
  6448. }
  6449. // Simplified test for values allowed as the last character in plain style.
  6450. function isPlainSafeLast(c) {
  6451. // just not whitespace or colon, it will be checked to be plain character later
  6452. return !isWhitespace(c) && c !== CHAR_COLON;
  6453. }
  6454. // Same as 'string'.codePointAt(pos), but works in older browsers.
  6455. function codePointAt(string, pos) {
  6456. var first = string.charCodeAt(pos), second;
  6457. if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
  6458. second = string.charCodeAt(pos + 1);
  6459. if (second >= 0xDC00 && second <= 0xDFFF) {
  6460. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  6461. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  6462. }
  6463. }
  6464. return first;
  6465. }
  6466. // Determines whether block indentation indicator is required.
  6467. function needIndentIndicator(string) {
  6468. var leadingSpaceRe = /^\n* /;
  6469. return leadingSpaceRe.test(string);
  6470. }
  6471. var STYLE_PLAIN = 1,
  6472. STYLE_SINGLE = 2,
  6473. STYLE_LITERAL = 3,
  6474. STYLE_FOLDED = 4,
  6475. STYLE_DOUBLE = 5;
  6476. // Determines which scalar styles are possible and returns the preferred style.
  6477. // lineWidth = -1 => no limit.
  6478. // Pre-conditions: str.length > 0.
  6479. // Post-conditions:
  6480. // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
  6481. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
  6482. // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
  6483. function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
  6484. testAmbiguousType, quotingType, forceQuotes, inblock) {
  6485. var i;
  6486. var char = 0;
  6487. var prevChar = null;
  6488. var hasLineBreak = false;
  6489. var hasFoldableLine = false; // only checked if shouldTrackWidth
  6490. var shouldTrackWidth = lineWidth !== -1;
  6491. var previousLineBreak = -1; // count the first line correctly
  6492. var plain = isPlainSafeFirst(codePointAt(string, 0))
  6493. && isPlainSafeLast(codePointAt(string, string.length - 1));
  6494. if (singleLineOnly || forceQuotes) {
  6495. // Case: no block styles.
  6496. // Check for disallowed characters to rule out plain and single.
  6497. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
  6498. char = codePointAt(string, i);
  6499. if (!isPrintable(char)) {
  6500. return STYLE_DOUBLE;
  6501. }
  6502. plain = plain && isPlainSafe(char, prevChar, inblock);
  6503. prevChar = char;
  6504. }
  6505. } else {
  6506. // Case: block styles permitted.
  6507. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
  6508. char = codePointAt(string, i);
  6509. if (char === CHAR_LINE_FEED) {
  6510. hasLineBreak = true;
  6511. // Check if any line can be folded.
  6512. if (shouldTrackWidth) {
  6513. hasFoldableLine = hasFoldableLine ||
  6514. // Foldable line = too long, and not more-indented.
  6515. (i - previousLineBreak - 1 > lineWidth &&
  6516. string[previousLineBreak + 1] !== ' ');
  6517. previousLineBreak = i;
  6518. }
  6519. } else if (!isPrintable(char)) {
  6520. return STYLE_DOUBLE;
  6521. }
  6522. plain = plain && isPlainSafe(char, prevChar, inblock);
  6523. prevChar = char;
  6524. }
  6525. // in case the end is missing a \n
  6526. hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
  6527. (i - previousLineBreak - 1 > lineWidth &&
  6528. string[previousLineBreak + 1] !== ' '));
  6529. }
  6530. // Although every style can represent \n without escaping, prefer block styles
  6531. // for multiline, since they're more readable and they don't add empty lines.
  6532. // Also prefer folding a super-long line.
  6533. if (!hasLineBreak && !hasFoldableLine) {
  6534. // Strings interpretable as another type have to be quoted;
  6535. // e.g. the string 'true' vs. the boolean true.
  6536. if (plain && !forceQuotes && !testAmbiguousType(string)) {
  6537. return STYLE_PLAIN;
  6538. }
  6539. return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
  6540. }
  6541. // Edge case: block indentation indicator can only have one digit.
  6542. if (indentPerLevel > 9 && needIndentIndicator(string)) {
  6543. return STYLE_DOUBLE;
  6544. }
  6545. // At this point we know block styles are valid.
  6546. // Prefer literal style unless we want to fold.
  6547. if (!forceQuotes) {
  6548. return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
  6549. }
  6550. return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
  6551. }
  6552. // Note: line breaking/folding is implemented for only the folded style.
  6553. // NB. We drop the last trailing newline (if any) of a returned block scalar
  6554. // since the dumper adds its own newline. This always works:
  6555. // • No ending newline => unaffected; already using strip "-" chomping.
  6556. // • Ending newline => removed then restored.
  6557. // Importantly, this keeps the "+" chomp indicator from gaining an extra line.
  6558. function writeScalar(state, string, level, iskey, inblock) {
  6559. state.dump = (function () {
  6560. if (string.length === 0) {
  6561. return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
  6562. }
  6563. if (!state.noCompatMode) {
  6564. if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
  6565. return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
  6566. }
  6567. }
  6568. var indent = state.indent * Math.max(1, level); // no 0-indent scalars
  6569. // As indentation gets deeper, let the width decrease monotonically
  6570. // to the lower bound min(state.lineWidth, 40).
  6571. // Note that this implies
  6572. // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
  6573. // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
  6574. // This behaves better than a constant minimum width which disallows narrower options,
  6575. // or an indent threshold which causes the width to suddenly increase.
  6576. var lineWidth = state.lineWidth === -1
  6577. ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
  6578. // Without knowing if keys are implicit/explicit, assume implicit for safety.
  6579. var singleLineOnly = iskey
  6580. // No block styles in flow mode.
  6581. || (state.flowLevel > -1 && level >= state.flowLevel);
  6582. function testAmbiguity(string) {
  6583. return testImplicitResolving(state, string);
  6584. }
  6585. switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
  6586. testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
  6587. case STYLE_PLAIN:
  6588. return string;
  6589. case STYLE_SINGLE:
  6590. return "'" + string.replace(/'/g, "''") + "'";
  6591. case STYLE_LITERAL:
  6592. return '|' + blockHeader(string, state.indent)
  6593. + dropEndingNewline(indentString(string, indent));
  6594. case STYLE_FOLDED:
  6595. return '>' + blockHeader(string, state.indent)
  6596. + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
  6597. case STYLE_DOUBLE:
  6598. return '"' + escapeString(string) + '"';
  6599. default:
  6600. throw new exception('impossible error: invalid scalar style');
  6601. }
  6602. }());
  6603. }
  6604. // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
  6605. function blockHeader(string, indentPerLevel) {
  6606. var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
  6607. // note the special case: the string '\n' counts as a "trailing" empty line.
  6608. var clip = string[string.length - 1] === '\n';
  6609. var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
  6610. var chomp = keep ? '+' : (clip ? '' : '-');
  6611. return indentIndicator + chomp + '\n';
  6612. }
  6613. // (See the note for writeScalar.)
  6614. function dropEndingNewline(string) {
  6615. return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
  6616. }
  6617. // Note: a long line without a suitable break point will exceed the width limit.
  6618. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
  6619. function foldString(string, width) {
  6620. // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
  6621. // unless they're before or after a more-indented line, or at the very
  6622. // beginning or end, in which case $k$ maps to $k$.
  6623. // Therefore, parse each chunk as newline(s) followed by a content line.
  6624. var lineRe = /(\n+)([^\n]*)/g;
  6625. // first line (possibly an empty line)
  6626. var result = (function () {
  6627. var nextLF = string.indexOf('\n');
  6628. nextLF = nextLF !== -1 ? nextLF : string.length;
  6629. lineRe.lastIndex = nextLF;
  6630. return foldLine(string.slice(0, nextLF), width);
  6631. }());
  6632. // If we haven't reached the first content line yet, don't add an extra \n.
  6633. var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
  6634. var moreIndented;
  6635. // rest of the lines
  6636. var match;
  6637. while ((match = lineRe.exec(string))) {
  6638. var prefix = match[1], line = match[2];
  6639. moreIndented = (line[0] === ' ');
  6640. result += prefix
  6641. + (!prevMoreIndented && !moreIndented && line !== ''
  6642. ? '\n' : '')
  6643. + foldLine(line, width);
  6644. prevMoreIndented = moreIndented;
  6645. }
  6646. return result;
  6647. }
  6648. // Greedy line breaking.
  6649. // Picks the longest line under the limit each time,
  6650. // otherwise settles for the shortest line over the limit.
  6651. // NB. More-indented lines *cannot* be folded, as that would add an extra \n.
  6652. function foldLine(line, width) {
  6653. if (line === '' || line[0] === ' ') return line;
  6654. // Since a more-indented line adds a \n, breaks can't be followed by a space.
  6655. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
  6656. var match;
  6657. // start is an inclusive index. end, curr, and next are exclusive.
  6658. var start = 0, end, curr = 0, next = 0;
  6659. var result = '';
  6660. // Invariants: 0 <= start <= length-1.
  6661. // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
  6662. // Inside the loop:
  6663. // A match implies length >= 2, so curr and next are <= length-2.
  6664. while ((match = breakRe.exec(line))) {
  6665. next = match.index;
  6666. // maintain invariant: curr - start <= width
  6667. if (next - start > width) {
  6668. end = (curr > start) ? curr : next; // derive end <= length-2
  6669. result += '\n' + line.slice(start, end);
  6670. // skip the space that was output as \n
  6671. start = end + 1; // derive start <= length-1
  6672. }
  6673. curr = next;
  6674. }
  6675. // By the invariants, start <= length-1, so there is something left over.
  6676. // It is either the whole string or a part starting from non-whitespace.
  6677. result += '\n';
  6678. // Insert a break if the remainder is too long and there is a break available.
  6679. if (line.length - start > width && curr > start) {
  6680. result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
  6681. } else {
  6682. result += line.slice(start);
  6683. }
  6684. return result.slice(1); // drop extra \n joiner
  6685. }
  6686. // Escapes a double-quoted string.
  6687. function escapeString(string) {
  6688. var result = '';
  6689. var char = 0;
  6690. var escapeSeq;
  6691. for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
  6692. char = codePointAt(string, i);
  6693. escapeSeq = ESCAPE_SEQUENCES[char];
  6694. if (!escapeSeq && isPrintable(char)) {
  6695. result += string[i];
  6696. if (char >= 0x10000) result += string[i + 1];
  6697. } else {
  6698. result += escapeSeq || encodeHex(char);
  6699. }
  6700. }
  6701. return result;
  6702. }
  6703. function writeFlowSequence(state, level, object) {
  6704. var _result = '',
  6705. _tag = state.tag,
  6706. index,
  6707. length,
  6708. value;
  6709. for (index = 0, length = object.length; index < length; index += 1) {
  6710. value = object[index];
  6711. if (state.replacer) {
  6712. value = state.replacer.call(object, String(index), value);
  6713. }
  6714. // Write only valid elements, put null instead of invalid elements.
  6715. if (writeNode(state, level, value, false, false) ||
  6716. (typeof value === 'undefined' &&
  6717. writeNode(state, level, null, false, false))) {
  6718. if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
  6719. _result += state.dump;
  6720. }
  6721. }
  6722. state.tag = _tag;
  6723. state.dump = '[' + _result + ']';
  6724. }
  6725. function writeBlockSequence(state, level, object, compact) {
  6726. var _result = '',
  6727. _tag = state.tag,
  6728. index,
  6729. length,
  6730. value;
  6731. for (index = 0, length = object.length; index < length; index += 1) {
  6732. value = object[index];
  6733. if (state.replacer) {
  6734. value = state.replacer.call(object, String(index), value);
  6735. }
  6736. // Write only valid elements, put null instead of invalid elements.
  6737. if (writeNode(state, level + 1, value, true, true, false, true) ||
  6738. (typeof value === 'undefined' &&
  6739. writeNode(state, level + 1, null, true, true, false, true))) {
  6740. if (!compact || _result !== '') {
  6741. _result += generateNextLine(state, level);
  6742. }
  6743. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  6744. _result += '-';
  6745. } else {
  6746. _result += '- ';
  6747. }
  6748. _result += state.dump;
  6749. }
  6750. }
  6751. state.tag = _tag;
  6752. state.dump = _result || '[]'; // Empty sequence if no valid values.
  6753. }
  6754. function writeFlowMapping(state, level, object) {
  6755. var _result = '',
  6756. _tag = state.tag,
  6757. objectKeyList = Object.keys(object),
  6758. index,
  6759. length,
  6760. objectKey,
  6761. objectValue,
  6762. pairBuffer;
  6763. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  6764. pairBuffer = '';
  6765. if (_result !== '') pairBuffer += ', ';
  6766. if (state.condenseFlow) pairBuffer += '"';
  6767. objectKey = objectKeyList[index];
  6768. objectValue = object[objectKey];
  6769. if (state.replacer) {
  6770. objectValue = state.replacer.call(object, objectKey, objectValue);
  6771. }
  6772. if (!writeNode(state, level, objectKey, false, false)) {
  6773. continue; // Skip this pair because of invalid key;
  6774. }
  6775. if (state.dump.length > 1024) pairBuffer += '? ';
  6776. pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
  6777. if (!writeNode(state, level, objectValue, false, false)) {
  6778. continue; // Skip this pair because of invalid value.
  6779. }
  6780. pairBuffer += state.dump;
  6781. // Both key and value are valid.
  6782. _result += pairBuffer;
  6783. }
  6784. state.tag = _tag;
  6785. state.dump = '{' + _result + '}';
  6786. }
  6787. function writeBlockMapping(state, level, object, compact) {
  6788. var _result = '',
  6789. _tag = state.tag,
  6790. objectKeyList = Object.keys(object),
  6791. index,
  6792. length,
  6793. objectKey,
  6794. objectValue,
  6795. explicitPair,
  6796. pairBuffer;
  6797. // Allow sorting keys so that the output file is deterministic
  6798. if (state.sortKeys === true) {
  6799. // Default sorting
  6800. objectKeyList.sort();
  6801. } else if (typeof state.sortKeys === 'function') {
  6802. // Custom sort function
  6803. objectKeyList.sort(state.sortKeys);
  6804. } else if (state.sortKeys) {
  6805. // Something is wrong
  6806. throw new exception('sortKeys must be a boolean or a function');
  6807. }
  6808. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  6809. pairBuffer = '';
  6810. if (!compact || _result !== '') {
  6811. pairBuffer += generateNextLine(state, level);
  6812. }
  6813. objectKey = objectKeyList[index];
  6814. objectValue = object[objectKey];
  6815. if (state.replacer) {
  6816. objectValue = state.replacer.call(object, objectKey, objectValue);
  6817. }
  6818. if (!writeNode(state, level + 1, objectKey, true, true, true)) {
  6819. continue; // Skip this pair because of invalid key.
  6820. }
  6821. explicitPair = (state.tag !== null && state.tag !== '?') ||
  6822. (state.dump && state.dump.length > 1024);
  6823. if (explicitPair) {
  6824. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  6825. pairBuffer += '?';
  6826. } else {
  6827. pairBuffer += '? ';
  6828. }
  6829. }
  6830. pairBuffer += state.dump;
  6831. if (explicitPair) {
  6832. pairBuffer += generateNextLine(state, level);
  6833. }
  6834. if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
  6835. continue; // Skip this pair because of invalid value.
  6836. }
  6837. if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
  6838. pairBuffer += ':';
  6839. } else {
  6840. pairBuffer += ': ';
  6841. }
  6842. pairBuffer += state.dump;
  6843. // Both key and value are valid.
  6844. _result += pairBuffer;
  6845. }
  6846. state.tag = _tag;
  6847. state.dump = _result || '{}'; // Empty mapping if no valid pairs.
  6848. }
  6849. function detectType(state, object, explicit) {
  6850. var _result, typeList, index, length, type, style;
  6851. typeList = explicit ? state.explicitTypes : state.implicitTypes;
  6852. for (index = 0, length = typeList.length; index < length; index += 1) {
  6853. type = typeList[index];
  6854. if ((type.instanceOf || type.predicate) &&
  6855. (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
  6856. (!type.predicate || type.predicate(object))) {
  6857. if (explicit) {
  6858. if (type.multi && type.representName) {
  6859. state.tag = type.representName(object);
  6860. } else {
  6861. state.tag = type.tag;
  6862. }
  6863. } else {
  6864. state.tag = '?';
  6865. }
  6866. if (type.represent) {
  6867. style = state.styleMap[type.tag] || type.defaultStyle;
  6868. if (_toString.call(type.represent) === '[object Function]') {
  6869. _result = type.represent(object, style);
  6870. } else if (_hasOwnProperty.call(type.represent, style)) {
  6871. _result = type.represent[style](object, style);
  6872. } else {
  6873. throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
  6874. }
  6875. state.dump = _result;
  6876. }
  6877. return true;
  6878. }
  6879. }
  6880. return false;
  6881. }
  6882. // Serializes `object` and writes it to global `result`.
  6883. // Returns true on success, or false on invalid object.
  6884. //
  6885. function writeNode(state, level, object, block, compact, iskey, isblockseq) {
  6886. state.tag = null;
  6887. state.dump = object;
  6888. if (!detectType(state, object, false)) {
  6889. detectType(state, object, true);
  6890. }
  6891. var type = _toString.call(state.dump);
  6892. var inblock = block;
  6893. var tagStr;
  6894. if (block) {
  6895. block = (state.flowLevel < 0 || state.flowLevel > level);
  6896. }
  6897. var objectOrArray = type === '[object Object]' || type === '[object Array]',
  6898. duplicateIndex,
  6899. duplicate;
  6900. if (objectOrArray) {
  6901. duplicateIndex = state.duplicates.indexOf(object);
  6902. duplicate = duplicateIndex !== -1;
  6903. }
  6904. if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
  6905. compact = false;
  6906. }
  6907. if (duplicate && state.usedDuplicates[duplicateIndex]) {
  6908. state.dump = '*ref_' + duplicateIndex;
  6909. } else {
  6910. if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
  6911. state.usedDuplicates[duplicateIndex] = true;
  6912. }
  6913. if (type === '[object Object]') {
  6914. if (block && (Object.keys(state.dump).length !== 0)) {
  6915. writeBlockMapping(state, level, state.dump, compact);
  6916. if (duplicate) {
  6917. state.dump = '&ref_' + duplicateIndex + state.dump;
  6918. }
  6919. } else {
  6920. writeFlowMapping(state, level, state.dump);
  6921. if (duplicate) {
  6922. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  6923. }
  6924. }
  6925. } else if (type === '[object Array]') {
  6926. if (block && (state.dump.length !== 0)) {
  6927. if (state.noArrayIndent && !isblockseq && level > 0) {
  6928. writeBlockSequence(state, level - 1, state.dump, compact);
  6929. } else {
  6930. writeBlockSequence(state, level, state.dump, compact);
  6931. }
  6932. if (duplicate) {
  6933. state.dump = '&ref_' + duplicateIndex + state.dump;
  6934. }
  6935. } else {
  6936. writeFlowSequence(state, level, state.dump);
  6937. if (duplicate) {
  6938. state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
  6939. }
  6940. }
  6941. } else if (type === '[object String]') {
  6942. if (state.tag !== '?') {
  6943. writeScalar(state, state.dump, level, iskey, inblock);
  6944. }
  6945. } else if (type === '[object Undefined]') {
  6946. return false;
  6947. } else {
  6948. if (state.skipInvalid) return false;
  6949. throw new exception('unacceptable kind of an object to dump ' + type);
  6950. }
  6951. if (state.tag !== null && state.tag !== '?') {
  6952. // Need to encode all characters except those allowed by the spec:
  6953. //
  6954. // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
  6955. // [36] ns-hex-digit ::= ns-dec-digit
  6956. // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
  6957. // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
  6958. // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
  6959. // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
  6960. // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
  6961. // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
  6962. //
  6963. // Also need to encode '!' because it has special meaning (end of tag prefix).
  6964. //
  6965. tagStr = encodeURI(
  6966. state.tag[0] === '!' ? state.tag.slice(1) : state.tag
  6967. ).replace(/!/g, '%21');
  6968. if (state.tag[0] === '!') {
  6969. tagStr = '!' + tagStr;
  6970. } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
  6971. tagStr = '!!' + tagStr.slice(18);
  6972. } else {
  6973. tagStr = '!<' + tagStr + '>';
  6974. }
  6975. state.dump = tagStr + ' ' + state.dump;
  6976. }
  6977. }
  6978. return true;
  6979. }
  6980. function getDuplicateReferences(object, state) {
  6981. var objects = [],
  6982. duplicatesIndexes = [],
  6983. index,
  6984. length;
  6985. inspectNode(object, objects, duplicatesIndexes);
  6986. for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
  6987. state.duplicates.push(objects[duplicatesIndexes[index]]);
  6988. }
  6989. state.usedDuplicates = new Array(length);
  6990. }
  6991. function inspectNode(object, objects, duplicatesIndexes) {
  6992. var objectKeyList,
  6993. index,
  6994. length;
  6995. if (object !== null && typeof object === 'object') {
  6996. index = objects.indexOf(object);
  6997. if (index !== -1) {
  6998. if (duplicatesIndexes.indexOf(index) === -1) {
  6999. duplicatesIndexes.push(index);
  7000. }
  7001. } else {
  7002. objects.push(object);
  7003. if (Array.isArray(object)) {
  7004. for (index = 0, length = object.length; index < length; index += 1) {
  7005. inspectNode(object[index], objects, duplicatesIndexes);
  7006. }
  7007. } else {
  7008. objectKeyList = Object.keys(object);
  7009. for (index = 0, length = objectKeyList.length; index < length; index += 1) {
  7010. inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
  7011. }
  7012. }
  7013. }
  7014. }
  7015. }
  7016. function dump$1(input, options) {
  7017. options = options || {};
  7018. var state = new State(options);
  7019. if (!state.noRefs) getDuplicateReferences(input, state);
  7020. var value = input;
  7021. if (state.replacer) {
  7022. value = state.replacer.call({ '': value }, '', value);
  7023. }
  7024. if (writeNode(state, 0, value, true, true)) return state.dump + '\n';
  7025. return '';
  7026. }
  7027. var dump_1 = dump$1;
  7028. var dumper = {
  7029. dump: dump_1
  7030. };
  7031. function renamed(from, to) {
  7032. return function () {
  7033. throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
  7034. 'Use yaml.' + to + ' instead, which is now safe by default.');
  7035. };
  7036. }
  7037. var Type = type;
  7038. var Schema = schema;
  7039. var FAILSAFE_SCHEMA = failsafe;
  7040. var JSON_SCHEMA = json;
  7041. var CORE_SCHEMA = core;
  7042. var DEFAULT_SCHEMA = _default;
  7043. var load = loader.load;
  7044. var loadAll = loader.loadAll;
  7045. var dump = dumper.dump;
  7046. var YAMLException = exception;
  7047. // Re-export all types in case user wants to create custom schema
  7048. var types = {
  7049. binary: binary,
  7050. float: float,
  7051. map: map,
  7052. null: _null,
  7053. pairs: pairs,
  7054. set: set,
  7055. timestamp: timestamp,
  7056. bool: bool,
  7057. int: int,
  7058. merge: merge,
  7059. omap: omap,
  7060. seq: seq,
  7061. str: str
  7062. };
  7063. // Removed functions from JS-YAML 3.0.x
  7064. var safeLoad = renamed('safeLoad', 'load');
  7065. var safeLoadAll = renamed('safeLoadAll', 'loadAll');
  7066. var safeDump = renamed('safeDump', 'dump');
  7067. var jsYaml = {
  7068. Type: Type,
  7069. Schema: Schema,
  7070. FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
  7071. JSON_SCHEMA: JSON_SCHEMA,
  7072. CORE_SCHEMA: CORE_SCHEMA,
  7073. DEFAULT_SCHEMA: DEFAULT_SCHEMA,
  7074. load: load,
  7075. loadAll: loadAll,
  7076. dump: dump,
  7077. YAMLException: YAMLException,
  7078. types: types,
  7079. safeLoad: safeLoad,
  7080. safeLoadAll: safeLoadAll,
  7081. safeDump: safeDump
  7082. };
  7083. // Detect either spaces or tabs but not both to properly handle tabs for indentation and spaces for alignment
  7084. const INDENT_REGEX = /^(?:( )+|\t+)/;
  7085. const INDENT_TYPE_SPACE = 'space';
  7086. const INDENT_TYPE_TAB = 'tab';
  7087. /**
  7088. Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation.
  7089. The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents.
  7090. ```
  7091. indents = {
  7092. t3: [1, 0],
  7093. t4: [1, 5],
  7094. s5: [1, 0],
  7095. s12: [1, 0],
  7096. }
  7097. ```
  7098. */
  7099. function makeIndentsMap(string, ignoreSingleSpaces) {
  7100. const indents = new Map();
  7101. // Remember the size of previous line's indentation
  7102. let previousSize = 0;
  7103. let previousIndentType;
  7104. // Indents key (ident type + size of the indents/unindents)
  7105. let key;
  7106. for (const line of string.split(/\n/g)) {
  7107. if (!line) {
  7108. // Ignore empty lines
  7109. continue;
  7110. }
  7111. let indent;
  7112. let indentType;
  7113. let weight;
  7114. let entry;
  7115. const matches = line.match(INDENT_REGEX);
  7116. if (matches === null) {
  7117. previousSize = 0;
  7118. previousIndentType = '';
  7119. } else {
  7120. indent = matches[0].length;
  7121. indentType = matches[1] ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
  7122. // Ignore single space unless it's the only indent detected to prevent common false positives
  7123. if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) {
  7124. continue;
  7125. }
  7126. if (indentType !== previousIndentType) {
  7127. previousSize = 0;
  7128. }
  7129. previousIndentType = indentType;
  7130. weight = 0;
  7131. const indentDifference = indent - previousSize;
  7132. previousSize = indent;
  7133. // Previous line have same indent?
  7134. if (indentDifference === 0) {
  7135. weight++;
  7136. // We use the key from previous loop
  7137. } else {
  7138. const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference;
  7139. key = encodeIndentsKey(indentType, absoluteIndentDifference);
  7140. }
  7141. // Update the stats
  7142. entry = indents.get(key);
  7143. entry = entry === undefined ? [1, 0] : [++entry[0], entry[1] + weight];
  7144. indents.set(key, entry);
  7145. }
  7146. }
  7147. return indents;
  7148. }
  7149. // Encode the indent type and amount as a string (e.g. 's4') for use as a compound key in the indents Map.
  7150. function encodeIndentsKey(indentType, indentAmount) {
  7151. const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't';
  7152. return typeCharacter + String(indentAmount);
  7153. }
  7154. // Extract the indent type and amount from a key of the indents Map.
  7155. function decodeIndentsKey(indentsKey) {
  7156. const keyHasTypeSpace = indentsKey[0] === 's';
  7157. const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB;
  7158. const amount = Number(indentsKey.slice(1));
  7159. return {type, amount};
  7160. }
  7161. // Return the key (e.g. 's4') from the indents Map that represents the most common indent,
  7162. // or return undefined if there are no indents.
  7163. function getMostUsedKey(indents) {
  7164. let result;
  7165. let maxUsed = 0;
  7166. let maxWeight = 0;
  7167. for (const [key, [usedCount, weight]] of indents) {
  7168. if (usedCount > maxUsed || (usedCount === maxUsed && weight > maxWeight)) {
  7169. maxUsed = usedCount;
  7170. maxWeight = weight;
  7171. result = key;
  7172. }
  7173. }
  7174. return result;
  7175. }
  7176. function makeIndentString(type, amount) {
  7177. const indentCharacter = type === INDENT_TYPE_SPACE ? ' ' : '\t';
  7178. return indentCharacter.repeat(amount);
  7179. }
  7180. function detectIndent(string) {
  7181. if (typeof string !== 'string') {
  7182. throw new TypeError('Expected a string');
  7183. }
  7184. // Identify indents while skipping single space indents to avoid common edge cases (e.g. code comments)
  7185. // If no indents are identified, run again and include all indents for comprehensive detection
  7186. let indents = makeIndentsMap(string, true);
  7187. if (indents.size === 0) {
  7188. indents = makeIndentsMap(string, false);
  7189. }
  7190. const keyOfMostUsedIndent = getMostUsedKey(indents);
  7191. let type;
  7192. let amount = 0;
  7193. let indent = '';
  7194. if (keyOfMostUsedIndent !== undefined) {
  7195. ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent));
  7196. indent = makeIndentString(type, amount);
  7197. }
  7198. return {
  7199. amount,
  7200. type,
  7201. indent,
  7202. };
  7203. }
  7204. const settingRegExp = /\/\*\s*@settings[\r\n]+?([\s\S]+?)\*\//g;
  7205. const nameRegExp = /^name:\s*(.+)$/m;
  7206. class CSSSettingsPlugin extends obsidian.Plugin {
  7207. constructor() {
  7208. super(...arguments);
  7209. this.settingsList = [];
  7210. this.errorList = [];
  7211. this.debounceTimer = 0;
  7212. }
  7213. onload() {
  7214. return __awaiter(this, void 0, void 0, function* () {
  7215. this.settingsManager = new CSSSettingsManager(this);
  7216. yield this.settingsManager.load();
  7217. this.settingsTab = new CSSSettingsTab(this.app, this);
  7218. this.addSettingTab(this.settingsTab);
  7219. this.registerView(viewType, (leaf) => new SettingsView(this, leaf));
  7220. this.addCommand({
  7221. id: "show-style-settings-leaf",
  7222. name: "Show style settings view",
  7223. callback: () => {
  7224. this.activateView();
  7225. },
  7226. });
  7227. this.registerEvent(this.app.workspace.on("css-change", () => {
  7228. this.parseCSS();
  7229. }));
  7230. this.registerEvent(this.app.workspace.on("parse-style-settings", () => {
  7231. this.parseCSS();
  7232. }));
  7233. this.lightEl = document.body.createDiv("theme-light style-settings-ref");
  7234. this.darkEl = document.body.createDiv("theme-dark style-settings-ref");
  7235. document.body.classList.add("css-settings-manager");
  7236. this.parseCSS();
  7237. });
  7238. }
  7239. getCSSVar(id) {
  7240. const light = getComputedStyle(this.lightEl).getPropertyValue(`--${id}`);
  7241. const dark = getComputedStyle(this.darkEl).getPropertyValue(`--${id}`);
  7242. const current = getComputedStyle(document.body).getPropertyValue(`--${id}`);
  7243. console.log(id, light, dark, current);
  7244. return { light, dark, current };
  7245. }
  7246. parseCSS() {
  7247. clearTimeout(this.debounceTimer);
  7248. this.settingsList = [];
  7249. this.errorList = [];
  7250. this.debounceTimer = window.setTimeout(() => {
  7251. const styleSheets = document.styleSheets;
  7252. for (let i = 0, len = styleSheets.length; i < len; i++) {
  7253. const sheet = styleSheets.item(i);
  7254. const text = sheet.ownerNode.textContent.trim();
  7255. let match = settingRegExp.exec(text);
  7256. if (match && match.length) {
  7257. do {
  7258. const nameMatch = text.match(nameRegExp);
  7259. const name = nameMatch
  7260. ? nameMatch[1]
  7261. : undefined;
  7262. try {
  7263. const str = match[1].trim();
  7264. const indent = detectIndent(str);
  7265. const settings = jsYaml.load(str.replace(/\t/g, indent.type === "space" ? indent.indent : " "), {
  7266. filename: name,
  7267. });
  7268. if (!settings.settings)
  7269. continue;
  7270. settings.settings = settings.settings.filter((setting) => setting);
  7271. if (typeof settings === "object" &&
  7272. settings.name &&
  7273. settings.id &&
  7274. settings.settings &&
  7275. settings.settings.length) {
  7276. this.settingsList.push(settings);
  7277. }
  7278. }
  7279. catch (e) {
  7280. this.errorList.push({ name, error: `${e}` });
  7281. }
  7282. } while ((match = settingRegExp.exec(text)) !== null);
  7283. }
  7284. }
  7285. this.settingsTab.settingsMarkup.setSettings(this.settingsList, this.errorList);
  7286. this.app.workspace.getLeavesOfType(viewType).forEach((leaf) => {
  7287. leaf.view.settingsMarkup.setSettings(this.settingsList, this.errorList);
  7288. });
  7289. this.settingsManager.initClasses();
  7290. }, 100);
  7291. }
  7292. onunload() {
  7293. this.lightEl.remove();
  7294. this.darkEl.remove();
  7295. this.lightEl = null;
  7296. this.darkEl = null;
  7297. document.body.classList.remove("css-settings-manager");
  7298. this.settingsManager.cleanup();
  7299. this.settingsTab.settingsMarkup.cleanup();
  7300. this.deactivateView();
  7301. }
  7302. deactivateView() {
  7303. this.app.workspace.detachLeavesOfType(viewType);
  7304. }
  7305. activateView() {
  7306. return __awaiter(this, void 0, void 0, function* () {
  7307. this.deactivateView();
  7308. const leaf = this.app.workspace.createLeafBySplit(this.app.workspace.activeLeaf, "vertical");
  7309. yield leaf.setViewState({
  7310. type: viewType,
  7311. });
  7312. leaf.view.settingsMarkup.setSettings(this.settingsList, this.errorList);
  7313. });
  7314. }
  7315. }
  7316. class SettingsMarkup {
  7317. constructor(app, plugin, containerEl, isView) {
  7318. this.cleanupFns = [];
  7319. this.settings = [];
  7320. this.errorList = [];
  7321. this.app = app;
  7322. this.plugin = plugin;
  7323. this.containerEl = containerEl;
  7324. this.isView = !!isView;
  7325. }
  7326. display() {
  7327. this.generate(this.settings);
  7328. }
  7329. cleanup() {
  7330. Array.from(this.cleanupFns).forEach((fn) => {
  7331. fn && fn();
  7332. this.cleanupFns.remove(fn);
  7333. });
  7334. }
  7335. setSettings(settings, errorList) {
  7336. this.settings = settings;
  7337. this.errorList = errorList;
  7338. this.plugin.settingsManager.setConfig(settings);
  7339. if (this.containerEl.parentNode) {
  7340. this.generate(settings);
  7341. }
  7342. }
  7343. displayErrors() {
  7344. let { containerEl, errorList } = this;
  7345. errorList.forEach((err) => {
  7346. containerEl.createDiv({ cls: "style-settings-error" }, (wrapper) => {
  7347. wrapper.createDiv({
  7348. cls: "style-settings-error-name",
  7349. text: `Error: ${err.name}`,
  7350. });
  7351. wrapper.createDiv({
  7352. cls: "style-settings-error-desc",
  7353. text: err.error,
  7354. });
  7355. });
  7356. });
  7357. }
  7358. displayEmpty() {
  7359. let { containerEl } = this;
  7360. containerEl.createDiv({ cls: "style-settings-empty" }, (wrapper) => {
  7361. wrapper.createDiv({
  7362. cls: "style-settings-empty-name",
  7363. text: "No style settings found",
  7364. });
  7365. wrapper.createDiv({ cls: "style-settings-empty-desc" }).appendChild(createFragment((frag) => {
  7366. 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. ");
  7367. frag.createEl("a", {
  7368. text: "Click here for details and examples.",
  7369. href: "https://github.com/mgmeyers/obsidian-style-settings#obsidian-style-settings-plugin",
  7370. });
  7371. }));
  7372. });
  7373. }
  7374. generate(settings) {
  7375. let { containerEl, plugin } = this;
  7376. containerEl.empty();
  7377. this.cleanup();
  7378. this.displayErrors();
  7379. if (settings.length === 0) {
  7380. return this.displayEmpty();
  7381. }
  7382. new obsidian.Setting(containerEl).then((setting) => {
  7383. // Build and import link to open the import modal
  7384. setting.controlEl.createEl("a", {
  7385. cls: "style-settings-import",
  7386. text: "Import",
  7387. href: "#",
  7388. }, (el) => {
  7389. el.addEventListener("click", (e) => {
  7390. e.preventDefault();
  7391. this.plugin.settingsManager.import();
  7392. });
  7393. });
  7394. // Build and export link to open the export modal
  7395. setting.controlEl.createEl("a", {
  7396. cls: "style-settings-export",
  7397. text: "Export",
  7398. href: "#",
  7399. }, (el) => {
  7400. el.addEventListener("click", (e) => {
  7401. e.preventDefault();
  7402. this.plugin.settingsManager.export("All settings", this.plugin.settingsManager.settings);
  7403. });
  7404. });
  7405. });
  7406. const cleanupFns = [];
  7407. settings.forEach((s) => {
  7408. const options = [
  7409. {
  7410. id: s.id,
  7411. type: "heading",
  7412. title: s.name,
  7413. level: 0,
  7414. collapsed: true,
  7415. resetFn: () => {
  7416. plugin.settingsManager.clearSection(s.id);
  7417. this.generate(this.settings);
  7418. },
  7419. },
  7420. ...s.settings,
  7421. ];
  7422. const cleanup = createSettings({
  7423. containerEl,
  7424. isView: this.isView,
  7425. sectionId: s.id,
  7426. sectionName: s.name,
  7427. settings: options,
  7428. settingsManager: plugin.settingsManager,
  7429. });
  7430. if (cleanup.length)
  7431. cleanupFns.push(...cleanup);
  7432. });
  7433. this.cleanupFns = cleanupFns;
  7434. }
  7435. }
  7436. class CSSSettingsTab extends obsidian.PluginSettingTab {
  7437. constructor(app, plugin) {
  7438. super(app, plugin);
  7439. this.settingsMarkup = new SettingsMarkup(app, plugin, this.containerEl);
  7440. }
  7441. display() {
  7442. this.settingsMarkup.display();
  7443. }
  7444. hide() {
  7445. this.settingsMarkup.cleanup();
  7446. }
  7447. }
  7448. const viewType = "style-settings";
  7449. class SettingsView extends obsidian.ItemView {
  7450. constructor(plugin, leaf) {
  7451. super(leaf);
  7452. this.plugin = plugin;
  7453. this.settingsMarkup = new SettingsMarkup(plugin.app, plugin, this.contentEl, true);
  7454. }
  7455. getViewType() {
  7456. return viewType;
  7457. }
  7458. getIcon() {
  7459. return "gear";
  7460. }
  7461. getDisplayText() {
  7462. return "Style Settings";
  7463. }
  7464. onOpen() {
  7465. return __awaiter(this, void 0, void 0, function* () {
  7466. return this.settingsMarkup.display();
  7467. });
  7468. }
  7469. onClose() {
  7470. return __awaiter(this, void 0, void 0, function* () {
  7471. return this.settingsMarkup.cleanup();
  7472. });
  7473. }
  7474. }
  7475. module.exports = CSSSettingsPlugin;