main.js 495 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209
  1. 'use strict';
  2. var obsidian = require('obsidian');
  3. function _interopNamespace(e) {
  4. if (e && e.__esModule) return e;
  5. var n = Object.create(null);
  6. if (e) {
  7. Object.keys(e).forEach(function (k) {
  8. if (k !== 'default') {
  9. var d = Object.getOwnPropertyDescriptor(e, k);
  10. Object.defineProperty(n, k, d.get ? d : {
  11. enumerable: true,
  12. get: function () { return e[k]; }
  13. });
  14. }
  15. });
  16. }
  17. n["default"] = e;
  18. return Object.freeze(n);
  19. }
  20. var obsidian__namespace = /*#__PURE__*/_interopNamespace(obsidian);
  21. function noop() { }
  22. function assign(tar, src) {
  23. // @ts-ignore
  24. for (const k in src)
  25. tar[k] = src[k];
  26. return tar;
  27. }
  28. function run(fn) {
  29. return fn();
  30. }
  31. function blank_object() {
  32. return Object.create(null);
  33. }
  34. function run_all(fns) {
  35. fns.forEach(run);
  36. }
  37. function is_function(thing) {
  38. return typeof thing === 'function';
  39. }
  40. function safe_not_equal(a, b) {
  41. return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
  42. }
  43. function is_empty(obj) {
  44. return Object.keys(obj).length === 0;
  45. }
  46. function create_slot(definition, ctx, $$scope, fn) {
  47. if (definition) {
  48. const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
  49. return definition[0](slot_ctx);
  50. }
  51. }
  52. function get_slot_context(definition, ctx, $$scope, fn) {
  53. return definition[1] && fn
  54. ? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
  55. : $$scope.ctx;
  56. }
  57. function get_slot_changes(definition, $$scope, dirty, fn) {
  58. if (definition[2] && fn) {
  59. const lets = definition[2](fn(dirty));
  60. if ($$scope.dirty === undefined) {
  61. return lets;
  62. }
  63. if (typeof lets === 'object') {
  64. const merged = [];
  65. const len = Math.max($$scope.dirty.length, lets.length);
  66. for (let i = 0; i < len; i += 1) {
  67. merged[i] = $$scope.dirty[i] | lets[i];
  68. }
  69. return merged;
  70. }
  71. return $$scope.dirty | lets;
  72. }
  73. return $$scope.dirty;
  74. }
  75. function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
  76. if (slot_changes) {
  77. const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
  78. slot.p(slot_context, slot_changes);
  79. }
  80. }
  81. function get_all_dirty_from_scope($$scope) {
  82. if ($$scope.ctx.length > 32) {
  83. const dirty = [];
  84. const length = $$scope.ctx.length / 32;
  85. for (let i = 0; i < length; i++) {
  86. dirty[i] = -1;
  87. }
  88. return dirty;
  89. }
  90. return -1;
  91. }
  92. function action_destroyer(action_result) {
  93. return action_result && is_function(action_result.destroy) ? action_result.destroy : noop;
  94. }
  95. function append(target, node) {
  96. target.appendChild(node);
  97. }
  98. function append_styles(target, style_sheet_id, styles) {
  99. const append_styles_to = get_root_for_style(target);
  100. if (!append_styles_to.getElementById(style_sheet_id)) {
  101. const style = element('style');
  102. style.id = style_sheet_id;
  103. style.textContent = styles;
  104. append_stylesheet(append_styles_to, style);
  105. }
  106. }
  107. function get_root_for_style(node) {
  108. if (!node)
  109. return document;
  110. const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
  111. if (root && root.host) {
  112. return root;
  113. }
  114. return node.ownerDocument;
  115. }
  116. function append_stylesheet(node, style) {
  117. append(node.head || node, style);
  118. }
  119. function insert(target, node, anchor) {
  120. target.insertBefore(node, anchor || null);
  121. }
  122. function detach(node) {
  123. node.parentNode.removeChild(node);
  124. }
  125. function destroy_each(iterations, detaching) {
  126. for (let i = 0; i < iterations.length; i += 1) {
  127. if (iterations[i])
  128. iterations[i].d(detaching);
  129. }
  130. }
  131. function element(name) {
  132. return document.createElement(name);
  133. }
  134. function svg_element(name) {
  135. return document.createElementNS('http://www.w3.org/2000/svg', name);
  136. }
  137. function text(data) {
  138. return document.createTextNode(data);
  139. }
  140. function space() {
  141. return text(' ');
  142. }
  143. function empty() {
  144. return text('');
  145. }
  146. function listen(node, event, handler, options) {
  147. node.addEventListener(event, handler, options);
  148. return () => node.removeEventListener(event, handler, options);
  149. }
  150. function attr(node, attribute, value) {
  151. if (value == null)
  152. node.removeAttribute(attribute);
  153. else if (node.getAttribute(attribute) !== value)
  154. node.setAttribute(attribute, value);
  155. }
  156. function set_svg_attributes(node, attributes) {
  157. for (const key in attributes) {
  158. attr(node, key, attributes[key]);
  159. }
  160. }
  161. function to_number(value) {
  162. return value === '' ? null : +value;
  163. }
  164. function children(element) {
  165. return Array.from(element.childNodes);
  166. }
  167. function set_data(text, data) {
  168. data = '' + data;
  169. if (text.wholeText !== data)
  170. text.data = data;
  171. }
  172. function set_input_value(input, value) {
  173. input.value = value == null ? '' : value;
  174. }
  175. function select_option(select, value) {
  176. for (let i = 0; i < select.options.length; i += 1) {
  177. const option = select.options[i];
  178. if (option.__value === value) {
  179. option.selected = true;
  180. return;
  181. }
  182. }
  183. select.selectedIndex = -1; // no option should be selected
  184. }
  185. function select_value(select) {
  186. const selected_option = select.querySelector(':checked') || select.options[0];
  187. return selected_option && selected_option.__value;
  188. }
  189. function toggle_class(element, name, toggle) {
  190. element.classList[toggle ? 'add' : 'remove'](name);
  191. }
  192. function custom_event(type, detail, bubbles = false) {
  193. const e = document.createEvent('CustomEvent');
  194. e.initCustomEvent(type, bubbles, false, detail);
  195. return e;
  196. }
  197. let current_component;
  198. function set_current_component(component) {
  199. current_component = component;
  200. }
  201. function get_current_component() {
  202. if (!current_component)
  203. throw new Error('Function called outside component initialization');
  204. return current_component;
  205. }
  206. function onMount(fn) {
  207. get_current_component().$$.on_mount.push(fn);
  208. }
  209. function createEventDispatcher() {
  210. const component = get_current_component();
  211. return (type, detail) => {
  212. const callbacks = component.$$.callbacks[type];
  213. if (callbacks) {
  214. // TODO are there situations where events could be dispatched
  215. // in a server (non-DOM) environment?
  216. const event = custom_event(type, detail);
  217. callbacks.slice().forEach(fn => {
  218. fn.call(component, event);
  219. });
  220. }
  221. };
  222. }
  223. // TODO figure out if we still want to support
  224. // shorthand events, or if we want to implement
  225. // a real bubbling mechanism
  226. function bubble(component, event) {
  227. const callbacks = component.$$.callbacks[event.type];
  228. if (callbacks) {
  229. // @ts-ignore
  230. callbacks.slice().forEach(fn => fn.call(this, event));
  231. }
  232. }
  233. const dirty_components = [];
  234. const binding_callbacks = [];
  235. const render_callbacks = [];
  236. const flush_callbacks = [];
  237. const resolved_promise = Promise.resolve();
  238. let update_scheduled = false;
  239. function schedule_update() {
  240. if (!update_scheduled) {
  241. update_scheduled = true;
  242. resolved_promise.then(flush);
  243. }
  244. }
  245. function add_render_callback(fn) {
  246. render_callbacks.push(fn);
  247. }
  248. function add_flush_callback(fn) {
  249. flush_callbacks.push(fn);
  250. }
  251. // flush() calls callbacks in this order:
  252. // 1. All beforeUpdate callbacks, in order: parents before children
  253. // 2. All bind:this callbacks, in reverse order: children before parents.
  254. // 3. All afterUpdate callbacks, in order: parents before children. EXCEPT
  255. // for afterUpdates called during the initial onMount, which are called in
  256. // reverse order: children before parents.
  257. // Since callbacks might update component values, which could trigger another
  258. // call to flush(), the following steps guard against this:
  259. // 1. During beforeUpdate, any updated components will be added to the
  260. // dirty_components array and will cause a reentrant call to flush(). Because
  261. // the flush index is kept outside the function, the reentrant call will pick
  262. // up where the earlier call left off and go through all dirty components. The
  263. // current_component value is saved and restored so that the reentrant call will
  264. // not interfere with the "parent" flush() call.
  265. // 2. bind:this callbacks cannot trigger new flush() calls.
  266. // 3. During afterUpdate, any updated components will NOT have their afterUpdate
  267. // callback called a second time; the seen_callbacks set, outside the flush()
  268. // function, guarantees this behavior.
  269. const seen_callbacks = new Set();
  270. let flushidx = 0; // Do *not* move this inside the flush() function
  271. function flush() {
  272. const saved_component = current_component;
  273. do {
  274. // first, call beforeUpdate functions
  275. // and update components
  276. while (flushidx < dirty_components.length) {
  277. const component = dirty_components[flushidx];
  278. flushidx++;
  279. set_current_component(component);
  280. update(component.$$);
  281. }
  282. set_current_component(null);
  283. dirty_components.length = 0;
  284. flushidx = 0;
  285. while (binding_callbacks.length)
  286. binding_callbacks.pop()();
  287. // then, once components are updated, call
  288. // afterUpdate functions. This may cause
  289. // subsequent updates...
  290. for (let i = 0; i < render_callbacks.length; i += 1) {
  291. const callback = render_callbacks[i];
  292. if (!seen_callbacks.has(callback)) {
  293. // ...so guard against infinite loops
  294. seen_callbacks.add(callback);
  295. callback();
  296. }
  297. }
  298. render_callbacks.length = 0;
  299. } while (dirty_components.length);
  300. while (flush_callbacks.length) {
  301. flush_callbacks.pop()();
  302. }
  303. update_scheduled = false;
  304. seen_callbacks.clear();
  305. set_current_component(saved_component);
  306. }
  307. function update($$) {
  308. if ($$.fragment !== null) {
  309. $$.update();
  310. run_all($$.before_update);
  311. const dirty = $$.dirty;
  312. $$.dirty = [-1];
  313. $$.fragment && $$.fragment.p($$.ctx, dirty);
  314. $$.after_update.forEach(add_render_callback);
  315. }
  316. }
  317. const outroing = new Set();
  318. let outros;
  319. function group_outros() {
  320. outros = {
  321. r: 0,
  322. c: [],
  323. p: outros // parent group
  324. };
  325. }
  326. function check_outros() {
  327. if (!outros.r) {
  328. run_all(outros.c);
  329. }
  330. outros = outros.p;
  331. }
  332. function transition_in(block, local) {
  333. if (block && block.i) {
  334. outroing.delete(block);
  335. block.i(local);
  336. }
  337. }
  338. function transition_out(block, local, detach, callback) {
  339. if (block && block.o) {
  340. if (outroing.has(block))
  341. return;
  342. outroing.add(block);
  343. outros.c.push(() => {
  344. outroing.delete(block);
  345. if (callback) {
  346. if (detach)
  347. block.d(1);
  348. callback();
  349. }
  350. });
  351. block.o(local);
  352. }
  353. }
  354. function outro_and_destroy_block(block, lookup) {
  355. transition_out(block, 1, 1, () => {
  356. lookup.delete(block.key);
  357. });
  358. }
  359. function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block, next, get_context) {
  360. let o = old_blocks.length;
  361. let n = list.length;
  362. let i = o;
  363. const old_indexes = {};
  364. while (i--)
  365. old_indexes[old_blocks[i].key] = i;
  366. const new_blocks = [];
  367. const new_lookup = new Map();
  368. const deltas = new Map();
  369. i = n;
  370. while (i--) {
  371. const child_ctx = get_context(ctx, list, i);
  372. const key = get_key(child_ctx);
  373. let block = lookup.get(key);
  374. if (!block) {
  375. block = create_each_block(key, child_ctx);
  376. block.c();
  377. }
  378. else if (dynamic) {
  379. block.p(child_ctx, dirty);
  380. }
  381. new_lookup.set(key, new_blocks[i] = block);
  382. if (key in old_indexes)
  383. deltas.set(key, Math.abs(i - old_indexes[key]));
  384. }
  385. const will_move = new Set();
  386. const did_move = new Set();
  387. function insert(block) {
  388. transition_in(block, 1);
  389. block.m(node, next);
  390. lookup.set(block.key, block);
  391. next = block.first;
  392. n--;
  393. }
  394. while (o && n) {
  395. const new_block = new_blocks[n - 1];
  396. const old_block = old_blocks[o - 1];
  397. const new_key = new_block.key;
  398. const old_key = old_block.key;
  399. if (new_block === old_block) {
  400. // do nothing
  401. next = new_block.first;
  402. o--;
  403. n--;
  404. }
  405. else if (!new_lookup.has(old_key)) {
  406. // remove old block
  407. destroy(old_block, lookup);
  408. o--;
  409. }
  410. else if (!lookup.has(new_key) || will_move.has(new_key)) {
  411. insert(new_block);
  412. }
  413. else if (did_move.has(old_key)) {
  414. o--;
  415. }
  416. else if (deltas.get(new_key) > deltas.get(old_key)) {
  417. did_move.add(new_key);
  418. insert(new_block);
  419. }
  420. else {
  421. will_move.add(old_key);
  422. o--;
  423. }
  424. }
  425. while (o--) {
  426. const old_block = old_blocks[o];
  427. if (!new_lookup.has(old_block.key))
  428. destroy(old_block, lookup);
  429. }
  430. while (n)
  431. insert(new_blocks[n - 1]);
  432. return new_blocks;
  433. }
  434. function get_spread_update(levels, updates) {
  435. const update = {};
  436. const to_null_out = {};
  437. const accounted_for = { $$scope: 1 };
  438. let i = levels.length;
  439. while (i--) {
  440. const o = levels[i];
  441. const n = updates[i];
  442. if (n) {
  443. for (const key in o) {
  444. if (!(key in n))
  445. to_null_out[key] = 1;
  446. }
  447. for (const key in n) {
  448. if (!accounted_for[key]) {
  449. update[key] = n[key];
  450. accounted_for[key] = 1;
  451. }
  452. }
  453. levels[i] = n;
  454. }
  455. else {
  456. for (const key in o) {
  457. accounted_for[key] = 1;
  458. }
  459. }
  460. }
  461. for (const key in to_null_out) {
  462. if (!(key in update))
  463. update[key] = undefined;
  464. }
  465. return update;
  466. }
  467. function bind(component, name, callback) {
  468. const index = component.$$.props[name];
  469. if (index !== undefined) {
  470. component.$$.bound[index] = callback;
  471. callback(component.$$.ctx[index]);
  472. }
  473. }
  474. function create_component(block) {
  475. block && block.c();
  476. }
  477. function mount_component(component, target, anchor, customElement) {
  478. const { fragment, on_mount, on_destroy, after_update } = component.$$;
  479. fragment && fragment.m(target, anchor);
  480. if (!customElement) {
  481. // onMount happens before the initial afterUpdate
  482. add_render_callback(() => {
  483. const new_on_destroy = on_mount.map(run).filter(is_function);
  484. if (on_destroy) {
  485. on_destroy.push(...new_on_destroy);
  486. }
  487. else {
  488. // Edge case - component was destroyed immediately,
  489. // most likely as a result of a binding initialising
  490. run_all(new_on_destroy);
  491. }
  492. component.$$.on_mount = [];
  493. });
  494. }
  495. after_update.forEach(add_render_callback);
  496. }
  497. function destroy_component(component, detaching) {
  498. const $$ = component.$$;
  499. if ($$.fragment !== null) {
  500. run_all($$.on_destroy);
  501. $$.fragment && $$.fragment.d(detaching);
  502. // TODO null out other refs, including component.$$ (but need to
  503. // preserve final state?)
  504. $$.on_destroy = $$.fragment = null;
  505. $$.ctx = [];
  506. }
  507. }
  508. function make_dirty(component, i) {
  509. if (component.$$.dirty[0] === -1) {
  510. dirty_components.push(component);
  511. schedule_update();
  512. component.$$.dirty.fill(0);
  513. }
  514. component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
  515. }
  516. function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
  517. const parent_component = current_component;
  518. set_current_component(component);
  519. const $$ = component.$$ = {
  520. fragment: null,
  521. ctx: null,
  522. // state
  523. props,
  524. update: noop,
  525. not_equal,
  526. bound: blank_object(),
  527. // lifecycle
  528. on_mount: [],
  529. on_destroy: [],
  530. on_disconnect: [],
  531. before_update: [],
  532. after_update: [],
  533. context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
  534. // everything else
  535. callbacks: blank_object(),
  536. dirty,
  537. skip_bound: false,
  538. root: options.target || parent_component.$$.root
  539. };
  540. append_styles && append_styles($$.root);
  541. let ready = false;
  542. $$.ctx = instance
  543. ? instance(component, options.props || {}, (i, ret, ...rest) => {
  544. const value = rest.length ? rest[0] : ret;
  545. if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
  546. if (!$$.skip_bound && $$.bound[i])
  547. $$.bound[i](value);
  548. if (ready)
  549. make_dirty(component, i);
  550. }
  551. return ret;
  552. })
  553. : [];
  554. $$.update();
  555. ready = true;
  556. run_all($$.before_update);
  557. // `false` as a special case of no DOM component
  558. $$.fragment = create_fragment ? create_fragment($$.ctx) : false;
  559. if (options.target) {
  560. if (options.hydrate) {
  561. const nodes = children(options.target);
  562. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  563. $$.fragment && $$.fragment.l(nodes);
  564. nodes.forEach(detach);
  565. }
  566. else {
  567. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  568. $$.fragment && $$.fragment.c();
  569. }
  570. if (options.intro)
  571. transition_in(component.$$.fragment);
  572. mount_component(component, options.target, options.anchor, options.customElement);
  573. flush();
  574. }
  575. set_current_component(parent_component);
  576. }
  577. /**
  578. * Base class for Svelte components. Used when dev=false.
  579. */
  580. class SvelteComponent {
  581. $destroy() {
  582. destroy_component(this, 1);
  583. this.$destroy = noop;
  584. }
  585. $on(type, callback) {
  586. const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
  587. callbacks.push(callback);
  588. return () => {
  589. const index = callbacks.indexOf(callback);
  590. if (index !== -1)
  591. callbacks.splice(index, 1);
  592. };
  593. }
  594. $set($$props) {
  595. if (this.$$set && !is_empty($$props)) {
  596. this.$$.skip_bound = true;
  597. this.$$set($$props);
  598. this.$$.skip_bound = false;
  599. }
  600. }
  601. }
  602. var ChoiceType;
  603. (function (ChoiceType) {
  604. ChoiceType["Capture"] = "Capture";
  605. ChoiceType["Macro"] = "Macro";
  606. ChoiceType["Multi"] = "Multi";
  607. ChoiceType["Template"] = "Template";
  608. })(ChoiceType || (ChoiceType = {}));
  609. /*!
  610. * Font Awesome Free 5.15.3 by @fontawesome - https://fontawesome.com
  611. * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
  612. */
  613. var faBars = {
  614. prefix: 'fas',
  615. iconName: 'bars',
  616. icon: [448, 512, [], "f0c9", "M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z"]
  617. };
  618. var faBolt = {
  619. prefix: 'fas',
  620. iconName: 'bolt',
  621. icon: [320, 512, [], "f0e7", "M296 160H180.6l42.6-129.8C227.2 15 215.7 0 200 0H56C44 0 33.8 8.9 32.2 20.8l-32 240C-1.7 275.2 9.5 288 24 288h118.7L96.6 482.5c-3.6 15.2 8 29.5 23.3 29.5 8.4 0 16.4-4.4 20.8-12l176-304c9.3-15.9-2.2-36-20.7-36z"]
  622. };
  623. var faChevronDown = {
  624. prefix: 'fas',
  625. iconName: 'chevron-down',
  626. icon: [448, 512, [], "f078", "M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z"]
  627. };
  628. var faCog = {
  629. prefix: 'fas',
  630. iconName: 'cog',
  631. icon: [512, 512, [], "f013", "M487.4 315.7l-42.6-24.6c4.3-23.2 4.3-47 0-70.2l42.6-24.6c4.9-2.8 7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8 110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4 6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7 85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7 94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47 0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6 30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9 15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7 8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9 42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7 43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z"]
  632. };
  633. var faTrash = {
  634. prefix: 'fas',
  635. iconName: 'trash',
  636. icon: [448, 512, [], "f1f8", "M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z"]
  637. };
  638. /* node_modules/svelte-awesome/components/svg/Path.svelte generated by Svelte v3.47.0 */
  639. function create_fragment$g(ctx) {
  640. let path;
  641. let path_key_value;
  642. let path_levels = [
  643. {
  644. key: path_key_value = "path-" + /*id*/ ctx[0]
  645. },
  646. /*data*/ ctx[1]
  647. ];
  648. let path_data = {};
  649. for (let i = 0; i < path_levels.length; i += 1) {
  650. path_data = assign(path_data, path_levels[i]);
  651. }
  652. return {
  653. c() {
  654. path = svg_element("path");
  655. set_svg_attributes(path, path_data);
  656. },
  657. m(target, anchor) {
  658. insert(target, path, anchor);
  659. },
  660. p(ctx, [dirty]) {
  661. set_svg_attributes(path, path_data = get_spread_update(path_levels, [
  662. dirty & /*id*/ 1 && path_key_value !== (path_key_value = "path-" + /*id*/ ctx[0]) && { key: path_key_value },
  663. dirty & /*data*/ 2 && /*data*/ ctx[1]
  664. ]));
  665. },
  666. i: noop,
  667. o: noop,
  668. d(detaching) {
  669. if (detaching) detach(path);
  670. }
  671. };
  672. }
  673. function instance$g($$self, $$props, $$invalidate) {
  674. let { id = '' } = $$props;
  675. let { data = {} } = $$props;
  676. $$self.$$set = $$props => {
  677. if ('id' in $$props) $$invalidate(0, id = $$props.id);
  678. if ('data' in $$props) $$invalidate(1, data = $$props.data);
  679. };
  680. return [id, data];
  681. }
  682. class Path extends SvelteComponent {
  683. constructor(options) {
  684. super();
  685. init(this, options, instance$g, create_fragment$g, safe_not_equal, { id: 0, data: 1 });
  686. }
  687. }
  688. /* node_modules/svelte-awesome/components/svg/Polygon.svelte generated by Svelte v3.47.0 */
  689. function create_fragment$f(ctx) {
  690. let polygon;
  691. let polygon_key_value;
  692. let polygon_levels = [
  693. {
  694. key: polygon_key_value = "polygon-" + /*id*/ ctx[0]
  695. },
  696. /*data*/ ctx[1]
  697. ];
  698. let polygon_data = {};
  699. for (let i = 0; i < polygon_levels.length; i += 1) {
  700. polygon_data = assign(polygon_data, polygon_levels[i]);
  701. }
  702. return {
  703. c() {
  704. polygon = svg_element("polygon");
  705. set_svg_attributes(polygon, polygon_data);
  706. },
  707. m(target, anchor) {
  708. insert(target, polygon, anchor);
  709. },
  710. p(ctx, [dirty]) {
  711. set_svg_attributes(polygon, polygon_data = get_spread_update(polygon_levels, [
  712. dirty & /*id*/ 1 && polygon_key_value !== (polygon_key_value = "polygon-" + /*id*/ ctx[0]) && { key: polygon_key_value },
  713. dirty & /*data*/ 2 && /*data*/ ctx[1]
  714. ]));
  715. },
  716. i: noop,
  717. o: noop,
  718. d(detaching) {
  719. if (detaching) detach(polygon);
  720. }
  721. };
  722. }
  723. function instance$f($$self, $$props, $$invalidate) {
  724. let { id = '' } = $$props;
  725. let { data = {} } = $$props;
  726. $$self.$$set = $$props => {
  727. if ('id' in $$props) $$invalidate(0, id = $$props.id);
  728. if ('data' in $$props) $$invalidate(1, data = $$props.data);
  729. };
  730. return [id, data];
  731. }
  732. class Polygon extends SvelteComponent {
  733. constructor(options) {
  734. super();
  735. init(this, options, instance$f, create_fragment$f, safe_not_equal, { id: 0, data: 1 });
  736. }
  737. }
  738. /* node_modules/svelte-awesome/components/svg/Raw.svelte generated by Svelte v3.47.0 */
  739. function create_fragment$e(ctx) {
  740. let g;
  741. return {
  742. c() {
  743. g = svg_element("g");
  744. },
  745. m(target, anchor) {
  746. insert(target, g, anchor);
  747. g.innerHTML = /*raw*/ ctx[0];
  748. },
  749. p(ctx, [dirty]) {
  750. if (dirty & /*raw*/ 1) g.innerHTML = /*raw*/ ctx[0]; },
  751. i: noop,
  752. o: noop,
  753. d(detaching) {
  754. if (detaching) detach(g);
  755. }
  756. };
  757. }
  758. function instance$e($$self, $$props, $$invalidate) {
  759. let cursor = 0xd4937;
  760. function getId() {
  761. cursor += 1;
  762. return `fa-${cursor.toString(16)}`;
  763. }
  764. let raw;
  765. let { data } = $$props;
  766. function getRaw(data) {
  767. if (!data || !data.raw) {
  768. return null;
  769. }
  770. let rawData = data.raw;
  771. const ids = {};
  772. rawData = rawData.replace(/\s(?:xml:)?id=["']?([^"')\s]+)/g, (match, id) => {
  773. const uniqueId = getId();
  774. ids[id] = uniqueId;
  775. return ` id="${uniqueId}"`;
  776. });
  777. rawData = rawData.replace(/#(?:([^'")\s]+)|xpointer\(id\((['"]?)([^')]+)\2\)\))/g, (match, rawId, _, pointerId) => {
  778. const id = rawId || pointerId;
  779. if (!id || !ids[id]) {
  780. return match;
  781. }
  782. return `#${ids[id]}`;
  783. });
  784. return rawData;
  785. }
  786. $$self.$$set = $$props => {
  787. if ('data' in $$props) $$invalidate(1, data = $$props.data);
  788. };
  789. $$self.$$.update = () => {
  790. if ($$self.$$.dirty & /*data*/ 2) {
  791. $$invalidate(0, raw = getRaw(data));
  792. }
  793. };
  794. return [raw, data];
  795. }
  796. class Raw extends SvelteComponent {
  797. constructor(options) {
  798. super();
  799. init(this, options, instance$e, create_fragment$e, safe_not_equal, { data: 1 });
  800. }
  801. }
  802. /* node_modules/svelte-awesome/components/svg/Svg.svelte generated by Svelte v3.47.0 */
  803. function add_css$9(target) {
  804. append_styles(target, "svelte-1dof0an", ".fa-icon.svelte-1dof0an{display:inline-block;fill:currentColor}.fa-flip-horizontal.svelte-1dof0an{transform:scale(-1, 1)}.fa-flip-vertical.svelte-1dof0an{transform:scale(1, -1)}.fa-spin.svelte-1dof0an{animation:svelte-1dof0an-fa-spin 1s 0s infinite linear}.fa-inverse.svelte-1dof0an{color:#fff}.fa-pulse.svelte-1dof0an{animation:svelte-1dof0an-fa-spin 1s infinite steps(8)}@keyframes svelte-1dof0an-fa-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}");
  805. }
  806. function create_fragment$d(ctx) {
  807. let svg;
  808. let svg_class_value;
  809. let svg_role_value;
  810. let current;
  811. const default_slot_template = /*#slots*/ ctx[13].default;
  812. const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[12], null);
  813. return {
  814. c() {
  815. svg = svg_element("svg");
  816. if (default_slot) default_slot.c();
  817. attr(svg, "version", "1.1");
  818. attr(svg, "class", svg_class_value = "fa-icon " + /*className*/ ctx[0] + " svelte-1dof0an");
  819. attr(svg, "x", /*x*/ ctx[8]);
  820. attr(svg, "y", /*y*/ ctx[9]);
  821. attr(svg, "width", /*width*/ ctx[1]);
  822. attr(svg, "height", /*height*/ ctx[2]);
  823. attr(svg, "aria-label", /*label*/ ctx[11]);
  824. attr(svg, "role", svg_role_value = /*label*/ ctx[11] ? 'img' : 'presentation');
  825. attr(svg, "viewBox", /*box*/ ctx[3]);
  826. attr(svg, "style", /*style*/ ctx[10]);
  827. toggle_class(svg, "fa-spin", /*spin*/ ctx[4]);
  828. toggle_class(svg, "fa-pulse", /*pulse*/ ctx[6]);
  829. toggle_class(svg, "fa-inverse", /*inverse*/ ctx[5]);
  830. toggle_class(svg, "fa-flip-horizontal", /*flip*/ ctx[7] === 'horizontal');
  831. toggle_class(svg, "fa-flip-vertical", /*flip*/ ctx[7] === 'vertical');
  832. },
  833. m(target, anchor) {
  834. insert(target, svg, anchor);
  835. if (default_slot) {
  836. default_slot.m(svg, null);
  837. }
  838. current = true;
  839. },
  840. p(ctx, [dirty]) {
  841. if (default_slot) {
  842. if (default_slot.p && (!current || dirty & /*$$scope*/ 4096)) {
  843. update_slot_base(
  844. default_slot,
  845. default_slot_template,
  846. ctx,
  847. /*$$scope*/ ctx[12],
  848. !current
  849. ? get_all_dirty_from_scope(/*$$scope*/ ctx[12])
  850. : get_slot_changes(default_slot_template, /*$$scope*/ ctx[12], dirty, null),
  851. null
  852. );
  853. }
  854. }
  855. if (!current || dirty & /*className*/ 1 && svg_class_value !== (svg_class_value = "fa-icon " + /*className*/ ctx[0] + " svelte-1dof0an")) {
  856. attr(svg, "class", svg_class_value);
  857. }
  858. if (!current || dirty & /*x*/ 256) {
  859. attr(svg, "x", /*x*/ ctx[8]);
  860. }
  861. if (!current || dirty & /*y*/ 512) {
  862. attr(svg, "y", /*y*/ ctx[9]);
  863. }
  864. if (!current || dirty & /*width*/ 2) {
  865. attr(svg, "width", /*width*/ ctx[1]);
  866. }
  867. if (!current || dirty & /*height*/ 4) {
  868. attr(svg, "height", /*height*/ ctx[2]);
  869. }
  870. if (!current || dirty & /*label*/ 2048) {
  871. attr(svg, "aria-label", /*label*/ ctx[11]);
  872. }
  873. if (!current || dirty & /*label*/ 2048 && svg_role_value !== (svg_role_value = /*label*/ ctx[11] ? 'img' : 'presentation')) {
  874. attr(svg, "role", svg_role_value);
  875. }
  876. if (!current || dirty & /*box*/ 8) {
  877. attr(svg, "viewBox", /*box*/ ctx[3]);
  878. }
  879. if (!current || dirty & /*style*/ 1024) {
  880. attr(svg, "style", /*style*/ ctx[10]);
  881. }
  882. if (dirty & /*className, spin*/ 17) {
  883. toggle_class(svg, "fa-spin", /*spin*/ ctx[4]);
  884. }
  885. if (dirty & /*className, pulse*/ 65) {
  886. toggle_class(svg, "fa-pulse", /*pulse*/ ctx[6]);
  887. }
  888. if (dirty & /*className, inverse*/ 33) {
  889. toggle_class(svg, "fa-inverse", /*inverse*/ ctx[5]);
  890. }
  891. if (dirty & /*className, flip*/ 129) {
  892. toggle_class(svg, "fa-flip-horizontal", /*flip*/ ctx[7] === 'horizontal');
  893. }
  894. if (dirty & /*className, flip*/ 129) {
  895. toggle_class(svg, "fa-flip-vertical", /*flip*/ ctx[7] === 'vertical');
  896. }
  897. },
  898. i(local) {
  899. if (current) return;
  900. transition_in(default_slot, local);
  901. current = true;
  902. },
  903. o(local) {
  904. transition_out(default_slot, local);
  905. current = false;
  906. },
  907. d(detaching) {
  908. if (detaching) detach(svg);
  909. if (default_slot) default_slot.d(detaching);
  910. }
  911. };
  912. }
  913. function instance$d($$self, $$props, $$invalidate) {
  914. let { $$slots: slots = {}, $$scope } = $$props;
  915. let { class: className } = $$props;
  916. let { width } = $$props;
  917. let { height } = $$props;
  918. let { box } = $$props;
  919. let { spin = false } = $$props;
  920. let { inverse = false } = $$props;
  921. let { pulse = false } = $$props;
  922. let { flip = null } = $$props;
  923. let { x = undefined } = $$props;
  924. let { y = undefined } = $$props;
  925. let { style = undefined } = $$props;
  926. let { label = undefined } = $$props;
  927. $$self.$$set = $$props => {
  928. if ('class' in $$props) $$invalidate(0, className = $$props.class);
  929. if ('width' in $$props) $$invalidate(1, width = $$props.width);
  930. if ('height' in $$props) $$invalidate(2, height = $$props.height);
  931. if ('box' in $$props) $$invalidate(3, box = $$props.box);
  932. if ('spin' in $$props) $$invalidate(4, spin = $$props.spin);
  933. if ('inverse' in $$props) $$invalidate(5, inverse = $$props.inverse);
  934. if ('pulse' in $$props) $$invalidate(6, pulse = $$props.pulse);
  935. if ('flip' in $$props) $$invalidate(7, flip = $$props.flip);
  936. if ('x' in $$props) $$invalidate(8, x = $$props.x);
  937. if ('y' in $$props) $$invalidate(9, y = $$props.y);
  938. if ('style' in $$props) $$invalidate(10, style = $$props.style);
  939. if ('label' in $$props) $$invalidate(11, label = $$props.label);
  940. if ('$$scope' in $$props) $$invalidate(12, $$scope = $$props.$$scope);
  941. };
  942. return [
  943. className,
  944. width,
  945. height,
  946. box,
  947. spin,
  948. inverse,
  949. pulse,
  950. flip,
  951. x,
  952. y,
  953. style,
  954. label,
  955. $$scope,
  956. slots
  957. ];
  958. }
  959. class Svg extends SvelteComponent {
  960. constructor(options) {
  961. super();
  962. init(
  963. this,
  964. options,
  965. instance$d,
  966. create_fragment$d,
  967. safe_not_equal,
  968. {
  969. class: 0,
  970. width: 1,
  971. height: 2,
  972. box: 3,
  973. spin: 4,
  974. inverse: 5,
  975. pulse: 6,
  976. flip: 7,
  977. x: 8,
  978. y: 9,
  979. style: 10,
  980. label: 11
  981. },
  982. add_css$9
  983. );
  984. }
  985. }
  986. /* node_modules/svelte-awesome/components/Icon.svelte generated by Svelte v3.47.0 */
  987. function get_each_context$3(ctx, list, i) {
  988. const child_ctx = ctx.slice();
  989. child_ctx[24] = list[i];
  990. child_ctx[26] = i;
  991. return child_ctx;
  992. }
  993. function get_each_context_1(ctx, list, i) {
  994. const child_ctx = ctx.slice();
  995. child_ctx[27] = list[i];
  996. child_ctx[26] = i;
  997. return child_ctx;
  998. }
  999. // (4:4) {#if self}
  1000. function create_if_block$4(ctx) {
  1001. let t0;
  1002. let t1;
  1003. let if_block2_anchor;
  1004. let current;
  1005. let if_block0 = /*self*/ ctx[0].paths && create_if_block_3(ctx);
  1006. let if_block1 = /*self*/ ctx[0].polygons && create_if_block_2$1(ctx);
  1007. let if_block2 = /*self*/ ctx[0].raw && create_if_block_1$2(ctx);
  1008. return {
  1009. c() {
  1010. if (if_block0) if_block0.c();
  1011. t0 = space();
  1012. if (if_block1) if_block1.c();
  1013. t1 = space();
  1014. if (if_block2) if_block2.c();
  1015. if_block2_anchor = empty();
  1016. },
  1017. m(target, anchor) {
  1018. if (if_block0) if_block0.m(target, anchor);
  1019. insert(target, t0, anchor);
  1020. if (if_block1) if_block1.m(target, anchor);
  1021. insert(target, t1, anchor);
  1022. if (if_block2) if_block2.m(target, anchor);
  1023. insert(target, if_block2_anchor, anchor);
  1024. current = true;
  1025. },
  1026. p(ctx, dirty) {
  1027. if (/*self*/ ctx[0].paths) {
  1028. if (if_block0) {
  1029. if_block0.p(ctx, dirty);
  1030. if (dirty & /*self*/ 1) {
  1031. transition_in(if_block0, 1);
  1032. }
  1033. } else {
  1034. if_block0 = create_if_block_3(ctx);
  1035. if_block0.c();
  1036. transition_in(if_block0, 1);
  1037. if_block0.m(t0.parentNode, t0);
  1038. }
  1039. } else if (if_block0) {
  1040. group_outros();
  1041. transition_out(if_block0, 1, 1, () => {
  1042. if_block0 = null;
  1043. });
  1044. check_outros();
  1045. }
  1046. if (/*self*/ ctx[0].polygons) {
  1047. if (if_block1) {
  1048. if_block1.p(ctx, dirty);
  1049. if (dirty & /*self*/ 1) {
  1050. transition_in(if_block1, 1);
  1051. }
  1052. } else {
  1053. if_block1 = create_if_block_2$1(ctx);
  1054. if_block1.c();
  1055. transition_in(if_block1, 1);
  1056. if_block1.m(t1.parentNode, t1);
  1057. }
  1058. } else if (if_block1) {
  1059. group_outros();
  1060. transition_out(if_block1, 1, 1, () => {
  1061. if_block1 = null;
  1062. });
  1063. check_outros();
  1064. }
  1065. if (/*self*/ ctx[0].raw) {
  1066. if (if_block2) {
  1067. if_block2.p(ctx, dirty);
  1068. if (dirty & /*self*/ 1) {
  1069. transition_in(if_block2, 1);
  1070. }
  1071. } else {
  1072. if_block2 = create_if_block_1$2(ctx);
  1073. if_block2.c();
  1074. transition_in(if_block2, 1);
  1075. if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
  1076. }
  1077. } else if (if_block2) {
  1078. group_outros();
  1079. transition_out(if_block2, 1, 1, () => {
  1080. if_block2 = null;
  1081. });
  1082. check_outros();
  1083. }
  1084. },
  1085. i(local) {
  1086. if (current) return;
  1087. transition_in(if_block0);
  1088. transition_in(if_block1);
  1089. transition_in(if_block2);
  1090. current = true;
  1091. },
  1092. o(local) {
  1093. transition_out(if_block0);
  1094. transition_out(if_block1);
  1095. transition_out(if_block2);
  1096. current = false;
  1097. },
  1098. d(detaching) {
  1099. if (if_block0) if_block0.d(detaching);
  1100. if (detaching) detach(t0);
  1101. if (if_block1) if_block1.d(detaching);
  1102. if (detaching) detach(t1);
  1103. if (if_block2) if_block2.d(detaching);
  1104. if (detaching) detach(if_block2_anchor);
  1105. }
  1106. };
  1107. }
  1108. // (5:6) {#if self.paths}
  1109. function create_if_block_3(ctx) {
  1110. let each_1_anchor;
  1111. let current;
  1112. let each_value_1 = /*self*/ ctx[0].paths;
  1113. let each_blocks = [];
  1114. for (let i = 0; i < each_value_1.length; i += 1) {
  1115. each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
  1116. }
  1117. const out = i => transition_out(each_blocks[i], 1, 1, () => {
  1118. each_blocks[i] = null;
  1119. });
  1120. return {
  1121. c() {
  1122. for (let i = 0; i < each_blocks.length; i += 1) {
  1123. each_blocks[i].c();
  1124. }
  1125. each_1_anchor = empty();
  1126. },
  1127. m(target, anchor) {
  1128. for (let i = 0; i < each_blocks.length; i += 1) {
  1129. each_blocks[i].m(target, anchor);
  1130. }
  1131. insert(target, each_1_anchor, anchor);
  1132. current = true;
  1133. },
  1134. p(ctx, dirty) {
  1135. if (dirty & /*self*/ 1) {
  1136. each_value_1 = /*self*/ ctx[0].paths;
  1137. let i;
  1138. for (i = 0; i < each_value_1.length; i += 1) {
  1139. const child_ctx = get_each_context_1(ctx, each_value_1, i);
  1140. if (each_blocks[i]) {
  1141. each_blocks[i].p(child_ctx, dirty);
  1142. transition_in(each_blocks[i], 1);
  1143. } else {
  1144. each_blocks[i] = create_each_block_1(child_ctx);
  1145. each_blocks[i].c();
  1146. transition_in(each_blocks[i], 1);
  1147. each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
  1148. }
  1149. }
  1150. group_outros();
  1151. for (i = each_value_1.length; i < each_blocks.length; i += 1) {
  1152. out(i);
  1153. }
  1154. check_outros();
  1155. }
  1156. },
  1157. i(local) {
  1158. if (current) return;
  1159. for (let i = 0; i < each_value_1.length; i += 1) {
  1160. transition_in(each_blocks[i]);
  1161. }
  1162. current = true;
  1163. },
  1164. o(local) {
  1165. each_blocks = each_blocks.filter(Boolean);
  1166. for (let i = 0; i < each_blocks.length; i += 1) {
  1167. transition_out(each_blocks[i]);
  1168. }
  1169. current = false;
  1170. },
  1171. d(detaching) {
  1172. destroy_each(each_blocks, detaching);
  1173. if (detaching) detach(each_1_anchor);
  1174. }
  1175. };
  1176. }
  1177. // (6:8) {#each self.paths as path, i}
  1178. function create_each_block_1(ctx) {
  1179. let path;
  1180. let current;
  1181. path = new Path({
  1182. props: {
  1183. id: /*i*/ ctx[26],
  1184. data: /*path*/ ctx[27]
  1185. }
  1186. });
  1187. return {
  1188. c() {
  1189. create_component(path.$$.fragment);
  1190. },
  1191. m(target, anchor) {
  1192. mount_component(path, target, anchor);
  1193. current = true;
  1194. },
  1195. p(ctx, dirty) {
  1196. const path_changes = {};
  1197. if (dirty & /*self*/ 1) path_changes.data = /*path*/ ctx[27];
  1198. path.$set(path_changes);
  1199. },
  1200. i(local) {
  1201. if (current) return;
  1202. transition_in(path.$$.fragment, local);
  1203. current = true;
  1204. },
  1205. o(local) {
  1206. transition_out(path.$$.fragment, local);
  1207. current = false;
  1208. },
  1209. d(detaching) {
  1210. destroy_component(path, detaching);
  1211. }
  1212. };
  1213. }
  1214. // (10:6) {#if self.polygons}
  1215. function create_if_block_2$1(ctx) {
  1216. let each_1_anchor;
  1217. let current;
  1218. let each_value = /*self*/ ctx[0].polygons;
  1219. let each_blocks = [];
  1220. for (let i = 0; i < each_value.length; i += 1) {
  1221. each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
  1222. }
  1223. const out = i => transition_out(each_blocks[i], 1, 1, () => {
  1224. each_blocks[i] = null;
  1225. });
  1226. return {
  1227. c() {
  1228. for (let i = 0; i < each_blocks.length; i += 1) {
  1229. each_blocks[i].c();
  1230. }
  1231. each_1_anchor = empty();
  1232. },
  1233. m(target, anchor) {
  1234. for (let i = 0; i < each_blocks.length; i += 1) {
  1235. each_blocks[i].m(target, anchor);
  1236. }
  1237. insert(target, each_1_anchor, anchor);
  1238. current = true;
  1239. },
  1240. p(ctx, dirty) {
  1241. if (dirty & /*self*/ 1) {
  1242. each_value = /*self*/ ctx[0].polygons;
  1243. let i;
  1244. for (i = 0; i < each_value.length; i += 1) {
  1245. const child_ctx = get_each_context$3(ctx, each_value, i);
  1246. if (each_blocks[i]) {
  1247. each_blocks[i].p(child_ctx, dirty);
  1248. transition_in(each_blocks[i], 1);
  1249. } else {
  1250. each_blocks[i] = create_each_block$3(child_ctx);
  1251. each_blocks[i].c();
  1252. transition_in(each_blocks[i], 1);
  1253. each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
  1254. }
  1255. }
  1256. group_outros();
  1257. for (i = each_value.length; i < each_blocks.length; i += 1) {
  1258. out(i);
  1259. }
  1260. check_outros();
  1261. }
  1262. },
  1263. i(local) {
  1264. if (current) return;
  1265. for (let i = 0; i < each_value.length; i += 1) {
  1266. transition_in(each_blocks[i]);
  1267. }
  1268. current = true;
  1269. },
  1270. o(local) {
  1271. each_blocks = each_blocks.filter(Boolean);
  1272. for (let i = 0; i < each_blocks.length; i += 1) {
  1273. transition_out(each_blocks[i]);
  1274. }
  1275. current = false;
  1276. },
  1277. d(detaching) {
  1278. destroy_each(each_blocks, detaching);
  1279. if (detaching) detach(each_1_anchor);
  1280. }
  1281. };
  1282. }
  1283. // (11:8) {#each self.polygons as polygon, i}
  1284. function create_each_block$3(ctx) {
  1285. let polygon;
  1286. let current;
  1287. polygon = new Polygon({
  1288. props: {
  1289. id: /*i*/ ctx[26],
  1290. data: /*polygon*/ ctx[24]
  1291. }
  1292. });
  1293. return {
  1294. c() {
  1295. create_component(polygon.$$.fragment);
  1296. },
  1297. m(target, anchor) {
  1298. mount_component(polygon, target, anchor);
  1299. current = true;
  1300. },
  1301. p(ctx, dirty) {
  1302. const polygon_changes = {};
  1303. if (dirty & /*self*/ 1) polygon_changes.data = /*polygon*/ ctx[24];
  1304. polygon.$set(polygon_changes);
  1305. },
  1306. i(local) {
  1307. if (current) return;
  1308. transition_in(polygon.$$.fragment, local);
  1309. current = true;
  1310. },
  1311. o(local) {
  1312. transition_out(polygon.$$.fragment, local);
  1313. current = false;
  1314. },
  1315. d(detaching) {
  1316. destroy_component(polygon, detaching);
  1317. }
  1318. };
  1319. }
  1320. // (15:6) {#if self.raw}
  1321. function create_if_block_1$2(ctx) {
  1322. let raw;
  1323. let updating_data;
  1324. let current;
  1325. function raw_data_binding(value) {
  1326. /*raw_data_binding*/ ctx[15](value);
  1327. }
  1328. let raw_props = {};
  1329. if (/*self*/ ctx[0] !== void 0) {
  1330. raw_props.data = /*self*/ ctx[0];
  1331. }
  1332. raw = new Raw({ props: raw_props });
  1333. binding_callbacks.push(() => bind(raw, 'data', raw_data_binding));
  1334. return {
  1335. c() {
  1336. create_component(raw.$$.fragment);
  1337. },
  1338. m(target, anchor) {
  1339. mount_component(raw, target, anchor);
  1340. current = true;
  1341. },
  1342. p(ctx, dirty) {
  1343. const raw_changes = {};
  1344. if (!updating_data && dirty & /*self*/ 1) {
  1345. updating_data = true;
  1346. raw_changes.data = /*self*/ ctx[0];
  1347. add_flush_callback(() => updating_data = false);
  1348. }
  1349. raw.$set(raw_changes);
  1350. },
  1351. i(local) {
  1352. if (current) return;
  1353. transition_in(raw.$$.fragment, local);
  1354. current = true;
  1355. },
  1356. o(local) {
  1357. transition_out(raw.$$.fragment, local);
  1358. current = false;
  1359. },
  1360. d(detaching) {
  1361. destroy_component(raw, detaching);
  1362. }
  1363. };
  1364. }
  1365. // (3:8)
  1366. function fallback_block(ctx) {
  1367. let if_block_anchor;
  1368. let current;
  1369. let if_block = /*self*/ ctx[0] && create_if_block$4(ctx);
  1370. return {
  1371. c() {
  1372. if (if_block) if_block.c();
  1373. if_block_anchor = empty();
  1374. },
  1375. m(target, anchor) {
  1376. if (if_block) if_block.m(target, anchor);
  1377. insert(target, if_block_anchor, anchor);
  1378. current = true;
  1379. },
  1380. p(ctx, dirty) {
  1381. if (/*self*/ ctx[0]) {
  1382. if (if_block) {
  1383. if_block.p(ctx, dirty);
  1384. if (dirty & /*self*/ 1) {
  1385. transition_in(if_block, 1);
  1386. }
  1387. } else {
  1388. if_block = create_if_block$4(ctx);
  1389. if_block.c();
  1390. transition_in(if_block, 1);
  1391. if_block.m(if_block_anchor.parentNode, if_block_anchor);
  1392. }
  1393. } else if (if_block) {
  1394. group_outros();
  1395. transition_out(if_block, 1, 1, () => {
  1396. if_block = null;
  1397. });
  1398. check_outros();
  1399. }
  1400. },
  1401. i(local) {
  1402. if (current) return;
  1403. transition_in(if_block);
  1404. current = true;
  1405. },
  1406. o(local) {
  1407. transition_out(if_block);
  1408. current = false;
  1409. },
  1410. d(detaching) {
  1411. if (if_block) if_block.d(detaching);
  1412. if (detaching) detach(if_block_anchor);
  1413. }
  1414. };
  1415. }
  1416. // (1:0) <Svg label={label} width={width} height={height} box={box} style={combinedStyle} spin={spin} flip={flip} inverse={inverse} pulse={pulse} class={className}>
  1417. function create_default_slot(ctx) {
  1418. let current;
  1419. const default_slot_template = /*#slots*/ ctx[14].default;
  1420. const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[16], null);
  1421. const default_slot_or_fallback = default_slot || fallback_block(ctx);
  1422. return {
  1423. c() {
  1424. if (default_slot_or_fallback) default_slot_or_fallback.c();
  1425. },
  1426. m(target, anchor) {
  1427. if (default_slot_or_fallback) {
  1428. default_slot_or_fallback.m(target, anchor);
  1429. }
  1430. current = true;
  1431. },
  1432. p(ctx, dirty) {
  1433. if (default_slot) {
  1434. if (default_slot.p && (!current || dirty & /*$$scope*/ 65536)) {
  1435. update_slot_base(
  1436. default_slot,
  1437. default_slot_template,
  1438. ctx,
  1439. /*$$scope*/ ctx[16],
  1440. !current
  1441. ? get_all_dirty_from_scope(/*$$scope*/ ctx[16])
  1442. : get_slot_changes(default_slot_template, /*$$scope*/ ctx[16], dirty, null),
  1443. null
  1444. );
  1445. }
  1446. } else {
  1447. if (default_slot_or_fallback && default_slot_or_fallback.p && (!current || dirty & /*self*/ 1)) {
  1448. default_slot_or_fallback.p(ctx, !current ? -1 : dirty);
  1449. }
  1450. }
  1451. },
  1452. i(local) {
  1453. if (current) return;
  1454. transition_in(default_slot_or_fallback, local);
  1455. current = true;
  1456. },
  1457. o(local) {
  1458. transition_out(default_slot_or_fallback, local);
  1459. current = false;
  1460. },
  1461. d(detaching) {
  1462. if (default_slot_or_fallback) default_slot_or_fallback.d(detaching);
  1463. }
  1464. };
  1465. }
  1466. function create_fragment$c(ctx) {
  1467. let svg;
  1468. let current;
  1469. svg = new Svg({
  1470. props: {
  1471. label: /*label*/ ctx[6],
  1472. width: /*width*/ ctx[7],
  1473. height: /*height*/ ctx[8],
  1474. box: /*box*/ ctx[10],
  1475. style: /*combinedStyle*/ ctx[9],
  1476. spin: /*spin*/ ctx[2],
  1477. flip: /*flip*/ ctx[5],
  1478. inverse: /*inverse*/ ctx[3],
  1479. pulse: /*pulse*/ ctx[4],
  1480. class: /*className*/ ctx[1],
  1481. $$slots: { default: [create_default_slot] },
  1482. $$scope: { ctx }
  1483. }
  1484. });
  1485. return {
  1486. c() {
  1487. create_component(svg.$$.fragment);
  1488. },
  1489. m(target, anchor) {
  1490. mount_component(svg, target, anchor);
  1491. current = true;
  1492. },
  1493. p(ctx, [dirty]) {
  1494. const svg_changes = {};
  1495. if (dirty & /*label*/ 64) svg_changes.label = /*label*/ ctx[6];
  1496. if (dirty & /*width*/ 128) svg_changes.width = /*width*/ ctx[7];
  1497. if (dirty & /*height*/ 256) svg_changes.height = /*height*/ ctx[8];
  1498. if (dirty & /*box*/ 1024) svg_changes.box = /*box*/ ctx[10];
  1499. if (dirty & /*combinedStyle*/ 512) svg_changes.style = /*combinedStyle*/ ctx[9];
  1500. if (dirty & /*spin*/ 4) svg_changes.spin = /*spin*/ ctx[2];
  1501. if (dirty & /*flip*/ 32) svg_changes.flip = /*flip*/ ctx[5];
  1502. if (dirty & /*inverse*/ 8) svg_changes.inverse = /*inverse*/ ctx[3];
  1503. if (dirty & /*pulse*/ 16) svg_changes.pulse = /*pulse*/ ctx[4];
  1504. if (dirty & /*className*/ 2) svg_changes.class = /*className*/ ctx[1];
  1505. if (dirty & /*$$scope, self*/ 65537) {
  1506. svg_changes.$$scope = { dirty, ctx };
  1507. }
  1508. svg.$set(svg_changes);
  1509. },
  1510. i(local) {
  1511. if (current) return;
  1512. transition_in(svg.$$.fragment, local);
  1513. current = true;
  1514. },
  1515. o(local) {
  1516. transition_out(svg.$$.fragment, local);
  1517. current = false;
  1518. },
  1519. d(detaching) {
  1520. destroy_component(svg, detaching);
  1521. }
  1522. };
  1523. }
  1524. let outerScale = 1;
  1525. function normaliseData(data) {
  1526. if ('iconName' in data && 'icon' in data) {
  1527. let normalisedData = {};
  1528. let faIcon = data.icon;
  1529. let name = data.iconName;
  1530. let width = faIcon[0];
  1531. let height = faIcon[1];
  1532. let paths = faIcon[4];
  1533. let iconData = { width, height, paths: [{ d: paths }] };
  1534. normalisedData[name] = iconData;
  1535. return normalisedData;
  1536. }
  1537. return data;
  1538. }
  1539. function instance$c($$self, $$props, $$invalidate) {
  1540. let { $$slots: slots = {}, $$scope } = $$props;
  1541. let { class: className = "" } = $$props;
  1542. let { data } = $$props;
  1543. let { scale = 1 } = $$props;
  1544. let { spin = false } = $$props;
  1545. let { inverse = false } = $$props;
  1546. let { pulse = false } = $$props;
  1547. let { flip = null } = $$props;
  1548. let { label = null } = $$props;
  1549. let { self = null } = $$props;
  1550. let { style = null } = $$props;
  1551. let width;
  1552. let height;
  1553. let combinedStyle;
  1554. let box;
  1555. function init() {
  1556. if (typeof data === 'undefined') {
  1557. return;
  1558. }
  1559. const normalisedData = normaliseData(data);
  1560. const [name] = Object.keys(normalisedData);
  1561. const icon = normalisedData[name];
  1562. if (!icon.paths) {
  1563. icon.paths = [];
  1564. }
  1565. if (icon.d) {
  1566. icon.paths.push({ d: icon.d });
  1567. }
  1568. if (!icon.polygons) {
  1569. icon.polygons = [];
  1570. }
  1571. if (icon.points) {
  1572. icon.polygons.push({ points: icon.points });
  1573. }
  1574. $$invalidate(0, self = icon);
  1575. }
  1576. function normalisedScale() {
  1577. let numScale = 1;
  1578. if (typeof scale !== 'undefined') {
  1579. numScale = Number(scale);
  1580. }
  1581. if (isNaN(numScale) || numScale <= 0) {
  1582. // eslint-disable-line no-restricted-globals
  1583. console.warn('Invalid prop: prop "scale" should be a number over 0.'); // eslint-disable-line no-console
  1584. return outerScale;
  1585. }
  1586. return numScale * outerScale;
  1587. }
  1588. function calculateBox() {
  1589. if (self) {
  1590. return `0 0 ${self.width} ${self.height}`;
  1591. }
  1592. return `0 0 ${width} ${height}`;
  1593. }
  1594. function calculateRatio() {
  1595. if (!self) {
  1596. return 1;
  1597. }
  1598. return Math.max(self.width, self.height) / 16;
  1599. }
  1600. function calculateWidth() {
  1601. if (self) {
  1602. return self.width / calculateRatio() * normalisedScale();
  1603. }
  1604. return 0;
  1605. }
  1606. function calculateHeight() {
  1607. if (self) {
  1608. return self.height / calculateRatio() * normalisedScale();
  1609. }
  1610. return 0;
  1611. }
  1612. function calculateStyle() {
  1613. let combined = "";
  1614. if (style !== null) {
  1615. combined += style;
  1616. }
  1617. let size = normalisedScale();
  1618. if (size === 1) {
  1619. if (combined.length === 0) {
  1620. return undefined;
  1621. }
  1622. return combined;
  1623. }
  1624. if (combined !== "" && !combined.endsWith(';')) {
  1625. combined += '; ';
  1626. }
  1627. return `${combined}font-size: ${size}em`;
  1628. }
  1629. function raw_data_binding(value) {
  1630. self = value;
  1631. $$invalidate(0, self);
  1632. }
  1633. $$self.$$set = $$props => {
  1634. if ('class' in $$props) $$invalidate(1, className = $$props.class);
  1635. if ('data' in $$props) $$invalidate(11, data = $$props.data);
  1636. if ('scale' in $$props) $$invalidate(12, scale = $$props.scale);
  1637. if ('spin' in $$props) $$invalidate(2, spin = $$props.spin);
  1638. if ('inverse' in $$props) $$invalidate(3, inverse = $$props.inverse);
  1639. if ('pulse' in $$props) $$invalidate(4, pulse = $$props.pulse);
  1640. if ('flip' in $$props) $$invalidate(5, flip = $$props.flip);
  1641. if ('label' in $$props) $$invalidate(6, label = $$props.label);
  1642. if ('self' in $$props) $$invalidate(0, self = $$props.self);
  1643. if ('style' in $$props) $$invalidate(13, style = $$props.style);
  1644. if ('$$scope' in $$props) $$invalidate(16, $$scope = $$props.$$scope);
  1645. };
  1646. $$self.$$.update = () => {
  1647. if ($$self.$$.dirty & /*data, style, scale*/ 14336) {
  1648. {
  1649. init();
  1650. $$invalidate(7, width = calculateWidth());
  1651. $$invalidate(8, height = calculateHeight());
  1652. $$invalidate(9, combinedStyle = calculateStyle());
  1653. $$invalidate(10, box = calculateBox());
  1654. }
  1655. }
  1656. };
  1657. return [
  1658. self,
  1659. className,
  1660. spin,
  1661. inverse,
  1662. pulse,
  1663. flip,
  1664. label,
  1665. width,
  1666. height,
  1667. combinedStyle,
  1668. box,
  1669. data,
  1670. scale,
  1671. style,
  1672. slots,
  1673. raw_data_binding,
  1674. $$scope
  1675. ];
  1676. }
  1677. class Icon extends SvelteComponent {
  1678. constructor(options) {
  1679. super();
  1680. init(this, options, instance$c, create_fragment$c, safe_not_equal, {
  1681. class: 1,
  1682. data: 11,
  1683. scale: 12,
  1684. spin: 2,
  1685. inverse: 3,
  1686. pulse: 4,
  1687. flip: 5,
  1688. label: 6,
  1689. self: 0,
  1690. style: 13
  1691. });
  1692. }
  1693. }
  1694. /* src/gui/choiceList/ChoiceItemRightButtons.svelte generated by Svelte v3.47.0 */
  1695. function add_css$8(target) {
  1696. append_styles(target, "svelte-a47k80", ".rightButtonsContainer.svelte-a47k80{display:flex;align-items:center;gap:8px}.clickable.svelte-a47k80:hover{cursor:pointer}.alignIconInDivInMiddle.svelte-a47k80{display:flex;align-items:center}");
  1697. }
  1698. // (24:4) {#if showConfigureButton}
  1699. function create_if_block$3(ctx) {
  1700. let div;
  1701. let icon;
  1702. let div_aria_label_value;
  1703. let current;
  1704. let mounted;
  1705. let dispose;
  1706. icon = new Icon({ props: { data: faCog } });
  1707. return {
  1708. c() {
  1709. div = element("div");
  1710. create_component(icon.$$.fragment);
  1711. attr(div, "class", "alignIconInDivInMiddle clickable svelte-a47k80");
  1712. attr(div, "aria-label", div_aria_label_value = `Configure${/*choiceName*/ ctx[3] ? " " + /*choiceName*/ ctx[3] : ""}`);
  1713. },
  1714. m(target, anchor) {
  1715. insert(target, div, anchor);
  1716. mount_component(icon, div, null);
  1717. current = true;
  1718. if (!mounted) {
  1719. dispose = listen(div, "click", /*emitConfigureChoice*/ ctx[5]);
  1720. mounted = true;
  1721. }
  1722. },
  1723. p(ctx, dirty) {
  1724. if (!current || dirty & /*choiceName*/ 8 && div_aria_label_value !== (div_aria_label_value = `Configure${/*choiceName*/ ctx[3] ? " " + /*choiceName*/ ctx[3] : ""}`)) {
  1725. attr(div, "aria-label", div_aria_label_value);
  1726. }
  1727. },
  1728. i(local) {
  1729. if (current) return;
  1730. transition_in(icon.$$.fragment, local);
  1731. current = true;
  1732. },
  1733. o(local) {
  1734. transition_out(icon.$$.fragment, local);
  1735. current = false;
  1736. },
  1737. d(detaching) {
  1738. if (detaching) detach(div);
  1739. destroy_component(icon);
  1740. mounted = false;
  1741. dispose();
  1742. }
  1743. };
  1744. }
  1745. function create_fragment$b(ctx) {
  1746. let div3;
  1747. let div0;
  1748. let icon0;
  1749. let div0_aria_label_value;
  1750. let div0_style_value;
  1751. let t0;
  1752. let t1;
  1753. let div1;
  1754. let icon1;
  1755. let div1_aria_label_value;
  1756. let t2;
  1757. let div2;
  1758. let icon2;
  1759. let div2_tabindex_value;
  1760. let div2_style_value;
  1761. let current;
  1762. let mounted;
  1763. let dispose;
  1764. icon0 = new Icon({ props: { data: faBolt } });
  1765. let if_block = /*showConfigureButton*/ ctx[1] && create_if_block$3(ctx);
  1766. icon1 = new Icon({ props: { data: faTrash } });
  1767. icon2 = new Icon({ props: { data: faBars } });
  1768. return {
  1769. c() {
  1770. div3 = element("div");
  1771. div0 = element("div");
  1772. create_component(icon0.$$.fragment);
  1773. t0 = space();
  1774. if (if_block) if_block.c();
  1775. t1 = space();
  1776. div1 = element("div");
  1777. create_component(icon1.$$.fragment);
  1778. t2 = space();
  1779. div2 = element("div");
  1780. create_component(icon2.$$.fragment);
  1781. attr(div0, "class", "alignIconInDivInMiddle clickable svelte-a47k80");
  1782. attr(div0, "aria-label", div0_aria_label_value = `${/*commandEnabled*/ ctx[2] ? "Remove" : "Add"} command${/*choiceName*/ ctx[3]
  1783. ? " for " + /*choiceName*/ ctx[3]
  1784. : ""}`);
  1785. attr(div0, "style", div0_style_value = /*commandEnabled*/ ctx[2] ? "color: #FDD023;" : "");
  1786. attr(div1, "aria-label", div1_aria_label_value = `Delete${/*choiceName*/ ctx[3] ? " " + /*choiceName*/ ctx[3] : ""}`);
  1787. attr(div1, "class", "alignIconInDivInMiddle clickable svelte-a47k80");
  1788. attr(div2, "tabindex", div2_tabindex_value = /*dragDisabled*/ ctx[0] ? 0 : -1);
  1789. attr(div2, "aria-label", "Drag-handle");
  1790. attr(div2, "style", div2_style_value = "" + ((/*dragDisabled*/ ctx[0]
  1791. ? 'cursor: grab'
  1792. : 'cursor: grabbing') + ";"));
  1793. attr(div2, "class", "alignIconInDivInMiddle svelte-a47k80");
  1794. attr(div3, "class", "rightButtonsContainer svelte-a47k80");
  1795. },
  1796. m(target, anchor) {
  1797. insert(target, div3, anchor);
  1798. append(div3, div0);
  1799. mount_component(icon0, div0, null);
  1800. append(div3, t0);
  1801. if (if_block) if_block.m(div3, null);
  1802. append(div3, t1);
  1803. append(div3, div1);
  1804. mount_component(icon1, div1, null);
  1805. append(div3, t2);
  1806. append(div3, div2);
  1807. mount_component(icon2, div2, null);
  1808. current = true;
  1809. if (!mounted) {
  1810. dispose = [
  1811. listen(div0, "click", /*emitToggleCommand*/ ctx[6]),
  1812. listen(div1, "click", /*emitDeleteChoice*/ ctx[4]),
  1813. listen(div2, "mousedown", /*mousedown_handler*/ ctx[7]),
  1814. listen(div2, "touchstart", /*touchstart_handler*/ ctx[8])
  1815. ];
  1816. mounted = true;
  1817. }
  1818. },
  1819. p(ctx, [dirty]) {
  1820. if (!current || dirty & /*commandEnabled, choiceName*/ 12 && div0_aria_label_value !== (div0_aria_label_value = `${/*commandEnabled*/ ctx[2] ? "Remove" : "Add"} command${/*choiceName*/ ctx[3]
  1821. ? " for " + /*choiceName*/ ctx[3]
  1822. : ""}`)) {
  1823. attr(div0, "aria-label", div0_aria_label_value);
  1824. }
  1825. if (!current || dirty & /*commandEnabled*/ 4 && div0_style_value !== (div0_style_value = /*commandEnabled*/ ctx[2] ? "color: #FDD023;" : "")) {
  1826. attr(div0, "style", div0_style_value);
  1827. }
  1828. if (/*showConfigureButton*/ ctx[1]) {
  1829. if (if_block) {
  1830. if_block.p(ctx, dirty);
  1831. if (dirty & /*showConfigureButton*/ 2) {
  1832. transition_in(if_block, 1);
  1833. }
  1834. } else {
  1835. if_block = create_if_block$3(ctx);
  1836. if_block.c();
  1837. transition_in(if_block, 1);
  1838. if_block.m(div3, t1);
  1839. }
  1840. } else if (if_block) {
  1841. group_outros();
  1842. transition_out(if_block, 1, 1, () => {
  1843. if_block = null;
  1844. });
  1845. check_outros();
  1846. }
  1847. if (!current || dirty & /*choiceName*/ 8 && div1_aria_label_value !== (div1_aria_label_value = `Delete${/*choiceName*/ ctx[3] ? " " + /*choiceName*/ ctx[3] : ""}`)) {
  1848. attr(div1, "aria-label", div1_aria_label_value);
  1849. }
  1850. if (!current || dirty & /*dragDisabled*/ 1 && div2_tabindex_value !== (div2_tabindex_value = /*dragDisabled*/ ctx[0] ? 0 : -1)) {
  1851. attr(div2, "tabindex", div2_tabindex_value);
  1852. }
  1853. if (!current || dirty & /*dragDisabled*/ 1 && div2_style_value !== (div2_style_value = "" + ((/*dragDisabled*/ ctx[0]
  1854. ? 'cursor: grab'
  1855. : 'cursor: grabbing') + ";"))) {
  1856. attr(div2, "style", div2_style_value);
  1857. }
  1858. },
  1859. i(local) {
  1860. if (current) return;
  1861. transition_in(icon0.$$.fragment, local);
  1862. transition_in(if_block);
  1863. transition_in(icon1.$$.fragment, local);
  1864. transition_in(icon2.$$.fragment, local);
  1865. current = true;
  1866. },
  1867. o(local) {
  1868. transition_out(icon0.$$.fragment, local);
  1869. transition_out(if_block);
  1870. transition_out(icon1.$$.fragment, local);
  1871. transition_out(icon2.$$.fragment, local);
  1872. current = false;
  1873. },
  1874. d(detaching) {
  1875. if (detaching) detach(div3);
  1876. destroy_component(icon0);
  1877. if (if_block) if_block.d();
  1878. destroy_component(icon1);
  1879. destroy_component(icon2);
  1880. mounted = false;
  1881. run_all(dispose);
  1882. }
  1883. };
  1884. }
  1885. function instance$b($$self, $$props, $$invalidate) {
  1886. let { dragDisabled } = $$props;
  1887. let { showConfigureButton = true } = $$props;
  1888. let { commandEnabled = false } = $$props;
  1889. let { choiceName = "" } = $$props;
  1890. const dispatcher = createEventDispatcher();
  1891. function emitDeleteChoice() {
  1892. dispatcher('deleteChoice');
  1893. }
  1894. function emitConfigureChoice() {
  1895. dispatcher('configureChoice');
  1896. }
  1897. function emitToggleCommand() {
  1898. dispatcher('toggleCommand');
  1899. }
  1900. function mousedown_handler(event) {
  1901. bubble.call(this, $$self, event);
  1902. }
  1903. function touchstart_handler(event) {
  1904. bubble.call(this, $$self, event);
  1905. }
  1906. $$self.$$set = $$props => {
  1907. if ('dragDisabled' in $$props) $$invalidate(0, dragDisabled = $$props.dragDisabled);
  1908. if ('showConfigureButton' in $$props) $$invalidate(1, showConfigureButton = $$props.showConfigureButton);
  1909. if ('commandEnabled' in $$props) $$invalidate(2, commandEnabled = $$props.commandEnabled);
  1910. if ('choiceName' in $$props) $$invalidate(3, choiceName = $$props.choiceName);
  1911. };
  1912. return [
  1913. dragDisabled,
  1914. showConfigureButton,
  1915. commandEnabled,
  1916. choiceName,
  1917. emitDeleteChoice,
  1918. emitConfigureChoice,
  1919. emitToggleCommand,
  1920. mousedown_handler,
  1921. touchstart_handler
  1922. ];
  1923. }
  1924. class ChoiceItemRightButtons extends SvelteComponent {
  1925. constructor(options) {
  1926. super();
  1927. init(
  1928. this,
  1929. options,
  1930. instance$b,
  1931. create_fragment$b,
  1932. safe_not_equal,
  1933. {
  1934. dragDisabled: 0,
  1935. showConfigureButton: 1,
  1936. commandEnabled: 2,
  1937. choiceName: 3
  1938. },
  1939. add_css$8
  1940. );
  1941. }
  1942. }
  1943. /* src/gui/choiceList/ChoiceListItem.svelte generated by Svelte v3.47.0 */
  1944. function add_css$7(target) {
  1945. append_styles(target, "svelte-1vcfikc", ".choiceListItem.svelte-1vcfikc{display:flex;font-size:16px;align-items:center;margin:12px 0 0 0;transition:1000ms ease-in-out}.choiceListItemName.svelte-1vcfikc{flex:1 0 0}");
  1946. }
  1947. function create_fragment$a(ctx) {
  1948. let div;
  1949. let span;
  1950. let t0_value = /*choice*/ ctx[0].name + "";
  1951. let t0;
  1952. let t1;
  1953. let rightbuttons;
  1954. let updating_choiceName;
  1955. let updating_commandEnabled;
  1956. let updating_showConfigureButton;
  1957. let updating_dragDisabled;
  1958. let current;
  1959. function rightbuttons_choiceName_binding(value) {
  1960. /*rightbuttons_choiceName_binding*/ ctx[6](value);
  1961. }
  1962. function rightbuttons_commandEnabled_binding(value) {
  1963. /*rightbuttons_commandEnabled_binding*/ ctx[7](value);
  1964. }
  1965. function rightbuttons_showConfigureButton_binding(value) {
  1966. /*rightbuttons_showConfigureButton_binding*/ ctx[8](value);
  1967. }
  1968. function rightbuttons_dragDisabled_binding(value) {
  1969. /*rightbuttons_dragDisabled_binding*/ ctx[9](value);
  1970. }
  1971. let rightbuttons_props = {};
  1972. if (/*choice*/ ctx[0].name !== void 0) {
  1973. rightbuttons_props.choiceName = /*choice*/ ctx[0].name;
  1974. }
  1975. if (/*choice*/ ctx[0].command !== void 0) {
  1976. rightbuttons_props.commandEnabled = /*choice*/ ctx[0].command;
  1977. }
  1978. if (/*showConfigureButton*/ ctx[2] !== void 0) {
  1979. rightbuttons_props.showConfigureButton = /*showConfigureButton*/ ctx[2];
  1980. }
  1981. if (/*dragDisabled*/ ctx[1] !== void 0) {
  1982. rightbuttons_props.dragDisabled = /*dragDisabled*/ ctx[1];
  1983. }
  1984. rightbuttons = new ChoiceItemRightButtons({ props: rightbuttons_props });
  1985. binding_callbacks.push(() => bind(rightbuttons, 'choiceName', rightbuttons_choiceName_binding));
  1986. binding_callbacks.push(() => bind(rightbuttons, 'commandEnabled', rightbuttons_commandEnabled_binding));
  1987. binding_callbacks.push(() => bind(rightbuttons, 'showConfigureButton', rightbuttons_showConfigureButton_binding));
  1988. binding_callbacks.push(() => bind(rightbuttons, 'dragDisabled', rightbuttons_dragDisabled_binding));
  1989. rightbuttons.$on("mousedown", /*mousedown_handler*/ ctx[10]);
  1990. rightbuttons.$on("touchstart", /*touchstart_handler*/ ctx[11]);
  1991. rightbuttons.$on("deleteChoice", /*deleteChoice*/ ctx[3]);
  1992. rightbuttons.$on("configureChoice", /*configureChoice*/ ctx[4]);
  1993. rightbuttons.$on("toggleCommand", /*toggleCommandForChoice*/ ctx[5]);
  1994. return {
  1995. c() {
  1996. div = element("div");
  1997. span = element("span");
  1998. t0 = text(t0_value);
  1999. t1 = space();
  2000. create_component(rightbuttons.$$.fragment);
  2001. attr(span, "class", "choiceListItemName svelte-1vcfikc");
  2002. attr(div, "class", "choiceListItem svelte-1vcfikc");
  2003. },
  2004. m(target, anchor) {
  2005. insert(target, div, anchor);
  2006. append(div, span);
  2007. append(span, t0);
  2008. append(div, t1);
  2009. mount_component(rightbuttons, div, null);
  2010. current = true;
  2011. },
  2012. p(ctx, [dirty]) {
  2013. if ((!current || dirty & /*choice*/ 1) && t0_value !== (t0_value = /*choice*/ ctx[0].name + "")) set_data(t0, t0_value);
  2014. const rightbuttons_changes = {};
  2015. if (!updating_choiceName && dirty & /*choice*/ 1) {
  2016. updating_choiceName = true;
  2017. rightbuttons_changes.choiceName = /*choice*/ ctx[0].name;
  2018. add_flush_callback(() => updating_choiceName = false);
  2019. }
  2020. if (!updating_commandEnabled && dirty & /*choice*/ 1) {
  2021. updating_commandEnabled = true;
  2022. rightbuttons_changes.commandEnabled = /*choice*/ ctx[0].command;
  2023. add_flush_callback(() => updating_commandEnabled = false);
  2024. }
  2025. if (!updating_showConfigureButton && dirty & /*showConfigureButton*/ 4) {
  2026. updating_showConfigureButton = true;
  2027. rightbuttons_changes.showConfigureButton = /*showConfigureButton*/ ctx[2];
  2028. add_flush_callback(() => updating_showConfigureButton = false);
  2029. }
  2030. if (!updating_dragDisabled && dirty & /*dragDisabled*/ 2) {
  2031. updating_dragDisabled = true;
  2032. rightbuttons_changes.dragDisabled = /*dragDisabled*/ ctx[1];
  2033. add_flush_callback(() => updating_dragDisabled = false);
  2034. }
  2035. rightbuttons.$set(rightbuttons_changes);
  2036. },
  2037. i(local) {
  2038. if (current) return;
  2039. transition_in(rightbuttons.$$.fragment, local);
  2040. current = true;
  2041. },
  2042. o(local) {
  2043. transition_out(rightbuttons.$$.fragment, local);
  2044. current = false;
  2045. },
  2046. d(detaching) {
  2047. if (detaching) detach(div);
  2048. destroy_component(rightbuttons);
  2049. }
  2050. };
  2051. }
  2052. function instance$a($$self, $$props, $$invalidate) {
  2053. let { choice } = $$props;
  2054. let { dragDisabled } = $$props;
  2055. let showConfigureButton = true;
  2056. const dispatcher = createEventDispatcher();
  2057. function deleteChoice() {
  2058. dispatcher('deleteChoice', { choice });
  2059. }
  2060. function configureChoice() {
  2061. dispatcher('configureChoice', { choice });
  2062. }
  2063. function toggleCommandForChoice() {
  2064. dispatcher('toggleCommand', { choice });
  2065. }
  2066. function rightbuttons_choiceName_binding(value) {
  2067. if ($$self.$$.not_equal(choice.name, value)) {
  2068. choice.name = value;
  2069. $$invalidate(0, choice);
  2070. }
  2071. }
  2072. function rightbuttons_commandEnabled_binding(value) {
  2073. if ($$self.$$.not_equal(choice.command, value)) {
  2074. choice.command = value;
  2075. $$invalidate(0, choice);
  2076. }
  2077. }
  2078. function rightbuttons_showConfigureButton_binding(value) {
  2079. showConfigureButton = value;
  2080. $$invalidate(2, showConfigureButton);
  2081. }
  2082. function rightbuttons_dragDisabled_binding(value) {
  2083. dragDisabled = value;
  2084. $$invalidate(1, dragDisabled);
  2085. }
  2086. function mousedown_handler(event) {
  2087. bubble.call(this, $$self, event);
  2088. }
  2089. function touchstart_handler(event) {
  2090. bubble.call(this, $$self, event);
  2091. }
  2092. $$self.$$set = $$props => {
  2093. if ('choice' in $$props) $$invalidate(0, choice = $$props.choice);
  2094. if ('dragDisabled' in $$props) $$invalidate(1, dragDisabled = $$props.dragDisabled);
  2095. };
  2096. return [
  2097. choice,
  2098. dragDisabled,
  2099. showConfigureButton,
  2100. deleteChoice,
  2101. configureChoice,
  2102. toggleCommandForChoice,
  2103. rightbuttons_choiceName_binding,
  2104. rightbuttons_commandEnabled_binding,
  2105. rightbuttons_showConfigureButton_binding,
  2106. rightbuttons_dragDisabled_binding,
  2107. mousedown_handler,
  2108. touchstart_handler
  2109. ];
  2110. }
  2111. class ChoiceListItem extends SvelteComponent {
  2112. constructor(options) {
  2113. super();
  2114. init(this, options, instance$a, create_fragment$a, safe_not_equal, { choice: 0, dragDisabled: 1 }, add_css$7);
  2115. }
  2116. }
  2117. /* src/gui/choiceList/MultiChoiceListItem.svelte generated by Svelte v3.47.0 */
  2118. function add_css$6(target) {
  2119. append_styles(target, "svelte-na99np", ".multiChoiceListItem.svelte-na99np{display:flex;font-size:16px;align-items:center;margin:12px 0 0 0}.clickable.svelte-na99np:hover{cursor:pointer}.multiChoiceListItemName.svelte-na99np{flex:1 0 0;margin-left:5px}.nestedChoiceList.svelte-na99np{padding-left:25px}");
  2120. }
  2121. // (43:4) {#if !collapseId || (collapseId && choice.id !== collapseId)}
  2122. function create_if_block$2(ctx) {
  2123. let if_block_anchor;
  2124. let current;
  2125. let if_block = !/*choice*/ ctx[0].collapsed && create_if_block_1$1(ctx);
  2126. return {
  2127. c() {
  2128. if (if_block) if_block.c();
  2129. if_block_anchor = empty();
  2130. },
  2131. m(target, anchor) {
  2132. if (if_block) if_block.m(target, anchor);
  2133. insert(target, if_block_anchor, anchor);
  2134. current = true;
  2135. },
  2136. p(ctx, dirty) {
  2137. if (!/*choice*/ ctx[0].collapsed) {
  2138. if (if_block) {
  2139. if_block.p(ctx, dirty);
  2140. if (dirty & /*choice*/ 1) {
  2141. transition_in(if_block, 1);
  2142. }
  2143. } else {
  2144. if_block = create_if_block_1$1(ctx);
  2145. if_block.c();
  2146. transition_in(if_block, 1);
  2147. if_block.m(if_block_anchor.parentNode, if_block_anchor);
  2148. }
  2149. } else if (if_block) {
  2150. group_outros();
  2151. transition_out(if_block, 1, 1, () => {
  2152. if_block = null;
  2153. });
  2154. check_outros();
  2155. }
  2156. },
  2157. i(local) {
  2158. if (current) return;
  2159. transition_in(if_block);
  2160. current = true;
  2161. },
  2162. o(local) {
  2163. transition_out(if_block);
  2164. current = false;
  2165. },
  2166. d(detaching) {
  2167. if (if_block) if_block.d(detaching);
  2168. if (detaching) detach(if_block_anchor);
  2169. }
  2170. };
  2171. }
  2172. // (44:8) {#if !choice.collapsed}
  2173. function create_if_block_1$1(ctx) {
  2174. let div;
  2175. let choicelist;
  2176. let updating_multiChoice;
  2177. let updating_choices;
  2178. let current;
  2179. function choicelist_multiChoice_binding(value) {
  2180. /*choicelist_multiChoice_binding*/ ctx[14](value);
  2181. }
  2182. function choicelist_choices_binding(value) {
  2183. /*choicelist_choices_binding*/ ctx[15](value);
  2184. }
  2185. let choicelist_props = {};
  2186. if (/*choice*/ ctx[0] !== void 0) {
  2187. choicelist_props.multiChoice = /*choice*/ ctx[0];
  2188. }
  2189. if (/*choice*/ ctx[0].choices !== void 0) {
  2190. choicelist_props.choices = /*choice*/ ctx[0].choices;
  2191. }
  2192. choicelist = new ChoiceList({ props: choicelist_props });
  2193. binding_callbacks.push(() => bind(choicelist, 'multiChoice', choicelist_multiChoice_binding));
  2194. binding_callbacks.push(() => bind(choicelist, 'choices', choicelist_choices_binding));
  2195. choicelist.$on("deleteChoice", /*deleteChoice_handler*/ ctx[16]);
  2196. choicelist.$on("configureChoice", /*configureChoice_handler*/ ctx[17]);
  2197. choicelist.$on("toggleCommand", /*toggleCommand_handler*/ ctx[18]);
  2198. return {
  2199. c() {
  2200. div = element("div");
  2201. create_component(choicelist.$$.fragment);
  2202. attr(div, "class", "nestedChoiceList svelte-na99np");
  2203. },
  2204. m(target, anchor) {
  2205. insert(target, div, anchor);
  2206. mount_component(choicelist, div, null);
  2207. current = true;
  2208. },
  2209. p(ctx, dirty) {
  2210. const choicelist_changes = {};
  2211. if (!updating_multiChoice && dirty & /*choice*/ 1) {
  2212. updating_multiChoice = true;
  2213. choicelist_changes.multiChoice = /*choice*/ ctx[0];
  2214. add_flush_callback(() => updating_multiChoice = false);
  2215. }
  2216. if (!updating_choices && dirty & /*choice*/ 1) {
  2217. updating_choices = true;
  2218. choicelist_changes.choices = /*choice*/ ctx[0].choices;
  2219. add_flush_callback(() => updating_choices = false);
  2220. }
  2221. choicelist.$set(choicelist_changes);
  2222. },
  2223. i(local) {
  2224. if (current) return;
  2225. transition_in(choicelist.$$.fragment, local);
  2226. current = true;
  2227. },
  2228. o(local) {
  2229. transition_out(choicelist.$$.fragment, local);
  2230. current = false;
  2231. },
  2232. d(detaching) {
  2233. if (detaching) detach(div);
  2234. destroy_component(choicelist);
  2235. }
  2236. };
  2237. }
  2238. function create_fragment$9(ctx) {
  2239. let div2;
  2240. let div1;
  2241. let div0;
  2242. let icon;
  2243. let t0;
  2244. let span;
  2245. let t1_value = /*choice*/ ctx[0].name + "";
  2246. let t1;
  2247. let t2;
  2248. let rightbuttons;
  2249. let updating_showConfigureButton;
  2250. let updating_dragDisabled;
  2251. let updating_choiceName;
  2252. let updating_commandEnabled;
  2253. let t3;
  2254. let current;
  2255. let mounted;
  2256. let dispose;
  2257. icon = new Icon({
  2258. props: {
  2259. data: faChevronDown,
  2260. style: `transform:rotate(${/*choice*/ ctx[0].collapsed ? -180 : 0}deg)`
  2261. }
  2262. });
  2263. function rightbuttons_showConfigureButton_binding(value) {
  2264. /*rightbuttons_showConfigureButton_binding*/ ctx[8](value);
  2265. }
  2266. function rightbuttons_dragDisabled_binding(value) {
  2267. /*rightbuttons_dragDisabled_binding*/ ctx[9](value);
  2268. }
  2269. function rightbuttons_choiceName_binding(value) {
  2270. /*rightbuttons_choiceName_binding*/ ctx[10](value);
  2271. }
  2272. function rightbuttons_commandEnabled_binding(value) {
  2273. /*rightbuttons_commandEnabled_binding*/ ctx[11](value);
  2274. }
  2275. let rightbuttons_props = {};
  2276. if (/*showConfigureButton*/ ctx[3] !== void 0) {
  2277. rightbuttons_props.showConfigureButton = /*showConfigureButton*/ ctx[3];
  2278. }
  2279. if (/*dragDisabled*/ ctx[1] !== void 0) {
  2280. rightbuttons_props.dragDisabled = /*dragDisabled*/ ctx[1];
  2281. }
  2282. if (/*choice*/ ctx[0].name !== void 0) {
  2283. rightbuttons_props.choiceName = /*choice*/ ctx[0].name;
  2284. }
  2285. if (/*choice*/ ctx[0].command !== void 0) {
  2286. rightbuttons_props.commandEnabled = /*choice*/ ctx[0].command;
  2287. }
  2288. rightbuttons = new ChoiceItemRightButtons({ props: rightbuttons_props });
  2289. binding_callbacks.push(() => bind(rightbuttons, 'showConfigureButton', rightbuttons_showConfigureButton_binding));
  2290. binding_callbacks.push(() => bind(rightbuttons, 'dragDisabled', rightbuttons_dragDisabled_binding));
  2291. binding_callbacks.push(() => bind(rightbuttons, 'choiceName', rightbuttons_choiceName_binding));
  2292. binding_callbacks.push(() => bind(rightbuttons, 'commandEnabled', rightbuttons_commandEnabled_binding));
  2293. rightbuttons.$on("mousedown", /*mousedown_handler*/ ctx[12]);
  2294. rightbuttons.$on("touchstart", /*touchstart_handler*/ ctx[13]);
  2295. rightbuttons.$on("deleteChoice", /*deleteChoice*/ ctx[4]);
  2296. rightbuttons.$on("configureChoice", /*configureChoice*/ ctx[5]);
  2297. rightbuttons.$on("toggleCommand", /*toggleCommandForChoice*/ ctx[6]);
  2298. let if_block = (!/*collapseId*/ ctx[2] || /*collapseId*/ ctx[2] && /*choice*/ ctx[0].id !== /*collapseId*/ ctx[2]) && create_if_block$2(ctx);
  2299. return {
  2300. c() {
  2301. div2 = element("div");
  2302. div1 = element("div");
  2303. div0 = element("div");
  2304. create_component(icon.$$.fragment);
  2305. t0 = space();
  2306. span = element("span");
  2307. t1 = text(t1_value);
  2308. t2 = space();
  2309. create_component(rightbuttons.$$.fragment);
  2310. t3 = space();
  2311. if (if_block) if_block.c();
  2312. attr(div0, "class", "multiChoiceListItemName clickable svelte-na99np");
  2313. attr(div1, "class", "multiChoiceListItem svelte-na99np");
  2314. },
  2315. m(target, anchor) {
  2316. insert(target, div2, anchor);
  2317. append(div2, div1);
  2318. append(div1, div0);
  2319. mount_component(icon, div0, null);
  2320. append(div0, t0);
  2321. append(div0, span);
  2322. append(span, t1);
  2323. append(div1, t2);
  2324. mount_component(rightbuttons, div1, null);
  2325. append(div2, t3);
  2326. if (if_block) if_block.m(div2, null);
  2327. current = true;
  2328. if (!mounted) {
  2329. dispose = listen(div0, "click", /*click_handler*/ ctx[7]);
  2330. mounted = true;
  2331. }
  2332. },
  2333. p(ctx, [dirty]) {
  2334. const icon_changes = {};
  2335. if (dirty & /*choice*/ 1) icon_changes.style = `transform:rotate(${/*choice*/ ctx[0].collapsed ? -180 : 0}deg)`;
  2336. icon.$set(icon_changes);
  2337. if ((!current || dirty & /*choice*/ 1) && t1_value !== (t1_value = /*choice*/ ctx[0].name + "")) set_data(t1, t1_value);
  2338. const rightbuttons_changes = {};
  2339. if (!updating_showConfigureButton && dirty & /*showConfigureButton*/ 8) {
  2340. updating_showConfigureButton = true;
  2341. rightbuttons_changes.showConfigureButton = /*showConfigureButton*/ ctx[3];
  2342. add_flush_callback(() => updating_showConfigureButton = false);
  2343. }
  2344. if (!updating_dragDisabled && dirty & /*dragDisabled*/ 2) {
  2345. updating_dragDisabled = true;
  2346. rightbuttons_changes.dragDisabled = /*dragDisabled*/ ctx[1];
  2347. add_flush_callback(() => updating_dragDisabled = false);
  2348. }
  2349. if (!updating_choiceName && dirty & /*choice*/ 1) {
  2350. updating_choiceName = true;
  2351. rightbuttons_changes.choiceName = /*choice*/ ctx[0].name;
  2352. add_flush_callback(() => updating_choiceName = false);
  2353. }
  2354. if (!updating_commandEnabled && dirty & /*choice*/ 1) {
  2355. updating_commandEnabled = true;
  2356. rightbuttons_changes.commandEnabled = /*choice*/ ctx[0].command;
  2357. add_flush_callback(() => updating_commandEnabled = false);
  2358. }
  2359. rightbuttons.$set(rightbuttons_changes);
  2360. if (!/*collapseId*/ ctx[2] || /*collapseId*/ ctx[2] && /*choice*/ ctx[0].id !== /*collapseId*/ ctx[2]) {
  2361. if (if_block) {
  2362. if_block.p(ctx, dirty);
  2363. if (dirty & /*collapseId, choice*/ 5) {
  2364. transition_in(if_block, 1);
  2365. }
  2366. } else {
  2367. if_block = create_if_block$2(ctx);
  2368. if_block.c();
  2369. transition_in(if_block, 1);
  2370. if_block.m(div2, null);
  2371. }
  2372. } else if (if_block) {
  2373. group_outros();
  2374. transition_out(if_block, 1, 1, () => {
  2375. if_block = null;
  2376. });
  2377. check_outros();
  2378. }
  2379. },
  2380. i(local) {
  2381. if (current) return;
  2382. transition_in(icon.$$.fragment, local);
  2383. transition_in(rightbuttons.$$.fragment, local);
  2384. transition_in(if_block);
  2385. current = true;
  2386. },
  2387. o(local) {
  2388. transition_out(icon.$$.fragment, local);
  2389. transition_out(rightbuttons.$$.fragment, local);
  2390. transition_out(if_block);
  2391. current = false;
  2392. },
  2393. d(detaching) {
  2394. if (detaching) detach(div2);
  2395. destroy_component(icon);
  2396. destroy_component(rightbuttons);
  2397. if (if_block) if_block.d();
  2398. mounted = false;
  2399. dispose();
  2400. }
  2401. };
  2402. }
  2403. function instance$9($$self, $$props, $$invalidate) {
  2404. let { choice } = $$props;
  2405. let { collapseId } = $$props;
  2406. let { dragDisabled } = $$props;
  2407. let showConfigureButton = true;
  2408. const dispatcher = createEventDispatcher();
  2409. function deleteChoice(e) {
  2410. dispatcher('deleteChoice', { choice });
  2411. }
  2412. function configureChoice() {
  2413. dispatcher('configureChoice', { choice });
  2414. }
  2415. function toggleCommandForChoice() {
  2416. dispatcher('toggleCommand', { choice });
  2417. }
  2418. const click_handler = () => $$invalidate(0, choice.collapsed = !choice.collapsed, choice);
  2419. function rightbuttons_showConfigureButton_binding(value) {
  2420. showConfigureButton = value;
  2421. $$invalidate(3, showConfigureButton);
  2422. }
  2423. function rightbuttons_dragDisabled_binding(value) {
  2424. dragDisabled = value;
  2425. $$invalidate(1, dragDisabled);
  2426. }
  2427. function rightbuttons_choiceName_binding(value) {
  2428. if ($$self.$$.not_equal(choice.name, value)) {
  2429. choice.name = value;
  2430. $$invalidate(0, choice);
  2431. }
  2432. }
  2433. function rightbuttons_commandEnabled_binding(value) {
  2434. if ($$self.$$.not_equal(choice.command, value)) {
  2435. choice.command = value;
  2436. $$invalidate(0, choice);
  2437. }
  2438. }
  2439. function mousedown_handler(event) {
  2440. bubble.call(this, $$self, event);
  2441. }
  2442. function touchstart_handler(event) {
  2443. bubble.call(this, $$self, event);
  2444. }
  2445. function choicelist_multiChoice_binding(value) {
  2446. choice = value;
  2447. $$invalidate(0, choice);
  2448. }
  2449. function choicelist_choices_binding(value) {
  2450. if ($$self.$$.not_equal(choice.choices, value)) {
  2451. choice.choices = value;
  2452. $$invalidate(0, choice);
  2453. }
  2454. }
  2455. function deleteChoice_handler(event) {
  2456. bubble.call(this, $$self, event);
  2457. }
  2458. function configureChoice_handler(event) {
  2459. bubble.call(this, $$self, event);
  2460. }
  2461. function toggleCommand_handler(event) {
  2462. bubble.call(this, $$self, event);
  2463. }
  2464. $$self.$$set = $$props => {
  2465. if ('choice' in $$props) $$invalidate(0, choice = $$props.choice);
  2466. if ('collapseId' in $$props) $$invalidate(2, collapseId = $$props.collapseId);
  2467. if ('dragDisabled' in $$props) $$invalidate(1, dragDisabled = $$props.dragDisabled);
  2468. };
  2469. return [
  2470. choice,
  2471. dragDisabled,
  2472. collapseId,
  2473. showConfigureButton,
  2474. deleteChoice,
  2475. configureChoice,
  2476. toggleCommandForChoice,
  2477. click_handler,
  2478. rightbuttons_showConfigureButton_binding,
  2479. rightbuttons_dragDisabled_binding,
  2480. rightbuttons_choiceName_binding,
  2481. rightbuttons_commandEnabled_binding,
  2482. mousedown_handler,
  2483. touchstart_handler,
  2484. choicelist_multiChoice_binding,
  2485. choicelist_choices_binding,
  2486. deleteChoice_handler,
  2487. configureChoice_handler,
  2488. toggleCommand_handler
  2489. ];
  2490. }
  2491. class MultiChoiceListItem extends SvelteComponent {
  2492. constructor(options) {
  2493. super();
  2494. init(
  2495. this,
  2496. options,
  2497. instance$9,
  2498. create_fragment$9,
  2499. safe_not_equal,
  2500. {
  2501. choice: 0,
  2502. collapseId: 2,
  2503. dragDisabled: 1
  2504. },
  2505. add_css$6
  2506. );
  2507. }
  2508. }
  2509. function _typeof(obj) {
  2510. "@babel/helpers - typeof";
  2511. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  2512. _typeof = function (obj) {
  2513. return typeof obj;
  2514. };
  2515. } else {
  2516. _typeof = function (obj) {
  2517. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  2518. };
  2519. }
  2520. return _typeof(obj);
  2521. }
  2522. function _defineProperty(obj, key, value) {
  2523. if (key in obj) {
  2524. Object.defineProperty(obj, key, {
  2525. value: value,
  2526. enumerable: true,
  2527. configurable: true,
  2528. writable: true
  2529. });
  2530. } else {
  2531. obj[key] = value;
  2532. }
  2533. return obj;
  2534. }
  2535. function ownKeys(object, enumerableOnly) {
  2536. var keys = Object.keys(object);
  2537. if (Object.getOwnPropertySymbols) {
  2538. var symbols = Object.getOwnPropertySymbols(object);
  2539. if (enumerableOnly) symbols = symbols.filter(function (sym) {
  2540. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  2541. });
  2542. keys.push.apply(keys, symbols);
  2543. }
  2544. return keys;
  2545. }
  2546. function _objectSpread2(target) {
  2547. for (var i = 1; i < arguments.length; i++) {
  2548. var source = arguments[i] != null ? arguments[i] : {};
  2549. if (i % 2) {
  2550. ownKeys(Object(source), true).forEach(function (key) {
  2551. _defineProperty(target, key, source[key]);
  2552. });
  2553. } else if (Object.getOwnPropertyDescriptors) {
  2554. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  2555. } else {
  2556. ownKeys(Object(source)).forEach(function (key) {
  2557. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  2558. });
  2559. }
  2560. }
  2561. return target;
  2562. }
  2563. function _objectWithoutPropertiesLoose(source, excluded) {
  2564. if (source == null) return {};
  2565. var target = {};
  2566. var sourceKeys = Object.keys(source);
  2567. var key, i;
  2568. for (i = 0; i < sourceKeys.length; i++) {
  2569. key = sourceKeys[i];
  2570. if (excluded.indexOf(key) >= 0) continue;
  2571. target[key] = source[key];
  2572. }
  2573. return target;
  2574. }
  2575. function _objectWithoutProperties(source, excluded) {
  2576. if (source == null) return {};
  2577. var target = _objectWithoutPropertiesLoose(source, excluded);
  2578. var key, i;
  2579. if (Object.getOwnPropertySymbols) {
  2580. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  2581. for (i = 0; i < sourceSymbolKeys.length; i++) {
  2582. key = sourceSymbolKeys[i];
  2583. if (excluded.indexOf(key) >= 0) continue;
  2584. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  2585. target[key] = source[key];
  2586. }
  2587. }
  2588. return target;
  2589. }
  2590. function _slicedToArray(arr, i) {
  2591. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  2592. }
  2593. function _toConsumableArray(arr) {
  2594. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  2595. }
  2596. function _arrayWithoutHoles(arr) {
  2597. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  2598. }
  2599. function _arrayWithHoles(arr) {
  2600. if (Array.isArray(arr)) return arr;
  2601. }
  2602. function _iterableToArray(iter) {
  2603. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  2604. }
  2605. function _iterableToArrayLimit(arr, i) {
  2606. if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  2607. var _arr = [];
  2608. var _n = true;
  2609. var _d = false;
  2610. var _e = undefined;
  2611. try {
  2612. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  2613. _arr.push(_s.value);
  2614. if (i && _arr.length === i) break;
  2615. }
  2616. } catch (err) {
  2617. _d = true;
  2618. _e = err;
  2619. } finally {
  2620. try {
  2621. if (!_n && _i["return"] != null) _i["return"]();
  2622. } finally {
  2623. if (_d) throw _e;
  2624. }
  2625. }
  2626. return _arr;
  2627. }
  2628. function _unsupportedIterableToArray(o, minLen) {
  2629. if (!o) return;
  2630. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  2631. var n = Object.prototype.toString.call(o).slice(8, -1);
  2632. if (n === "Object" && o.constructor) n = o.constructor.name;
  2633. if (n === "Map" || n === "Set") return Array.from(o);
  2634. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  2635. }
  2636. function _arrayLikeToArray(arr, len) {
  2637. if (len == null || len > arr.length) len = arr.length;
  2638. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  2639. return arr2;
  2640. }
  2641. function _nonIterableSpread() {
  2642. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  2643. }
  2644. function _nonIterableRest() {
  2645. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  2646. }
  2647. function _createForOfIteratorHelper(o, allowArrayLike) {
  2648. var it;
  2649. if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
  2650. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  2651. if (it) o = it;
  2652. var i = 0;
  2653. var F = function () {};
  2654. return {
  2655. s: F,
  2656. n: function () {
  2657. if (i >= o.length) return {
  2658. done: true
  2659. };
  2660. return {
  2661. done: false,
  2662. value: o[i++]
  2663. };
  2664. },
  2665. e: function (e) {
  2666. throw e;
  2667. },
  2668. f: F
  2669. };
  2670. }
  2671. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  2672. }
  2673. var normalCompletion = true,
  2674. didErr = false,
  2675. err;
  2676. return {
  2677. s: function () {
  2678. it = o[Symbol.iterator]();
  2679. },
  2680. n: function () {
  2681. var step = it.next();
  2682. normalCompletion = step.done;
  2683. return step;
  2684. },
  2685. e: function (e) {
  2686. didErr = true;
  2687. err = e;
  2688. },
  2689. f: function () {
  2690. try {
  2691. if (!normalCompletion && it.return != null) it.return();
  2692. } finally {
  2693. if (didErr) throw err;
  2694. }
  2695. }
  2696. };
  2697. }
  2698. // external events
  2699. var FINALIZE_EVENT_NAME = "finalize";
  2700. var CONSIDER_EVENT_NAME = "consider";
  2701. /**
  2702. * @typedef {Object} Info
  2703. * @property {string} trigger
  2704. * @property {string} id
  2705. * @property {string} source
  2706. * @param {Node} el
  2707. * @param {Array} items
  2708. * @param {Info} info
  2709. */
  2710. function dispatchFinalizeEvent(el, items, info) {
  2711. el.dispatchEvent(new CustomEvent(FINALIZE_EVENT_NAME, {
  2712. detail: {
  2713. items: items,
  2714. info: info
  2715. }
  2716. }));
  2717. }
  2718. /**
  2719. * Dispatches a consider event
  2720. * @param {Node} el
  2721. * @param {Array} items
  2722. * @param {Info} info
  2723. */
  2724. function dispatchConsiderEvent(el, items, info) {
  2725. el.dispatchEvent(new CustomEvent(CONSIDER_EVENT_NAME, {
  2726. detail: {
  2727. items: items,
  2728. info: info
  2729. }
  2730. }));
  2731. } // internal events
  2732. var DRAGGED_ENTERED_EVENT_NAME = "draggedEntered";
  2733. var DRAGGED_LEFT_EVENT_NAME = "draggedLeft";
  2734. var DRAGGED_OVER_INDEX_EVENT_NAME = "draggedOverIndex";
  2735. var DRAGGED_LEFT_DOCUMENT_EVENT_NAME = "draggedLeftDocument";
  2736. var DRAGGED_LEFT_TYPES = {
  2737. LEFT_FOR_ANOTHER: "leftForAnother",
  2738. OUTSIDE_OF_ANY: "outsideOfAny"
  2739. };
  2740. function dispatchDraggedElementEnteredContainer(containerEl, indexObj, draggedEl) {
  2741. containerEl.dispatchEvent(new CustomEvent(DRAGGED_ENTERED_EVENT_NAME, {
  2742. detail: {
  2743. indexObj: indexObj,
  2744. draggedEl: draggedEl
  2745. }
  2746. }));
  2747. }
  2748. /**
  2749. * @param containerEl - the dropzone the element left
  2750. * @param draggedEl - the dragged element
  2751. * @param theOtherDz - the new dropzone the element entered
  2752. */
  2753. function dispatchDraggedElementLeftContainerForAnother(containerEl, draggedEl, theOtherDz) {
  2754. containerEl.dispatchEvent(new CustomEvent(DRAGGED_LEFT_EVENT_NAME, {
  2755. detail: {
  2756. draggedEl: draggedEl,
  2757. type: DRAGGED_LEFT_TYPES.LEFT_FOR_ANOTHER,
  2758. theOtherDz: theOtherDz
  2759. }
  2760. }));
  2761. }
  2762. function dispatchDraggedElementLeftContainerForNone(containerEl, draggedEl) {
  2763. containerEl.dispatchEvent(new CustomEvent(DRAGGED_LEFT_EVENT_NAME, {
  2764. detail: {
  2765. draggedEl: draggedEl,
  2766. type: DRAGGED_LEFT_TYPES.OUTSIDE_OF_ANY
  2767. }
  2768. }));
  2769. }
  2770. function dispatchDraggedElementIsOverIndex(containerEl, indexObj, draggedEl) {
  2771. containerEl.dispatchEvent(new CustomEvent(DRAGGED_OVER_INDEX_EVENT_NAME, {
  2772. detail: {
  2773. indexObj: indexObj,
  2774. draggedEl: draggedEl
  2775. }
  2776. }));
  2777. }
  2778. function dispatchDraggedLeftDocument(draggedEl) {
  2779. window.dispatchEvent(new CustomEvent(DRAGGED_LEFT_DOCUMENT_EVENT_NAME, {
  2780. detail: {
  2781. draggedEl: draggedEl
  2782. }
  2783. }));
  2784. }
  2785. var TRIGGERS = {
  2786. DRAG_STARTED: "dragStarted",
  2787. DRAGGED_ENTERED: DRAGGED_ENTERED_EVENT_NAME,
  2788. DRAGGED_ENTERED_ANOTHER: "dragEnteredAnother",
  2789. DRAGGED_OVER_INDEX: DRAGGED_OVER_INDEX_EVENT_NAME,
  2790. DRAGGED_LEFT: DRAGGED_LEFT_EVENT_NAME,
  2791. DRAGGED_LEFT_ALL: "draggedLeftAll",
  2792. DROPPED_INTO_ZONE: "droppedIntoZone",
  2793. DROPPED_INTO_ANOTHER: "droppedIntoAnother",
  2794. DROPPED_OUTSIDE_OF_ANY: "droppedOutsideOfAny",
  2795. DRAG_STOPPED: "dragStopped"
  2796. };
  2797. var SOURCES = {
  2798. POINTER: "pointer",
  2799. KEYBOARD: "keyboard"
  2800. };
  2801. var SHADOW_ITEM_MARKER_PROPERTY_NAME = "isDndShadowItem";
  2802. var SHADOW_ELEMENT_ATTRIBUTE_NAME = "data-is-dnd-shadow-item";
  2803. var SHADOW_PLACEHOLDER_ITEM_ID = "id:dnd-shadow-placeholder-0000";
  2804. var DRAGGED_ELEMENT_ID = "dnd-action-dragged-el";
  2805. var ITEM_ID_KEY = "id";
  2806. var activeDndZoneCount = 0;
  2807. function incrementActiveDropZoneCount() {
  2808. activeDndZoneCount++;
  2809. }
  2810. function decrementActiveDropZoneCount() {
  2811. if (activeDndZoneCount === 0) {
  2812. throw new Error("Bug! trying to decrement when there are no dropzones");
  2813. }
  2814. activeDndZoneCount--;
  2815. }
  2816. var isOnServer = typeof window === "undefined";
  2817. // This is based off https://stackoverflow.com/questions/27745438/how-to-compute-getboundingclientrect-without-considering-transforms/57876601#57876601
  2818. // It removes the transforms that are potentially applied by the flip animations
  2819. /**
  2820. * Gets the bounding rect but removes transforms (ex: flip animation)
  2821. * @param {HTMLElement} el
  2822. * @return {{top: number, left: number, bottom: number, right: number}}
  2823. */
  2824. function getBoundingRectNoTransforms(el) {
  2825. var ta;
  2826. var rect = el.getBoundingClientRect();
  2827. var style = getComputedStyle(el);
  2828. var tx = style.transform;
  2829. if (tx) {
  2830. var sx, sy, dx, dy;
  2831. if (tx.startsWith("matrix3d(")) {
  2832. ta = tx.slice(9, -1).split(/, /);
  2833. sx = +ta[0];
  2834. sy = +ta[5];
  2835. dx = +ta[12];
  2836. dy = +ta[13];
  2837. } else if (tx.startsWith("matrix(")) {
  2838. ta = tx.slice(7, -1).split(/, /);
  2839. sx = +ta[0];
  2840. sy = +ta[3];
  2841. dx = +ta[4];
  2842. dy = +ta[5];
  2843. } else {
  2844. return rect;
  2845. }
  2846. var to = style.transformOrigin;
  2847. var x = rect.x - dx - (1 - sx) * parseFloat(to);
  2848. var y = rect.y - dy - (1 - sy) * parseFloat(to.slice(to.indexOf(" ") + 1));
  2849. var w = sx ? rect.width / sx : el.offsetWidth;
  2850. var h = sy ? rect.height / sy : el.offsetHeight;
  2851. return {
  2852. x: x,
  2853. y: y,
  2854. width: w,
  2855. height: h,
  2856. top: y,
  2857. right: x + w,
  2858. bottom: y + h,
  2859. left: x
  2860. };
  2861. } else {
  2862. return rect;
  2863. }
  2864. }
  2865. /**
  2866. * Gets the absolute bounding rect (accounts for the window's scroll position and removes transforms)
  2867. * @param {HTMLElement} el
  2868. * @return {{top: number, left: number, bottom: number, right: number}}
  2869. */
  2870. function getAbsoluteRectNoTransforms(el) {
  2871. var rect = getBoundingRectNoTransforms(el);
  2872. return {
  2873. top: rect.top + window.scrollY,
  2874. bottom: rect.bottom + window.scrollY,
  2875. left: rect.left + window.scrollX,
  2876. right: rect.right + window.scrollX
  2877. };
  2878. }
  2879. /**
  2880. * Gets the absolute bounding rect (accounts for the window's scroll position)
  2881. * @param {HTMLElement} el
  2882. * @return {{top: number, left: number, bottom: number, right: number}}
  2883. */
  2884. function getAbsoluteRect(el) {
  2885. var rect = el.getBoundingClientRect();
  2886. return {
  2887. top: rect.top + window.scrollY,
  2888. bottom: rect.bottom + window.scrollY,
  2889. left: rect.left + window.scrollX,
  2890. right: rect.right + window.scrollX
  2891. };
  2892. }
  2893. /**
  2894. * finds the center :)
  2895. * @typedef {Object} Rect
  2896. * @property {number} top
  2897. * @property {number} bottom
  2898. * @property {number} left
  2899. * @property {number} right
  2900. * @param {Rect} rect
  2901. * @return {{x: number, y: number}}
  2902. */
  2903. function findCenter(rect) {
  2904. return {
  2905. x: (rect.left + rect.right) / 2,
  2906. y: (rect.top + rect.bottom) / 2
  2907. };
  2908. }
  2909. /**
  2910. * @typedef {Object} Point
  2911. * @property {number} x
  2912. * @property {number} y
  2913. * @param {Point} pointA
  2914. * @param {Point} pointB
  2915. * @return {number}
  2916. */
  2917. function calcDistance(pointA, pointB) {
  2918. return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
  2919. }
  2920. /**
  2921. * @param {Point} point
  2922. * @param {Rect} rect
  2923. * @return {boolean|boolean}
  2924. */
  2925. function isPointInsideRect(point, rect) {
  2926. return point.y <= rect.bottom && point.y >= rect.top && point.x >= rect.left && point.x <= rect.right;
  2927. }
  2928. /**
  2929. * find the absolute coordinates of the center of a dom element
  2930. * @param el {HTMLElement}
  2931. * @returns {{x: number, y: number}}
  2932. */
  2933. function findCenterOfElement(el) {
  2934. return findCenter(getAbsoluteRect(el));
  2935. }
  2936. /**
  2937. * @param {HTMLElement} elA
  2938. * @param {HTMLElement} elB
  2939. * @return {boolean}
  2940. */
  2941. function isCenterOfAInsideB(elA, elB) {
  2942. var centerOfA = findCenterOfElement(elA);
  2943. var rectOfB = getAbsoluteRectNoTransforms(elB);
  2944. return isPointInsideRect(centerOfA, rectOfB);
  2945. }
  2946. /**
  2947. * @param {HTMLElement|ChildNode} elA
  2948. * @param {HTMLElement|ChildNode} elB
  2949. * @return {number}
  2950. */
  2951. function calcDistanceBetweenCenters(elA, elB) {
  2952. var centerOfA = findCenterOfElement(elA);
  2953. var centerOfB = findCenterOfElement(elB);
  2954. return calcDistance(centerOfA, centerOfB);
  2955. }
  2956. /**
  2957. * @param {HTMLElement} el - the element to check
  2958. * @returns {boolean} - true if the element in its entirety is off screen including the scrollable area (the normal dom events look at the mouse rather than the element)
  2959. */
  2960. function isElementOffDocument(el) {
  2961. var rect = getAbsoluteRect(el);
  2962. return rect.right < 0 || rect.left > document.documentElement.scrollWidth || rect.bottom < 0 || rect.top > document.documentElement.scrollHeight;
  2963. }
  2964. /**
  2965. * If the point is inside the element returns its distances from the sides, otherwise returns null
  2966. * @param {Point} point
  2967. * @param {HTMLElement} el
  2968. * @return {null|{top: number, left: number, bottom: number, right: number}}
  2969. */
  2970. function calcInnerDistancesBetweenPointAndSidesOfElement(point, el) {
  2971. var rect = getAbsoluteRect(el);
  2972. if (!isPointInsideRect(point, rect)) {
  2973. return null;
  2974. }
  2975. return {
  2976. top: point.y - rect.top,
  2977. bottom: rect.bottom - point.y,
  2978. left: point.x - rect.left,
  2979. // TODO - figure out what is so special about right (why the rect is too big)
  2980. right: Math.min(rect.right, document.documentElement.clientWidth) - point.x
  2981. };
  2982. }
  2983. var dzToShadowIndexToRect;
  2984. /**
  2985. * Resets the cache that allows for smarter "would be index" resolution. Should be called after every drag operation
  2986. */
  2987. function resetIndexesCache() {
  2988. dzToShadowIndexToRect = new Map();
  2989. }
  2990. resetIndexesCache();
  2991. /**
  2992. * Caches the coordinates of the shadow element when it's in a certain index in a certain dropzone.
  2993. * Helpful in order to determine "would be index" more effectively
  2994. * @param {HTMLElement} dz
  2995. * @return {number} - the shadow element index
  2996. */
  2997. function cacheShadowRect(dz) {
  2998. var shadowElIndex = Array.from(dz.children).findIndex(function (child) {
  2999. return child.getAttribute(SHADOW_ELEMENT_ATTRIBUTE_NAME);
  3000. });
  3001. if (shadowElIndex >= 0) {
  3002. if (!dzToShadowIndexToRect.has(dz)) {
  3003. dzToShadowIndexToRect.set(dz, new Map());
  3004. }
  3005. dzToShadowIndexToRect.get(dz).set(shadowElIndex, getAbsoluteRectNoTransforms(dz.children[shadowElIndex]));
  3006. return shadowElIndex;
  3007. }
  3008. return undefined;
  3009. }
  3010. /**
  3011. * @typedef {Object} Index
  3012. * @property {number} index - the would be index
  3013. * @property {boolean} isProximityBased - false if the element is actually over the index, true if it is not over it but this index is the closest
  3014. */
  3015. /**
  3016. * Find the index for the dragged element in the list it is dragged over
  3017. * @param {HTMLElement} floatingAboveEl
  3018. * @param {HTMLElement} collectionBelowEl
  3019. * @returns {Index|null} - if the element is over the container the Index object otherwise null
  3020. */
  3021. function findWouldBeIndex(floatingAboveEl, collectionBelowEl) {
  3022. if (!isCenterOfAInsideB(floatingAboveEl, collectionBelowEl)) {
  3023. return null;
  3024. }
  3025. var children = collectionBelowEl.children; // the container is empty, floating element should be the first
  3026. if (children.length === 0) {
  3027. return {
  3028. index: 0,
  3029. isProximityBased: true
  3030. };
  3031. }
  3032. var shadowElIndex = cacheShadowRect(collectionBelowEl); // the search could be more efficient but keeping it simple for now
  3033. // a possible improvement: pass in the lastIndex it was found in and check there first, then expand from there
  3034. for (var i = 0; i < children.length; i++) {
  3035. if (isCenterOfAInsideB(floatingAboveEl, children[i])) {
  3036. var cachedShadowRect = dzToShadowIndexToRect.has(collectionBelowEl) && dzToShadowIndexToRect.get(collectionBelowEl).get(i);
  3037. if (cachedShadowRect) {
  3038. if (!isPointInsideRect(findCenterOfElement(floatingAboveEl), cachedShadowRect)) {
  3039. return {
  3040. index: shadowElIndex,
  3041. isProximityBased: false
  3042. };
  3043. }
  3044. }
  3045. return {
  3046. index: i,
  3047. isProximityBased: false
  3048. };
  3049. }
  3050. } // this can happen if there is space around the children so the floating element has
  3051. //entered the container but not any of the children, in this case we will find the nearest child
  3052. var minDistanceSoFar = Number.MAX_VALUE;
  3053. var indexOfMin = undefined; // we are checking all of them because we don't know whether we are dealing with a horizontal or vertical container and where the floating element entered from
  3054. for (var _i = 0; _i < children.length; _i++) {
  3055. var distance = calcDistanceBetweenCenters(floatingAboveEl, children[_i]);
  3056. if (distance < minDistanceSoFar) {
  3057. minDistanceSoFar = distance;
  3058. indexOfMin = _i;
  3059. }
  3060. }
  3061. return {
  3062. index: indexOfMin,
  3063. isProximityBased: true
  3064. };
  3065. }
  3066. var SCROLL_ZONE_PX = 25;
  3067. function makeScroller() {
  3068. var scrollingInfo;
  3069. function resetScrolling() {
  3070. scrollingInfo = {
  3071. directionObj: undefined,
  3072. stepPx: 0
  3073. };
  3074. }
  3075. resetScrolling(); // directionObj {x: 0|1|-1, y:0|1|-1} - 1 means down in y and right in x
  3076. function scrollContainer(containerEl) {
  3077. var _scrollingInfo = scrollingInfo,
  3078. directionObj = _scrollingInfo.directionObj,
  3079. stepPx = _scrollingInfo.stepPx;
  3080. if (directionObj) {
  3081. containerEl.scrollBy(directionObj.x * stepPx, directionObj.y * stepPx);
  3082. window.requestAnimationFrame(function () {
  3083. return scrollContainer(containerEl);
  3084. });
  3085. }
  3086. }
  3087. function calcScrollStepPx(distancePx) {
  3088. return SCROLL_ZONE_PX - distancePx;
  3089. }
  3090. /**
  3091. * If the pointer is next to the sides of the element to scroll, will trigger scrolling
  3092. * Can be called repeatedly with updated pointer and elementToScroll values without issues
  3093. * @return {boolean} - true if scrolling was needed
  3094. */
  3095. function scrollIfNeeded(pointer, elementToScroll) {
  3096. if (!elementToScroll) {
  3097. return false;
  3098. }
  3099. var distances = calcInnerDistancesBetweenPointAndSidesOfElement(pointer, elementToScroll);
  3100. if (distances === null) {
  3101. resetScrolling();
  3102. return false;
  3103. }
  3104. var isAlreadyScrolling = !!scrollingInfo.directionObj;
  3105. var scrollingVertically = false,
  3106. scrollingHorizontally = false; // vertical
  3107. if (elementToScroll.scrollHeight > elementToScroll.clientHeight) {
  3108. if (distances.bottom < SCROLL_ZONE_PX) {
  3109. scrollingVertically = true;
  3110. scrollingInfo.directionObj = {
  3111. x: 0,
  3112. y: 1
  3113. };
  3114. scrollingInfo.stepPx = calcScrollStepPx(distances.bottom);
  3115. } else if (distances.top < SCROLL_ZONE_PX) {
  3116. scrollingVertically = true;
  3117. scrollingInfo.directionObj = {
  3118. x: 0,
  3119. y: -1
  3120. };
  3121. scrollingInfo.stepPx = calcScrollStepPx(distances.top);
  3122. }
  3123. if (!isAlreadyScrolling && scrollingVertically) {
  3124. scrollContainer(elementToScroll);
  3125. return true;
  3126. }
  3127. } // horizontal
  3128. if (elementToScroll.scrollWidth > elementToScroll.clientWidth) {
  3129. if (distances.right < SCROLL_ZONE_PX) {
  3130. scrollingHorizontally = true;
  3131. scrollingInfo.directionObj = {
  3132. x: 1,
  3133. y: 0
  3134. };
  3135. scrollingInfo.stepPx = calcScrollStepPx(distances.right);
  3136. } else if (distances.left < SCROLL_ZONE_PX) {
  3137. scrollingHorizontally = true;
  3138. scrollingInfo.directionObj = {
  3139. x: -1,
  3140. y: 0
  3141. };
  3142. scrollingInfo.stepPx = calcScrollStepPx(distances.left);
  3143. }
  3144. if (!isAlreadyScrolling && scrollingHorizontally) {
  3145. scrollContainer(elementToScroll);
  3146. return true;
  3147. }
  3148. }
  3149. resetScrolling();
  3150. return false;
  3151. }
  3152. return {
  3153. scrollIfNeeded: scrollIfNeeded,
  3154. resetScrolling: resetScrolling
  3155. };
  3156. }
  3157. /**
  3158. * @param {Object} object
  3159. * @return {string}
  3160. */
  3161. function toString$1(object) {
  3162. return JSON.stringify(object, null, 2);
  3163. }
  3164. /**
  3165. * Finds the depth of the given node in the DOM tree
  3166. * @param {HTMLElement} node
  3167. * @return {number} - the depth of the node
  3168. */
  3169. function getDepth(node) {
  3170. if (!node) {
  3171. throw new Error("cannot get depth of a falsy node");
  3172. }
  3173. return _getDepth(node, 0);
  3174. }
  3175. function _getDepth(node) {
  3176. var countSoFar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  3177. if (!node.parentElement) {
  3178. return countSoFar - 1;
  3179. }
  3180. return _getDepth(node.parentElement, countSoFar + 1);
  3181. }
  3182. /**
  3183. * A simple util to shallow compare objects quickly, it doesn't validate the arguments so pass objects in
  3184. * @param {Object} objA
  3185. * @param {Object} objB
  3186. * @return {boolean} - true if objA and objB are shallow equal
  3187. */
  3188. function areObjectsShallowEqual(objA, objB) {
  3189. if (Object.keys(objA).length !== Object.keys(objB).length) {
  3190. return false;
  3191. }
  3192. for (var keyA in objA) {
  3193. if (!{}.hasOwnProperty.call(objB, keyA) || objB[keyA] !== objA[keyA]) {
  3194. return false;
  3195. }
  3196. }
  3197. return true;
  3198. }
  3199. /**
  3200. * Shallow compares two arrays
  3201. * @param arrA
  3202. * @param arrB
  3203. * @return {boolean} - whether the arrays are shallow equal
  3204. */
  3205. function areArraysShallowEqualSameOrder(arrA, arrB) {
  3206. if (arrA.length !== arrB.length) {
  3207. return false;
  3208. }
  3209. for (var i = 0; i < arrA.length; i++) {
  3210. if (arrA[i] !== arrB[i]) {
  3211. return false;
  3212. }
  3213. }
  3214. return true;
  3215. }
  3216. var INTERVAL_MS = 200;
  3217. var TOLERANCE_PX = 10;
  3218. var _makeScroller = makeScroller(),
  3219. scrollIfNeeded = _makeScroller.scrollIfNeeded,
  3220. resetScrolling = _makeScroller.resetScrolling;
  3221. var next;
  3222. /**
  3223. * Tracks the dragged elements and performs the side effects when it is dragged over a drop zone (basically dispatching custom-events scrolling)
  3224. * @param {Set<HTMLElement>} dropZones
  3225. * @param {HTMLElement} draggedEl
  3226. * @param {number} [intervalMs = INTERVAL_MS]
  3227. */
  3228. function observe(draggedEl, dropZones) {
  3229. var intervalMs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : INTERVAL_MS;
  3230. // initialization
  3231. var lastDropZoneFound;
  3232. var lastIndexFound;
  3233. var lastIsDraggedInADropZone = false;
  3234. var lastCentrePositionOfDragged; // We are sorting to make sure that in case of nested zones of the same type the one "on top" is considered first
  3235. var dropZonesFromDeepToShallow = Array.from(dropZones).sort(function (dz1, dz2) {
  3236. return getDepth(dz2) - getDepth(dz1);
  3237. });
  3238. /**
  3239. * The main function in this module. Tracks where everything is/ should be a take the actions
  3240. */
  3241. function andNow() {
  3242. var currentCenterOfDragged = findCenterOfElement(draggedEl);
  3243. var scrolled = scrollIfNeeded(currentCenterOfDragged, lastDropZoneFound); // we only want to make a new decision after the element was moved a bit to prevent flickering
  3244. if (!scrolled && lastCentrePositionOfDragged && Math.abs(lastCentrePositionOfDragged.x - currentCenterOfDragged.x) < TOLERANCE_PX && Math.abs(lastCentrePositionOfDragged.y - currentCenterOfDragged.y) < TOLERANCE_PX) {
  3245. next = window.setTimeout(andNow, intervalMs);
  3246. return;
  3247. }
  3248. if (isElementOffDocument(draggedEl)) {
  3249. dispatchDraggedLeftDocument(draggedEl);
  3250. return;
  3251. }
  3252. lastCentrePositionOfDragged = currentCenterOfDragged; // this is a simple algorithm, potential improvement: first look at lastDropZoneFound
  3253. var isDraggedInADropZone = false;
  3254. var _iterator = _createForOfIteratorHelper(dropZonesFromDeepToShallow),
  3255. _step;
  3256. try {
  3257. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3258. var dz = _step.value;
  3259. var indexObj = findWouldBeIndex(draggedEl, dz);
  3260. if (indexObj === null) {
  3261. // it is not inside
  3262. continue;
  3263. }
  3264. var index = indexObj.index;
  3265. isDraggedInADropZone = true; // the element is over a container
  3266. if (dz !== lastDropZoneFound) {
  3267. lastDropZoneFound && dispatchDraggedElementLeftContainerForAnother(lastDropZoneFound, draggedEl, dz);
  3268. dispatchDraggedElementEnteredContainer(dz, indexObj, draggedEl);
  3269. lastDropZoneFound = dz;
  3270. } else if (index !== lastIndexFound) {
  3271. dispatchDraggedElementIsOverIndex(dz, indexObj, draggedEl);
  3272. lastIndexFound = index;
  3273. } // we handle looping with the 'continue' statement above
  3274. break;
  3275. } // the first time the dragged element is not in any dropzone we need to notify the last dropzone it was in
  3276. } catch (err) {
  3277. _iterator.e(err);
  3278. } finally {
  3279. _iterator.f();
  3280. }
  3281. if (!isDraggedInADropZone && lastIsDraggedInADropZone && lastDropZoneFound) {
  3282. dispatchDraggedElementLeftContainerForNone(lastDropZoneFound, draggedEl);
  3283. lastDropZoneFound = undefined;
  3284. lastIndexFound = undefined;
  3285. lastIsDraggedInADropZone = false;
  3286. } else {
  3287. lastIsDraggedInADropZone = true;
  3288. }
  3289. next = window.setTimeout(andNow, intervalMs);
  3290. }
  3291. andNow();
  3292. } // assumption - we can only observe one dragged element at a time, this could be changed in the future
  3293. function unobserve() {
  3294. clearTimeout(next);
  3295. resetScrolling();
  3296. resetIndexesCache();
  3297. }
  3298. var INTERVAL_MS$1 = 300;
  3299. var mousePosition;
  3300. /**
  3301. * Do not use this! it is visible for testing only until we get over the issue Cypress not triggering the mousemove listeners
  3302. * // TODO - make private (remove export)
  3303. * @param {{clientX: number, clientY: number}} e
  3304. */
  3305. function updateMousePosition(e) {
  3306. var c = e.touches ? e.touches[0] : e;
  3307. mousePosition = {
  3308. x: c.clientX,
  3309. y: c.clientY
  3310. };
  3311. }
  3312. var _makeScroller$1 = makeScroller(),
  3313. scrollIfNeeded$1 = _makeScroller$1.scrollIfNeeded,
  3314. resetScrolling$1 = _makeScroller$1.resetScrolling;
  3315. var next$1;
  3316. function loop() {
  3317. if (mousePosition) {
  3318. scrollIfNeeded$1(mousePosition, document.documentElement);
  3319. }
  3320. next$1 = window.setTimeout(loop, INTERVAL_MS$1);
  3321. }
  3322. /**
  3323. * will start watching the mouse pointer and scroll the window if it goes next to the edges
  3324. */
  3325. function armWindowScroller() {
  3326. window.addEventListener("mousemove", updateMousePosition);
  3327. window.addEventListener("touchmove", updateMousePosition);
  3328. loop();
  3329. }
  3330. /**
  3331. * will stop watching the mouse pointer and won't scroll the window anymore
  3332. */
  3333. function disarmWindowScroller() {
  3334. window.removeEventListener("mousemove", updateMousePosition);
  3335. window.removeEventListener("touchmove", updateMousePosition);
  3336. mousePosition = undefined;
  3337. window.clearTimeout(next$1);
  3338. resetScrolling$1();
  3339. }
  3340. var TRANSITION_DURATION_SECONDS = 0.2;
  3341. /**
  3342. * private helper function - creates a transition string for a property
  3343. * @param {string} property
  3344. * @return {string} - the transition string
  3345. */
  3346. function trs(property) {
  3347. return "".concat(property, " ").concat(TRANSITION_DURATION_SECONDS, "s ease");
  3348. }
  3349. /**
  3350. * clones the given element and applies proper styles and transitions to the dragged element
  3351. * @param {HTMLElement} originalElement
  3352. * @param {Point} [positionCenterOnXY]
  3353. * @return {Node} - the cloned, styled element
  3354. */
  3355. function createDraggedElementFrom(originalElement, positionCenterOnXY) {
  3356. var rect = originalElement.getBoundingClientRect();
  3357. var draggedEl = originalElement.cloneNode(true);
  3358. copyStylesFromTo(originalElement, draggedEl);
  3359. draggedEl.id = DRAGGED_ELEMENT_ID;
  3360. draggedEl.style.position = "fixed";
  3361. var elTopPx = rect.top;
  3362. var elLeftPx = rect.left;
  3363. draggedEl.style.top = "".concat(elTopPx, "px");
  3364. draggedEl.style.left = "".concat(elLeftPx, "px");
  3365. if (positionCenterOnXY) {
  3366. var center = findCenter(rect);
  3367. elTopPx -= center.y - positionCenterOnXY.y;
  3368. elLeftPx -= center.x - positionCenterOnXY.x;
  3369. window.setTimeout(function () {
  3370. draggedEl.style.top = "".concat(elTopPx, "px");
  3371. draggedEl.style.left = "".concat(elLeftPx, "px");
  3372. }, 0);
  3373. }
  3374. draggedEl.style.margin = "0"; // we can't have relative or automatic height and width or it will break the illusion
  3375. draggedEl.style.boxSizing = "border-box";
  3376. draggedEl.style.height = "".concat(rect.height, "px");
  3377. draggedEl.style.width = "".concat(rect.width, "px");
  3378. draggedEl.style.transition = "".concat(trs("top"), ", ").concat(trs("left"), ", ").concat(trs("background-color"), ", ").concat(trs("opacity"), ", ").concat(trs("color"), " "); // this is a workaround for a strange browser bug that causes the right border to disappear when all the transitions are added at the same time
  3379. window.setTimeout(function () {
  3380. return draggedEl.style.transition += ", ".concat(trs("width"), ", ").concat(trs("height"));
  3381. }, 0);
  3382. draggedEl.style.zIndex = "9999";
  3383. draggedEl.style.cursor = "grabbing";
  3384. return draggedEl;
  3385. }
  3386. /**
  3387. * styles the dragged element to a 'dropped' state
  3388. * @param {HTMLElement} draggedEl
  3389. */
  3390. function moveDraggedElementToWasDroppedState(draggedEl) {
  3391. draggedEl.style.cursor = "grab";
  3392. }
  3393. /**
  3394. * Morphs the dragged element style, maintains the mouse pointer within the element
  3395. * @param {HTMLElement} draggedEl
  3396. * @param {HTMLElement} copyFromEl - the element the dragged element should look like, typically the shadow element
  3397. * @param {number} currentMouseX
  3398. * @param {number} currentMouseY
  3399. * @param {function} transformDraggedElement - function to transform the dragged element, does nothing by default.
  3400. */
  3401. function morphDraggedElementToBeLike(draggedEl, copyFromEl, currentMouseX, currentMouseY, transformDraggedElement) {
  3402. var newRect = copyFromEl.getBoundingClientRect();
  3403. var draggedElRect = draggedEl.getBoundingClientRect();
  3404. var widthChange = newRect.width - draggedElRect.width;
  3405. var heightChange = newRect.height - draggedElRect.height;
  3406. if (widthChange || heightChange) {
  3407. var relativeDistanceOfMousePointerFromDraggedSides = {
  3408. left: (currentMouseX - draggedElRect.left) / draggedElRect.width,
  3409. top: (currentMouseY - draggedElRect.top) / draggedElRect.height
  3410. };
  3411. draggedEl.style.height = "".concat(newRect.height, "px");
  3412. draggedEl.style.width = "".concat(newRect.width, "px");
  3413. draggedEl.style.left = "".concat(parseFloat(draggedEl.style.left) - relativeDistanceOfMousePointerFromDraggedSides.left * widthChange, "px");
  3414. draggedEl.style.top = "".concat(parseFloat(draggedEl.style.top) - relativeDistanceOfMousePointerFromDraggedSides.top * heightChange, "px");
  3415. } /// other properties
  3416. copyStylesFromTo(copyFromEl, draggedEl);
  3417. transformDraggedElement();
  3418. }
  3419. /**
  3420. * @param {HTMLElement} copyFromEl
  3421. * @param {HTMLElement} copyToEl
  3422. */
  3423. function copyStylesFromTo(copyFromEl, copyToEl) {
  3424. var computedStyle = window.getComputedStyle(copyFromEl);
  3425. Array.from(computedStyle).filter(function (s) {
  3426. return s.startsWith("background") || s.startsWith("padding") || s.startsWith("font") || s.startsWith("text") || s.startsWith("align") || s.startsWith("justify") || s.startsWith("display") || s.startsWith("flex") || s.startsWith("border") || s === "opacity" || s === "color" || s === "list-style-type";
  3427. }).forEach(function (s) {
  3428. return copyToEl.style.setProperty(s, computedStyle.getPropertyValue(s), computedStyle.getPropertyPriority(s));
  3429. });
  3430. }
  3431. /**
  3432. * makes the element compatible with being draggable
  3433. * @param {HTMLElement} draggableEl
  3434. * @param {boolean} dragDisabled
  3435. */
  3436. function styleDraggable(draggableEl, dragDisabled) {
  3437. draggableEl.draggable = false;
  3438. draggableEl.ondragstart = function () {
  3439. return false;
  3440. };
  3441. if (!dragDisabled) {
  3442. draggableEl.style.userSelect = "none";
  3443. draggableEl.style.WebkitUserSelect = "none";
  3444. draggableEl.style.cursor = "grab";
  3445. } else {
  3446. draggableEl.style.userSelect = "";
  3447. draggableEl.style.WebkitUserSelect = "";
  3448. draggableEl.style.cursor = "";
  3449. }
  3450. }
  3451. /**
  3452. * Hides the provided element so that it can stay in the dom without interrupting
  3453. * @param {HTMLElement} dragTarget
  3454. */
  3455. function hideOriginalDragTarget(dragTarget) {
  3456. dragTarget.style.display = "none";
  3457. dragTarget.style.position = "fixed";
  3458. dragTarget.style.zIndex = "-5";
  3459. }
  3460. /**
  3461. * styles the shadow element
  3462. * @param {HTMLElement} shadowEl
  3463. */
  3464. function decorateShadowEl(shadowEl) {
  3465. shadowEl.style.visibility = "hidden";
  3466. shadowEl.setAttribute(SHADOW_ELEMENT_ATTRIBUTE_NAME, "true");
  3467. }
  3468. /**
  3469. * undo the styles the shadow element
  3470. * @param {HTMLElement} shadowEl
  3471. */
  3472. function unDecorateShadowElement(shadowEl) {
  3473. shadowEl.style.visibility = "";
  3474. shadowEl.removeAttribute(SHADOW_ELEMENT_ATTRIBUTE_NAME);
  3475. }
  3476. /**
  3477. * will mark the given dropzones as visually active
  3478. * @param {Array<HTMLElement>} dropZones
  3479. * @param {Function} getStyles - maps a dropzone to a styles object (so the styles can be removed)
  3480. * @param {Function} getClasses - maps a dropzone to a classList
  3481. */
  3482. function styleActiveDropZones(dropZones) {
  3483. var getStyles = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
  3484. var getClasses = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {
  3485. return [];
  3486. };
  3487. dropZones.forEach(function (dz) {
  3488. var styles = getStyles(dz);
  3489. Object.keys(styles).forEach(function (style) {
  3490. dz.style[style] = styles[style];
  3491. });
  3492. getClasses(dz).forEach(function (c) {
  3493. return dz.classList.add(c);
  3494. });
  3495. });
  3496. }
  3497. /**
  3498. * will remove the 'active' styling from given dropzones
  3499. * @param {Array<HTMLElement>} dropZones
  3500. * @param {Function} getStyles - maps a dropzone to a styles object
  3501. * @param {Function} getClasses - maps a dropzone to a classList
  3502. */
  3503. function styleInactiveDropZones(dropZones) {
  3504. var getStyles = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
  3505. var getClasses = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {
  3506. return [];
  3507. };
  3508. dropZones.forEach(function (dz) {
  3509. var styles = getStyles(dz);
  3510. Object.keys(styles).forEach(function (style) {
  3511. dz.style[style] = "";
  3512. });
  3513. getClasses(dz).forEach(function (c) {
  3514. return dz.classList.contains(c) && dz.classList.remove(c);
  3515. });
  3516. });
  3517. }
  3518. /**
  3519. * will prevent the provided element from shrinking by setting its minWidth and minHeight to the current width and height values
  3520. * @param {HTMLElement} el
  3521. * @return {function(): void} - run this function to undo the operation and restore the original values
  3522. */
  3523. function preventShrinking(el) {
  3524. var originalMinHeight = el.style.minHeight;
  3525. el.style.minHeight = window.getComputedStyle(el).getPropertyValue("height");
  3526. var originalMinWidth = el.style.minWidth;
  3527. el.style.minWidth = window.getComputedStyle(el).getPropertyValue("width");
  3528. return function undo() {
  3529. el.style.minHeight = originalMinHeight;
  3530. el.style.minWidth = originalMinWidth;
  3531. };
  3532. }
  3533. var DEFAULT_DROP_ZONE_TYPE = "--any--";
  3534. var MIN_OBSERVATION_INTERVAL_MS = 100;
  3535. var MIN_MOVEMENT_BEFORE_DRAG_START_PX = 3;
  3536. var DEFAULT_DROP_TARGET_STYLE = {
  3537. outline: "rgba(255, 255, 102, 0.7) solid 2px"
  3538. };
  3539. var originalDragTarget;
  3540. var draggedEl;
  3541. var draggedElData;
  3542. var draggedElType;
  3543. var originDropZone;
  3544. var originIndex;
  3545. var shadowElData;
  3546. var shadowElDropZone;
  3547. var dragStartMousePosition;
  3548. var currentMousePosition;
  3549. var isWorkingOnPreviousDrag = false;
  3550. var finalizingPreviousDrag = false;
  3551. var unlockOriginDzMinDimensions;
  3552. var isDraggedOutsideOfAnyDz = false; // a map from type to a set of drop-zones
  3553. var typeToDropZones = new Map(); // important - this is needed because otherwise the config that would be used for everyone is the config of the element that created the event listeners
  3554. var dzToConfig = new Map(); // this is needed in order to be able to cleanup old listeners and avoid stale closures issues (as the listener is defined within each zone)
  3555. var elToMouseDownListener = new WeakMap();
  3556. /* drop-zones registration management */
  3557. function registerDropZone(dropZoneEl, type) {
  3558. if (!typeToDropZones.has(type)) {
  3559. typeToDropZones.set(type, new Set());
  3560. }
  3561. if (!typeToDropZones.get(type).has(dropZoneEl)) {
  3562. typeToDropZones.get(type).add(dropZoneEl);
  3563. incrementActiveDropZoneCount();
  3564. }
  3565. }
  3566. function unregisterDropZone(dropZoneEl, type) {
  3567. typeToDropZones.get(type)["delete"](dropZoneEl);
  3568. decrementActiveDropZoneCount();
  3569. if (typeToDropZones.get(type).size === 0) {
  3570. typeToDropZones["delete"](type);
  3571. }
  3572. }
  3573. /* functions to manage observing the dragged element and trigger custom drag-events */
  3574. function watchDraggedElement() {
  3575. armWindowScroller();
  3576. var dropZones = typeToDropZones.get(draggedElType);
  3577. var _iterator = _createForOfIteratorHelper(dropZones),
  3578. _step;
  3579. try {
  3580. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  3581. var dz = _step.value;
  3582. dz.addEventListener(DRAGGED_ENTERED_EVENT_NAME, handleDraggedEntered);
  3583. dz.addEventListener(DRAGGED_LEFT_EVENT_NAME, handleDraggedLeft);
  3584. dz.addEventListener(DRAGGED_OVER_INDEX_EVENT_NAME, handleDraggedIsOverIndex);
  3585. }
  3586. } catch (err) {
  3587. _iterator.e(err);
  3588. } finally {
  3589. _iterator.f();
  3590. }
  3591. window.addEventListener(DRAGGED_LEFT_DOCUMENT_EVENT_NAME, handleDrop); // it is important that we don't have an interval that is faster than the flip duration because it can cause elements to jump bach and forth
  3592. var observationIntervalMs = Math.max.apply(Math, [MIN_OBSERVATION_INTERVAL_MS].concat(_toConsumableArray(Array.from(dropZones.keys()).map(function (dz) {
  3593. return dzToConfig.get(dz).dropAnimationDurationMs;
  3594. }))));
  3595. observe(draggedEl, dropZones, observationIntervalMs * 1.07);
  3596. }
  3597. function unWatchDraggedElement() {
  3598. disarmWindowScroller();
  3599. var dropZones = typeToDropZones.get(draggedElType);
  3600. var _iterator2 = _createForOfIteratorHelper(dropZones),
  3601. _step2;
  3602. try {
  3603. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  3604. var dz = _step2.value;
  3605. dz.removeEventListener(DRAGGED_ENTERED_EVENT_NAME, handleDraggedEntered);
  3606. dz.removeEventListener(DRAGGED_LEFT_EVENT_NAME, handleDraggedLeft);
  3607. dz.removeEventListener(DRAGGED_OVER_INDEX_EVENT_NAME, handleDraggedIsOverIndex);
  3608. }
  3609. } catch (err) {
  3610. _iterator2.e(err);
  3611. } finally {
  3612. _iterator2.f();
  3613. }
  3614. window.removeEventListener(DRAGGED_LEFT_DOCUMENT_EVENT_NAME, handleDrop);
  3615. unobserve();
  3616. } // finds the initial placeholder that is placed there on drag start
  3617. function findShadowPlaceHolderIdx(items) {
  3618. return items.findIndex(function (item) {
  3619. return item[ITEM_ID_KEY] === SHADOW_PLACEHOLDER_ITEM_ID;
  3620. });
  3621. }
  3622. function findShadowElementIdx(items) {
  3623. // checking that the id is not the placeholder's for Dragula like usecases
  3624. return items.findIndex(function (item) {
  3625. return !!item[SHADOW_ITEM_MARKER_PROPERTY_NAME] && item[ITEM_ID_KEY] !== SHADOW_PLACEHOLDER_ITEM_ID;
  3626. });
  3627. }
  3628. /* custom drag-events handlers */
  3629. function handleDraggedEntered(e) {
  3630. var _dzToConfig$get = dzToConfig.get(e.currentTarget),
  3631. items = _dzToConfig$get.items,
  3632. dropFromOthersDisabled = _dzToConfig$get.dropFromOthersDisabled;
  3633. if (dropFromOthersDisabled && e.currentTarget !== originDropZone) {
  3634. return;
  3635. }
  3636. isDraggedOutsideOfAnyDz = false; // this deals with another race condition. in rare occasions (super rapid operations) the list hasn't updated yet
  3637. items = items.filter(function (item) {
  3638. return item[ITEM_ID_KEY] !== shadowElData[ITEM_ID_KEY];
  3639. });
  3640. if (originDropZone !== e.currentTarget) {
  3641. var originZoneItems = dzToConfig.get(originDropZone).items;
  3642. var newOriginZoneItems = originZoneItems.filter(function (item) {
  3643. return !item[SHADOW_ITEM_MARKER_PROPERTY_NAME];
  3644. });
  3645. dispatchConsiderEvent(originDropZone, newOriginZoneItems, {
  3646. trigger: TRIGGERS.DRAGGED_ENTERED_ANOTHER,
  3647. id: draggedElData[ITEM_ID_KEY],
  3648. source: SOURCES.POINTER
  3649. });
  3650. } else {
  3651. var shadowPlaceHolderIdx = findShadowPlaceHolderIdx(items);
  3652. if (shadowPlaceHolderIdx !== -1) {
  3653. items.splice(shadowPlaceHolderIdx, 1);
  3654. }
  3655. }
  3656. var _e$detail$indexObj = e.detail.indexObj,
  3657. index = _e$detail$indexObj.index,
  3658. isProximityBased = _e$detail$indexObj.isProximityBased;
  3659. var shadowElIdx = isProximityBased && index === e.currentTarget.children.length - 1 ? index + 1 : index;
  3660. shadowElDropZone = e.currentTarget;
  3661. items.splice(shadowElIdx, 0, shadowElData);
  3662. dispatchConsiderEvent(e.currentTarget, items, {
  3663. trigger: TRIGGERS.DRAGGED_ENTERED,
  3664. id: draggedElData[ITEM_ID_KEY],
  3665. source: SOURCES.POINTER
  3666. });
  3667. }
  3668. function handleDraggedLeft(e) {
  3669. // dealing with a rare race condition on extremely rapid clicking and dropping
  3670. if (!isWorkingOnPreviousDrag) return;
  3671. var _dzToConfig$get2 = dzToConfig.get(e.currentTarget),
  3672. items = _dzToConfig$get2.items,
  3673. dropFromOthersDisabled = _dzToConfig$get2.dropFromOthersDisabled;
  3674. if (dropFromOthersDisabled && e.currentTarget !== originDropZone && e.currentTarget !== shadowElDropZone) {
  3675. return;
  3676. }
  3677. var shadowElIdx = findShadowElementIdx(items);
  3678. var shadowItem = items.splice(shadowElIdx, 1)[0];
  3679. shadowElDropZone = undefined;
  3680. var _e$detail = e.detail,
  3681. type = _e$detail.type,
  3682. theOtherDz = _e$detail.theOtherDz;
  3683. if (type === DRAGGED_LEFT_TYPES.OUTSIDE_OF_ANY || type === DRAGGED_LEFT_TYPES.LEFT_FOR_ANOTHER && theOtherDz !== originDropZone && dzToConfig.get(theOtherDz).dropFromOthersDisabled) {
  3684. isDraggedOutsideOfAnyDz = true;
  3685. shadowElDropZone = originDropZone;
  3686. var originZoneItems = dzToConfig.get(originDropZone).items;
  3687. originZoneItems.splice(originIndex, 0, shadowItem);
  3688. dispatchConsiderEvent(originDropZone, originZoneItems, {
  3689. trigger: TRIGGERS.DRAGGED_LEFT_ALL,
  3690. id: draggedElData[ITEM_ID_KEY],
  3691. source: SOURCES.POINTER
  3692. });
  3693. } // for the origin dz, when the dragged is outside of any, this will be fired in addition to the previous. this is for simplicity
  3694. dispatchConsiderEvent(e.currentTarget, items, {
  3695. trigger: TRIGGERS.DRAGGED_LEFT,
  3696. id: draggedElData[ITEM_ID_KEY],
  3697. source: SOURCES.POINTER
  3698. });
  3699. }
  3700. function handleDraggedIsOverIndex(e) {
  3701. var _dzToConfig$get3 = dzToConfig.get(e.currentTarget),
  3702. items = _dzToConfig$get3.items,
  3703. dropFromOthersDisabled = _dzToConfig$get3.dropFromOthersDisabled;
  3704. if (dropFromOthersDisabled && e.currentTarget !== originDropZone) {
  3705. return;
  3706. }
  3707. isDraggedOutsideOfAnyDz = false;
  3708. var index = e.detail.indexObj.index;
  3709. var shadowElIdx = findShadowElementIdx(items);
  3710. items.splice(shadowElIdx, 1);
  3711. items.splice(index, 0, shadowElData);
  3712. dispatchConsiderEvent(e.currentTarget, items, {
  3713. trigger: TRIGGERS.DRAGGED_OVER_INDEX,
  3714. id: draggedElData[ITEM_ID_KEY],
  3715. source: SOURCES.POINTER
  3716. });
  3717. } // Global mouse/touch-events handlers
  3718. function handleMouseMove(e) {
  3719. e.preventDefault();
  3720. var c = e.touches ? e.touches[0] : e;
  3721. currentMousePosition = {
  3722. x: c.clientX,
  3723. y: c.clientY
  3724. };
  3725. draggedEl.style.transform = "translate3d(".concat(currentMousePosition.x - dragStartMousePosition.x, "px, ").concat(currentMousePosition.y - dragStartMousePosition.y, "px, 0)");
  3726. }
  3727. function handleDrop() {
  3728. finalizingPreviousDrag = true; // cleanup
  3729. window.removeEventListener("mousemove", handleMouseMove);
  3730. window.removeEventListener("touchmove", handleMouseMove);
  3731. window.removeEventListener("mouseup", handleDrop);
  3732. window.removeEventListener("touchend", handleDrop);
  3733. unWatchDraggedElement();
  3734. moveDraggedElementToWasDroppedState(draggedEl);
  3735. if (!shadowElDropZone) {
  3736. shadowElDropZone = originDropZone;
  3737. }
  3738. var _dzToConfig$get4 = dzToConfig.get(shadowElDropZone),
  3739. items = _dzToConfig$get4.items,
  3740. type = _dzToConfig$get4.type;
  3741. styleInactiveDropZones(typeToDropZones.get(type), function (dz) {
  3742. return dzToConfig.get(dz).dropTargetStyle;
  3743. }, function (dz) {
  3744. return dzToConfig.get(dz).dropTargetClasses;
  3745. });
  3746. var shadowElIdx = findShadowElementIdx(items); // the handler might remove the shadow element, ex: dragula like copy on drag
  3747. if (shadowElIdx === -1) shadowElIdx = originIndex;
  3748. items = items.map(function (item) {
  3749. return item[SHADOW_ITEM_MARKER_PROPERTY_NAME] ? draggedElData : item;
  3750. });
  3751. function finalizeWithinZone() {
  3752. unlockOriginDzMinDimensions();
  3753. dispatchFinalizeEvent(shadowElDropZone, items, {
  3754. trigger: isDraggedOutsideOfAnyDz ? TRIGGERS.DROPPED_OUTSIDE_OF_ANY : TRIGGERS.DROPPED_INTO_ZONE,
  3755. id: draggedElData[ITEM_ID_KEY],
  3756. source: SOURCES.POINTER
  3757. });
  3758. if (shadowElDropZone !== originDropZone) {
  3759. // letting the origin drop zone know the element was permanently taken away
  3760. dispatchFinalizeEvent(originDropZone, dzToConfig.get(originDropZone).items, {
  3761. trigger: TRIGGERS.DROPPED_INTO_ANOTHER,
  3762. id: draggedElData[ITEM_ID_KEY],
  3763. source: SOURCES.POINTER
  3764. });
  3765. }
  3766. unDecorateShadowElement(shadowElDropZone.children[shadowElIdx]);
  3767. cleanupPostDrop();
  3768. }
  3769. animateDraggedToFinalPosition(shadowElIdx, finalizeWithinZone);
  3770. } // helper function for handleDrop
  3771. function animateDraggedToFinalPosition(shadowElIdx, callback) {
  3772. var shadowElRect = getBoundingRectNoTransforms(shadowElDropZone.children[shadowElIdx]);
  3773. var newTransform = {
  3774. x: shadowElRect.left - parseFloat(draggedEl.style.left),
  3775. y: shadowElRect.top - parseFloat(draggedEl.style.top)
  3776. };
  3777. var _dzToConfig$get5 = dzToConfig.get(shadowElDropZone),
  3778. dropAnimationDurationMs = _dzToConfig$get5.dropAnimationDurationMs;
  3779. var transition = "transform ".concat(dropAnimationDurationMs, "ms ease");
  3780. draggedEl.style.transition = draggedEl.style.transition ? draggedEl.style.transition + "," + transition : transition;
  3781. draggedEl.style.transform = "translate3d(".concat(newTransform.x, "px, ").concat(newTransform.y, "px, 0)");
  3782. window.setTimeout(callback, dropAnimationDurationMs);
  3783. }
  3784. /* cleanup */
  3785. function cleanupPostDrop() {
  3786. draggedEl.remove();
  3787. originalDragTarget.remove();
  3788. draggedEl = undefined;
  3789. originalDragTarget = undefined;
  3790. draggedElData = undefined;
  3791. draggedElType = undefined;
  3792. originDropZone = undefined;
  3793. originIndex = undefined;
  3794. shadowElData = undefined;
  3795. shadowElDropZone = undefined;
  3796. dragStartMousePosition = undefined;
  3797. currentMousePosition = undefined;
  3798. isWorkingOnPreviousDrag = false;
  3799. finalizingPreviousDrag = false;
  3800. unlockOriginDzMinDimensions = undefined;
  3801. isDraggedOutsideOfAnyDz = false;
  3802. }
  3803. function dndzone(node, options) {
  3804. var config = {
  3805. items: undefined,
  3806. type: undefined,
  3807. flipDurationMs: 0,
  3808. dragDisabled: false,
  3809. morphDisabled: false,
  3810. dropFromOthersDisabled: false,
  3811. dropTargetStyle: DEFAULT_DROP_TARGET_STYLE,
  3812. dropTargetClasses: [],
  3813. transformDraggedElement: function transformDraggedElement() {},
  3814. centreDraggedOnCursor: false
  3815. };
  3816. var elToIdx = new Map();
  3817. function addMaybeListeners() {
  3818. window.addEventListener("mousemove", handleMouseMoveMaybeDragStart, {
  3819. passive: false
  3820. });
  3821. window.addEventListener("touchmove", handleMouseMoveMaybeDragStart, {
  3822. passive: false,
  3823. capture: false
  3824. });
  3825. window.addEventListener("mouseup", handleFalseAlarm, {
  3826. passive: false
  3827. });
  3828. window.addEventListener("touchend", handleFalseAlarm, {
  3829. passive: false
  3830. });
  3831. }
  3832. function removeMaybeListeners() {
  3833. window.removeEventListener("mousemove", handleMouseMoveMaybeDragStart);
  3834. window.removeEventListener("touchmove", handleMouseMoveMaybeDragStart);
  3835. window.removeEventListener("mouseup", handleFalseAlarm);
  3836. window.removeEventListener("touchend", handleFalseAlarm);
  3837. }
  3838. function handleFalseAlarm() {
  3839. removeMaybeListeners();
  3840. originalDragTarget = undefined;
  3841. dragStartMousePosition = undefined;
  3842. currentMousePosition = undefined;
  3843. }
  3844. function handleMouseMoveMaybeDragStart(e) {
  3845. e.preventDefault();
  3846. var c = e.touches ? e.touches[0] : e;
  3847. currentMousePosition = {
  3848. x: c.clientX,
  3849. y: c.clientY
  3850. };
  3851. if (Math.abs(currentMousePosition.x - dragStartMousePosition.x) >= MIN_MOVEMENT_BEFORE_DRAG_START_PX || Math.abs(currentMousePosition.y - dragStartMousePosition.y) >= MIN_MOVEMENT_BEFORE_DRAG_START_PX) {
  3852. removeMaybeListeners();
  3853. handleDragStart();
  3854. }
  3855. }
  3856. function handleMouseDown(e) {
  3857. // on safari clicking on a select element doesn't fire mouseup at the end of the click and in general this makes more sense
  3858. if (e.target !== e.currentTarget && (e.target.value !== undefined || e.target.isContentEditable)) {
  3859. return;
  3860. } // prevents responding to any button but left click which equals 0 (which is falsy)
  3861. if (e.button) {
  3862. return;
  3863. }
  3864. if (isWorkingOnPreviousDrag) {
  3865. return;
  3866. }
  3867. e.stopPropagation();
  3868. var c = e.touches ? e.touches[0] : e;
  3869. dragStartMousePosition = {
  3870. x: c.clientX,
  3871. y: c.clientY
  3872. };
  3873. currentMousePosition = _objectSpread2({}, dragStartMousePosition);
  3874. originalDragTarget = e.currentTarget;
  3875. addMaybeListeners();
  3876. }
  3877. function handleDragStart() {
  3878. isWorkingOnPreviousDrag = true; // initialising globals
  3879. var currentIdx = elToIdx.get(originalDragTarget);
  3880. originIndex = currentIdx;
  3881. originDropZone = originalDragTarget.parentElement;
  3882. var items = config.items,
  3883. type = config.type,
  3884. centreDraggedOnCursor = config.centreDraggedOnCursor;
  3885. draggedElData = _objectSpread2({}, items[currentIdx]);
  3886. draggedElType = type;
  3887. shadowElData = _objectSpread2(_objectSpread2({}, draggedElData), {}, _defineProperty({}, SHADOW_ITEM_MARKER_PROPERTY_NAME, true)); // The initial shadow element. We need a different id at first in order to avoid conflicts and timing issues
  3888. var placeHolderElData = _objectSpread2(_objectSpread2({}, shadowElData), {}, _defineProperty({}, ITEM_ID_KEY, SHADOW_PLACEHOLDER_ITEM_ID)); // creating the draggable element
  3889. draggedEl = createDraggedElementFrom(originalDragTarget, centreDraggedOnCursor && currentMousePosition); // We will keep the original dom node in the dom because touch events keep firing on it, we want to re-add it after the framework removes it
  3890. function keepOriginalElementInDom() {
  3891. if (!draggedEl.parentElement) {
  3892. document.body.appendChild(draggedEl); // to prevent the outline from disappearing
  3893. draggedEl.focus();
  3894. watchDraggedElement();
  3895. hideOriginalDragTarget(originalDragTarget);
  3896. document.body.appendChild(originalDragTarget);
  3897. } else {
  3898. window.requestAnimationFrame(keepOriginalElementInDom);
  3899. }
  3900. }
  3901. window.requestAnimationFrame(keepOriginalElementInDom);
  3902. styleActiveDropZones(Array.from(typeToDropZones.get(config.type)).filter(function (dz) {
  3903. return dz === originDropZone || !dzToConfig.get(dz).dropFromOthersDisabled;
  3904. }), function (dz) {
  3905. return dzToConfig.get(dz).dropTargetStyle;
  3906. }, function (dz) {
  3907. return dzToConfig.get(dz).dropTargetClasses;
  3908. }); // removing the original element by removing its data entry
  3909. items.splice(currentIdx, 1, placeHolderElData);
  3910. unlockOriginDzMinDimensions = preventShrinking(originDropZone);
  3911. dispatchConsiderEvent(originDropZone, items, {
  3912. trigger: TRIGGERS.DRAG_STARTED,
  3913. id: draggedElData[ITEM_ID_KEY],
  3914. source: SOURCES.POINTER
  3915. }); // handing over to global handlers - starting to watch the element
  3916. window.addEventListener("mousemove", handleMouseMove, {
  3917. passive: false
  3918. });
  3919. window.addEventListener("touchmove", handleMouseMove, {
  3920. passive: false,
  3921. capture: false
  3922. });
  3923. window.addEventListener("mouseup", handleDrop, {
  3924. passive: false
  3925. });
  3926. window.addEventListener("touchend", handleDrop, {
  3927. passive: false
  3928. });
  3929. }
  3930. function configure(_ref) {
  3931. var _ref$items = _ref.items,
  3932. items = _ref$items === void 0 ? undefined : _ref$items,
  3933. _ref$flipDurationMs = _ref.flipDurationMs,
  3934. dropAnimationDurationMs = _ref$flipDurationMs === void 0 ? 0 : _ref$flipDurationMs,
  3935. _ref$type = _ref.type,
  3936. newType = _ref$type === void 0 ? DEFAULT_DROP_ZONE_TYPE : _ref$type,
  3937. _ref$dragDisabled = _ref.dragDisabled,
  3938. dragDisabled = _ref$dragDisabled === void 0 ? false : _ref$dragDisabled,
  3939. _ref$morphDisabled = _ref.morphDisabled,
  3940. morphDisabled = _ref$morphDisabled === void 0 ? false : _ref$morphDisabled,
  3941. _ref$dropFromOthersDi = _ref.dropFromOthersDisabled,
  3942. dropFromOthersDisabled = _ref$dropFromOthersDi === void 0 ? false : _ref$dropFromOthersDi,
  3943. _ref$dropTargetStyle = _ref.dropTargetStyle,
  3944. dropTargetStyle = _ref$dropTargetStyle === void 0 ? DEFAULT_DROP_TARGET_STYLE : _ref$dropTargetStyle,
  3945. _ref$dropTargetClasse = _ref.dropTargetClasses,
  3946. dropTargetClasses = _ref$dropTargetClasse === void 0 ? [] : _ref$dropTargetClasse,
  3947. _ref$transformDragged = _ref.transformDraggedElement,
  3948. transformDraggedElement = _ref$transformDragged === void 0 ? function () {} : _ref$transformDragged,
  3949. _ref$centreDraggedOnC = _ref.centreDraggedOnCursor,
  3950. centreDraggedOnCursor = _ref$centreDraggedOnC === void 0 ? false : _ref$centreDraggedOnC;
  3951. config.dropAnimationDurationMs = dropAnimationDurationMs;
  3952. if (config.type && newType !== config.type) {
  3953. unregisterDropZone(node, config.type);
  3954. }
  3955. config.type = newType;
  3956. registerDropZone(node, newType);
  3957. config.items = _toConsumableArray(items);
  3958. config.dragDisabled = dragDisabled;
  3959. config.morphDisabled = morphDisabled;
  3960. config.transformDraggedElement = transformDraggedElement;
  3961. config.centreDraggedOnCursor = centreDraggedOnCursor; // realtime update for dropTargetStyle
  3962. if (isWorkingOnPreviousDrag && !finalizingPreviousDrag && (!areObjectsShallowEqual(dropTargetStyle, config.dropTargetStyle) || !areArraysShallowEqualSameOrder(dropTargetClasses, config.dropTargetClasses))) {
  3963. styleInactiveDropZones([node], function () {
  3964. return config.dropTargetStyle;
  3965. }, function () {
  3966. return dropTargetClasses;
  3967. });
  3968. styleActiveDropZones([node], function () {
  3969. return dropTargetStyle;
  3970. }, function () {
  3971. return dropTargetClasses;
  3972. });
  3973. }
  3974. config.dropTargetStyle = dropTargetStyle;
  3975. config.dropTargetClasses = _toConsumableArray(dropTargetClasses); // realtime update for dropFromOthersDisabled
  3976. function getConfigProp(dz, propName) {
  3977. return dzToConfig.get(dz) ? dzToConfig.get(dz)[propName] : config[propName];
  3978. }
  3979. if (isWorkingOnPreviousDrag && config.dropFromOthersDisabled !== dropFromOthersDisabled) {
  3980. if (dropFromOthersDisabled) {
  3981. styleInactiveDropZones([node], function (dz) {
  3982. return getConfigProp(dz, "dropTargetStyle");
  3983. }, function (dz) {
  3984. return getConfigProp(dz, "dropTargetClasses");
  3985. });
  3986. } else {
  3987. styleActiveDropZones([node], function (dz) {
  3988. return getConfigProp(dz, "dropTargetStyle");
  3989. }, function (dz) {
  3990. return getConfigProp(dz, "dropTargetClasses");
  3991. });
  3992. }
  3993. }
  3994. config.dropFromOthersDisabled = dropFromOthersDisabled;
  3995. dzToConfig.set(node, config);
  3996. var shadowElIdx = findShadowElementIdx(config.items);
  3997. var _loop = function _loop(idx) {
  3998. var draggableEl = node.children[idx];
  3999. styleDraggable(draggableEl, dragDisabled);
  4000. if (idx === shadowElIdx) {
  4001. if (!morphDisabled) {
  4002. morphDraggedElementToBeLike(draggedEl, draggableEl, currentMousePosition.x, currentMousePosition.y, function () {
  4003. return config.transformDraggedElement(draggedEl, draggedElData, idx);
  4004. });
  4005. }
  4006. decorateShadowEl(draggableEl);
  4007. return "continue";
  4008. }
  4009. draggableEl.removeEventListener("mousedown", elToMouseDownListener.get(draggableEl));
  4010. draggableEl.removeEventListener("touchstart", elToMouseDownListener.get(draggableEl));
  4011. if (!dragDisabled) {
  4012. draggableEl.addEventListener("mousedown", handleMouseDown);
  4013. draggableEl.addEventListener("touchstart", handleMouseDown);
  4014. elToMouseDownListener.set(draggableEl, handleMouseDown);
  4015. } // updating the idx
  4016. elToIdx.set(draggableEl, idx);
  4017. };
  4018. for (var idx = 0; idx < node.children.length; idx++) {
  4019. var _ret = _loop(idx);
  4020. if (_ret === "continue") continue;
  4021. }
  4022. }
  4023. configure(options);
  4024. return {
  4025. update: function update(newOptions) {
  4026. configure(newOptions);
  4027. },
  4028. destroy: function destroy() {
  4029. unregisterDropZone(node, config.type);
  4030. dzToConfig["delete"](node);
  4031. }
  4032. };
  4033. }
  4034. var _ID_TO_INSTRUCTION;
  4035. var INSTRUCTION_IDs = {
  4036. DND_ZONE_ACTIVE: "dnd-zone-active",
  4037. DND_ZONE_DRAG_DISABLED: "dnd-zone-drag-disabled"
  4038. };
  4039. var ID_TO_INSTRUCTION = (_ID_TO_INSTRUCTION = {}, _defineProperty(_ID_TO_INSTRUCTION, INSTRUCTION_IDs.DND_ZONE_ACTIVE, "Tab to one the items and press space-bar or enter to start dragging it"), _defineProperty(_ID_TO_INSTRUCTION, INSTRUCTION_IDs.DND_ZONE_DRAG_DISABLED, "This is a disabled drag and drop list"), _ID_TO_INSTRUCTION);
  4040. var ALERT_DIV_ID = "dnd-action-aria-alert";
  4041. var alertsDiv;
  4042. function initAriaOnBrowser() {
  4043. // setting the dynamic alerts
  4044. alertsDiv = document.createElement("div");
  4045. (function initAlertsDiv() {
  4046. alertsDiv.id = ALERT_DIV_ID; // tab index -1 makes the alert be read twice on chrome for some reason
  4047. //alertsDiv.tabIndex = -1;
  4048. alertsDiv.style.position = "fixed";
  4049. alertsDiv.style.bottom = "0";
  4050. alertsDiv.style.left = "0";
  4051. alertsDiv.style.zIndex = "-5";
  4052. alertsDiv.style.opacity = "0";
  4053. alertsDiv.style.height = "0";
  4054. alertsDiv.style.width = "0";
  4055. alertsDiv.setAttribute("role", "alert");
  4056. })();
  4057. document.body.prepend(alertsDiv); // setting the instructions
  4058. Object.entries(ID_TO_INSTRUCTION).forEach(function (_ref) {
  4059. var _ref2 = _slicedToArray(_ref, 2),
  4060. id = _ref2[0],
  4061. txt = _ref2[1];
  4062. return document.body.prepend(instructionToHiddenDiv(id, txt));
  4063. });
  4064. }
  4065. /**
  4066. * Initializes the static aria instructions so they can be attached to zones
  4067. * @return {{DND_ZONE_ACTIVE: string, DND_ZONE_DRAG_DISABLED: string} | null} - the IDs for static aria instruction (to be used via aria-describedby) or null on the server
  4068. */
  4069. function initAria() {
  4070. if (isOnServer) return null;
  4071. if (document.readyState === "complete") {
  4072. initAriaOnBrowser();
  4073. } else {
  4074. window.addEventListener("DOMContentLoaded", initAriaOnBrowser);
  4075. }
  4076. return _objectSpread2({}, INSTRUCTION_IDs);
  4077. }
  4078. function instructionToHiddenDiv(id, txt) {
  4079. var div = document.createElement("div");
  4080. div.id = id;
  4081. div.innerHTML = "<p>".concat(txt, "</p>");
  4082. div.style.display = "none";
  4083. div.style.position = "fixed";
  4084. div.style.zIndex = "-5";
  4085. return div;
  4086. }
  4087. /**
  4088. * Will make the screen reader alert the provided text to the user
  4089. * @param {string} txt
  4090. */
  4091. function alertToScreenReader(txt) {
  4092. alertsDiv.innerHTML = "";
  4093. var alertText = document.createTextNode(txt);
  4094. alertsDiv.appendChild(alertText); // this is needed for Safari
  4095. alertsDiv.style.display = "none";
  4096. alertsDiv.style.display = "inline";
  4097. }
  4098. var DEFAULT_DROP_ZONE_TYPE$1 = "--any--";
  4099. var DEFAULT_DROP_TARGET_STYLE$1 = {
  4100. outline: "rgba(255, 255, 102, 0.7) solid 2px"
  4101. };
  4102. var isDragging = false;
  4103. var draggedItemType;
  4104. var focusedDz;
  4105. var focusedDzLabel = "";
  4106. var focusedItem;
  4107. var focusedItemId;
  4108. var focusedItemLabel = "";
  4109. var allDragTargets = new WeakSet();
  4110. var elToKeyDownListeners = new WeakMap();
  4111. var elToFocusListeners = new WeakMap();
  4112. var dzToHandles = new Map();
  4113. var dzToConfig$1 = new Map();
  4114. var typeToDropZones$1 = new Map();
  4115. /* TODO (potentially)
  4116. * what's the deal with the black border of voice-reader not following focus?
  4117. * maybe keep focus on the last dragged item upon drop?
  4118. */
  4119. var INSTRUCTION_IDs$1 = initAria();
  4120. /* drop-zones registration management */
  4121. function registerDropZone$1(dropZoneEl, type) {
  4122. if (typeToDropZones$1.size === 0) {
  4123. window.addEventListener("keydown", globalKeyDownHandler);
  4124. window.addEventListener("click", globalClickHandler);
  4125. }
  4126. if (!typeToDropZones$1.has(type)) {
  4127. typeToDropZones$1.set(type, new Set());
  4128. }
  4129. if (!typeToDropZones$1.get(type).has(dropZoneEl)) {
  4130. typeToDropZones$1.get(type).add(dropZoneEl);
  4131. incrementActiveDropZoneCount();
  4132. }
  4133. }
  4134. function unregisterDropZone$1(dropZoneEl, type) {
  4135. if (focusedDz === dropZoneEl) {
  4136. handleDrop$1();
  4137. }
  4138. typeToDropZones$1.get(type)["delete"](dropZoneEl);
  4139. decrementActiveDropZoneCount();
  4140. if (typeToDropZones$1.get(type).size === 0) {
  4141. typeToDropZones$1["delete"](type);
  4142. }
  4143. if (typeToDropZones$1.size === 0) {
  4144. window.removeEventListener("keydown", globalKeyDownHandler);
  4145. window.removeEventListener("click", globalClickHandler);
  4146. }
  4147. }
  4148. function globalKeyDownHandler(e) {
  4149. if (!isDragging) return;
  4150. switch (e.key) {
  4151. case "Escape":
  4152. {
  4153. handleDrop$1();
  4154. break;
  4155. }
  4156. }
  4157. }
  4158. function globalClickHandler() {
  4159. if (!isDragging) return;
  4160. if (!allDragTargets.has(document.activeElement)) {
  4161. handleDrop$1();
  4162. }
  4163. }
  4164. function handleZoneFocus(e) {
  4165. if (!isDragging) return;
  4166. var newlyFocusedDz = e.currentTarget;
  4167. if (newlyFocusedDz === focusedDz) return;
  4168. focusedDzLabel = newlyFocusedDz.getAttribute("aria-label") || "";
  4169. var _dzToConfig$get = dzToConfig$1.get(focusedDz),
  4170. originItems = _dzToConfig$get.items;
  4171. var originItem = originItems.find(function (item) {
  4172. return item[ITEM_ID_KEY] === focusedItemId;
  4173. });
  4174. var originIdx = originItems.indexOf(originItem);
  4175. var itemToMove = originItems.splice(originIdx, 1)[0];
  4176. var _dzToConfig$get2 = dzToConfig$1.get(newlyFocusedDz),
  4177. targetItems = _dzToConfig$get2.items,
  4178. autoAriaDisabled = _dzToConfig$get2.autoAriaDisabled;
  4179. if (newlyFocusedDz.getBoundingClientRect().top < focusedDz.getBoundingClientRect().top || newlyFocusedDz.getBoundingClientRect().left < focusedDz.getBoundingClientRect().left) {
  4180. targetItems.push(itemToMove);
  4181. if (!autoAriaDisabled) {
  4182. alertToScreenReader("Moved item ".concat(focusedItemLabel, " to the end of the list ").concat(focusedDzLabel));
  4183. }
  4184. } else {
  4185. targetItems.unshift(itemToMove);
  4186. if (!autoAriaDisabled) {
  4187. alertToScreenReader("Moved item ".concat(focusedItemLabel, " to the beginning of the list ").concat(focusedDzLabel));
  4188. }
  4189. }
  4190. var dzFrom = focusedDz;
  4191. dispatchFinalizeEvent(dzFrom, originItems, {
  4192. trigger: TRIGGERS.DROPPED_INTO_ANOTHER,
  4193. id: focusedItemId,
  4194. source: SOURCES.KEYBOARD
  4195. });
  4196. dispatchFinalizeEvent(newlyFocusedDz, targetItems, {
  4197. trigger: TRIGGERS.DROPPED_INTO_ZONE,
  4198. id: focusedItemId,
  4199. source: SOURCES.KEYBOARD
  4200. });
  4201. focusedDz = newlyFocusedDz;
  4202. }
  4203. function triggerAllDzsUpdate() {
  4204. dzToHandles.forEach(function (_ref, dz) {
  4205. var update = _ref.update;
  4206. return update(dzToConfig$1.get(dz));
  4207. });
  4208. }
  4209. function handleDrop$1() {
  4210. var dispatchConsider = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  4211. if (!dzToConfig$1.get(focusedDz).autoAriaDisabled) {
  4212. alertToScreenReader("Stopped dragging item ".concat(focusedItemLabel));
  4213. }
  4214. if (allDragTargets.has(document.activeElement)) {
  4215. document.activeElement.blur();
  4216. }
  4217. if (dispatchConsider) {
  4218. dispatchConsiderEvent(focusedDz, dzToConfig$1.get(focusedDz).items, {
  4219. trigger: TRIGGERS.DRAG_STOPPED,
  4220. id: focusedItemId,
  4221. source: SOURCES.KEYBOARD
  4222. });
  4223. }
  4224. styleInactiveDropZones(typeToDropZones$1.get(draggedItemType), function (dz) {
  4225. return dzToConfig$1.get(dz).dropTargetStyle;
  4226. }, function (dz) {
  4227. return dzToConfig$1.get(dz).dropTargetClasses;
  4228. });
  4229. focusedItem = null;
  4230. focusedItemId = null;
  4231. focusedItemLabel = "";
  4232. draggedItemType = null;
  4233. focusedDz = null;
  4234. focusedDzLabel = "";
  4235. isDragging = false;
  4236. triggerAllDzsUpdate();
  4237. } //////
  4238. function dndzone$1(node, options) {
  4239. var config = {
  4240. items: undefined,
  4241. type: undefined,
  4242. dragDisabled: false,
  4243. dropFromOthersDisabled: false,
  4244. dropTargetStyle: DEFAULT_DROP_TARGET_STYLE$1,
  4245. dropTargetClasses: [],
  4246. autoAriaDisabled: false
  4247. };
  4248. function swap(arr, i, j) {
  4249. if (arr.length <= 1) return;
  4250. arr.splice(j, 1, arr.splice(i, 1, arr[j])[0]);
  4251. }
  4252. function handleKeyDown(e) {
  4253. switch (e.key) {
  4254. case "Enter":
  4255. case " ":
  4256. {
  4257. // we don't want to affect nested input elements or clickable elements
  4258. if ((e.target.disabled !== undefined || e.target.href || e.target.isContentEditable) && !allDragTargets.has(e.target)) {
  4259. return;
  4260. }
  4261. e.preventDefault(); // preventing scrolling on spacebar
  4262. e.stopPropagation();
  4263. if (isDragging) {
  4264. // TODO - should this trigger a drop? only here or in general (as in when hitting space or enter outside of any zone)?
  4265. handleDrop$1();
  4266. } else {
  4267. // drag start
  4268. handleDragStart(e);
  4269. }
  4270. break;
  4271. }
  4272. case "ArrowDown":
  4273. case "ArrowRight":
  4274. {
  4275. if (!isDragging) return;
  4276. e.preventDefault(); // prevent scrolling
  4277. e.stopPropagation();
  4278. var _dzToConfig$get3 = dzToConfig$1.get(node),
  4279. items = _dzToConfig$get3.items;
  4280. var children = Array.from(node.children);
  4281. var idx = children.indexOf(e.currentTarget);
  4282. if (idx < children.length - 1) {
  4283. if (!config.autoAriaDisabled) {
  4284. alertToScreenReader("Moved item ".concat(focusedItemLabel, " to position ").concat(idx + 2, " in the list ").concat(focusedDzLabel));
  4285. }
  4286. swap(items, idx, idx + 1);
  4287. dispatchFinalizeEvent(node, items, {
  4288. trigger: TRIGGERS.DROPPED_INTO_ZONE,
  4289. id: focusedItemId,
  4290. source: SOURCES.KEYBOARD
  4291. });
  4292. }
  4293. break;
  4294. }
  4295. case "ArrowUp":
  4296. case "ArrowLeft":
  4297. {
  4298. if (!isDragging) return;
  4299. e.preventDefault(); // prevent scrolling
  4300. e.stopPropagation();
  4301. var _dzToConfig$get4 = dzToConfig$1.get(node),
  4302. _items = _dzToConfig$get4.items;
  4303. var _children = Array.from(node.children);
  4304. var _idx = _children.indexOf(e.currentTarget);
  4305. if (_idx > 0) {
  4306. if (!config.autoAriaDisabled) {
  4307. alertToScreenReader("Moved item ".concat(focusedItemLabel, " to position ").concat(_idx, " in the list ").concat(focusedDzLabel));
  4308. }
  4309. swap(_items, _idx, _idx - 1);
  4310. dispatchFinalizeEvent(node, _items, {
  4311. trigger: TRIGGERS.DROPPED_INTO_ZONE,
  4312. id: focusedItemId,
  4313. source: SOURCES.KEYBOARD
  4314. });
  4315. }
  4316. break;
  4317. }
  4318. }
  4319. }
  4320. function handleDragStart(e) {
  4321. setCurrentFocusedItem(e.currentTarget);
  4322. focusedDz = node;
  4323. draggedItemType = config.type;
  4324. isDragging = true;
  4325. var dropTargets = Array.from(typeToDropZones$1.get(config.type)).filter(function (dz) {
  4326. return dz === focusedDz || !dzToConfig$1.get(dz).dropFromOthersDisabled;
  4327. });
  4328. styleActiveDropZones(dropTargets, function (dz) {
  4329. return dzToConfig$1.get(dz).dropTargetStyle;
  4330. }, function (dz) {
  4331. return dzToConfig$1.get(dz).dropTargetClasses;
  4332. });
  4333. if (!config.autoAriaDisabled) {
  4334. var msg = "Started dragging item ".concat(focusedItemLabel, ". Use the arrow keys to move it within its list ").concat(focusedDzLabel);
  4335. if (dropTargets.length > 1) {
  4336. msg += ", or tab to another list in order to move the item into it";
  4337. }
  4338. alertToScreenReader(msg);
  4339. }
  4340. dispatchConsiderEvent(node, dzToConfig$1.get(node).items, {
  4341. trigger: TRIGGERS.DRAG_STARTED,
  4342. id: focusedItemId,
  4343. source: SOURCES.KEYBOARD
  4344. });
  4345. triggerAllDzsUpdate();
  4346. }
  4347. function handleClick(e) {
  4348. if (!isDragging) return;
  4349. if (e.currentTarget === focusedItem) return;
  4350. e.stopPropagation();
  4351. handleDrop$1(false);
  4352. handleDragStart(e);
  4353. }
  4354. function setCurrentFocusedItem(draggableEl) {
  4355. var _dzToConfig$get5 = dzToConfig$1.get(node),
  4356. items = _dzToConfig$get5.items;
  4357. var children = Array.from(node.children);
  4358. var focusedItemIdx = children.indexOf(draggableEl);
  4359. focusedItem = draggableEl;
  4360. focusedItem.tabIndex = 0;
  4361. focusedItemId = items[focusedItemIdx][ITEM_ID_KEY];
  4362. focusedItemLabel = children[focusedItemIdx].getAttribute("aria-label") || "";
  4363. }
  4364. function configure(_ref2) {
  4365. var _ref2$items = _ref2.items,
  4366. items = _ref2$items === void 0 ? [] : _ref2$items,
  4367. _ref2$type = _ref2.type,
  4368. newType = _ref2$type === void 0 ? DEFAULT_DROP_ZONE_TYPE$1 : _ref2$type,
  4369. _ref2$dragDisabled = _ref2.dragDisabled,
  4370. dragDisabled = _ref2$dragDisabled === void 0 ? false : _ref2$dragDisabled,
  4371. _ref2$dropFromOthersD = _ref2.dropFromOthersDisabled,
  4372. dropFromOthersDisabled = _ref2$dropFromOthersD === void 0 ? false : _ref2$dropFromOthersD,
  4373. _ref2$dropTargetStyle = _ref2.dropTargetStyle,
  4374. dropTargetStyle = _ref2$dropTargetStyle === void 0 ? DEFAULT_DROP_TARGET_STYLE$1 : _ref2$dropTargetStyle,
  4375. _ref2$dropTargetClass = _ref2.dropTargetClasses,
  4376. dropTargetClasses = _ref2$dropTargetClass === void 0 ? [] : _ref2$dropTargetClass,
  4377. _ref2$autoAriaDisable = _ref2.autoAriaDisabled,
  4378. autoAriaDisabled = _ref2$autoAriaDisable === void 0 ? false : _ref2$autoAriaDisable;
  4379. config.items = _toConsumableArray(items);
  4380. config.dragDisabled = dragDisabled;
  4381. config.dropFromOthersDisabled = dropFromOthersDisabled;
  4382. config.dropTargetStyle = dropTargetStyle;
  4383. config.dropTargetClasses = dropTargetClasses;
  4384. config.autoAriaDisabled = autoAriaDisabled;
  4385. if (!autoAriaDisabled) {
  4386. node.setAttribute("aria-disabled", dragDisabled);
  4387. node.setAttribute("role", "list");
  4388. node.setAttribute("aria-describedby", dragDisabled ? INSTRUCTION_IDs$1.DND_ZONE_DRAG_DISABLED : INSTRUCTION_IDs$1.DND_ZONE_ACTIVE);
  4389. }
  4390. if (config.type && newType !== config.type) {
  4391. unregisterDropZone$1(node, config.type);
  4392. }
  4393. config.type = newType;
  4394. registerDropZone$1(node, newType);
  4395. dzToConfig$1.set(node, config);
  4396. node.tabIndex = isDragging && (node === focusedDz || focusedItem.contains(node) || config.dropFromOthersDisabled || focusedDz && config.type !== dzToConfig$1.get(focusedDz).type) ? -1 : 0;
  4397. node.addEventListener("focus", handleZoneFocus);
  4398. var _loop = function _loop(i) {
  4399. var draggableEl = node.children[i];
  4400. allDragTargets.add(draggableEl);
  4401. draggableEl.tabIndex = isDragging ? -1 : 0;
  4402. if (!autoAriaDisabled) {
  4403. draggableEl.setAttribute("role", "listitem");
  4404. }
  4405. draggableEl.removeEventListener("keydown", elToKeyDownListeners.get(draggableEl));
  4406. draggableEl.removeEventListener("click", elToFocusListeners.get(draggableEl));
  4407. if (!dragDisabled) {
  4408. draggableEl.addEventListener("keydown", handleKeyDown);
  4409. elToKeyDownListeners.set(draggableEl, handleKeyDown);
  4410. draggableEl.addEventListener("click", handleClick);
  4411. elToFocusListeners.set(draggableEl, handleClick);
  4412. }
  4413. if (isDragging && config.items[i][ITEM_ID_KEY] === focusedItemId) {
  4414. focusedItem = draggableEl;
  4415. focusedItem.tabIndex = 0; // without this the element loses focus if it moves backwards in the list
  4416. draggableEl.focus();
  4417. }
  4418. };
  4419. for (var i = 0; i < node.children.length; i++) {
  4420. _loop(i);
  4421. }
  4422. }
  4423. configure(options);
  4424. var handles = {
  4425. update: function update(newOptions) {
  4426. configure(newOptions);
  4427. },
  4428. destroy: function destroy() {
  4429. unregisterDropZone$1(node, config.type);
  4430. dzToConfig$1["delete"](node);
  4431. dzToHandles["delete"](node);
  4432. }
  4433. };
  4434. dzToHandles.set(node, handles);
  4435. return handles;
  4436. }
  4437. /**
  4438. * A custom action to turn any container to a dnd zone and all of its direct children to draggables
  4439. * Supports mouse, touch and keyboard interactions.
  4440. * Dispatches two events that the container is expected to react to by modifying its list of items,
  4441. * which will then feed back in to this action via the update function
  4442. *
  4443. * @typedef {object} Options
  4444. * @property {array} items - the list of items that was used to generate the children of the given node (the list used in the #each block
  4445. * @property {string} [type] - the type of the dnd zone. children dragged from here can only be dropped in other zones of the same type, default to a base type
  4446. * @property {number} [flipDurationMs] - if the list animated using flip (recommended), specifies the flip duration such that everything syncs with it without conflict, defaults to zero
  4447. * @property {boolean} [dragDisabled]
  4448. * @property {boolean} [morphDisabled] - whether dragged element should morph to zone dimensions
  4449. * @property {boolean} [dropFromOthersDisabled]
  4450. * @property {object} [dropTargetStyle]
  4451. * @property {string[]} [dropTargetClasses]
  4452. * @property {function} [transformDraggedElement]
  4453. * @param {HTMLElement} node - the element to enhance
  4454. * @param {Options} options
  4455. * @return {{update: function, destroy: function}}
  4456. */
  4457. function dndzone$2(node, options) {
  4458. validateOptions(options);
  4459. var pointerZone = dndzone(node, options);
  4460. var keyboardZone = dndzone$1(node, options);
  4461. return {
  4462. update: function update(newOptions) {
  4463. validateOptions(newOptions);
  4464. pointerZone.update(newOptions);
  4465. keyboardZone.update(newOptions);
  4466. },
  4467. destroy: function destroy() {
  4468. pointerZone.destroy();
  4469. keyboardZone.destroy();
  4470. }
  4471. };
  4472. }
  4473. function validateOptions(options) {
  4474. /*eslint-disable*/
  4475. var items = options.items;
  4476. options.flipDurationMs;
  4477. options.type;
  4478. options.dragDisabled;
  4479. options.morphDisabled;
  4480. options.dropFromOthersDisabled;
  4481. options.dropTargetStyle;
  4482. var dropTargetClasses = options.dropTargetClasses;
  4483. options.transformDraggedElement;
  4484. options.autoAriaDisabled;
  4485. options.centreDraggedOnCursor;
  4486. var rest = _objectWithoutProperties(options, ["items", "flipDurationMs", "type", "dragDisabled", "morphDisabled", "dropFromOthersDisabled", "dropTargetStyle", "dropTargetClasses", "transformDraggedElement", "autoAriaDisabled", "centreDraggedOnCursor"]);
  4487. /*eslint-enable*/
  4488. if (Object.keys(rest).length > 0) {
  4489. console.warn("dndzone will ignore unknown options", rest);
  4490. }
  4491. if (!items) {
  4492. throw new Error("no 'items' key provided to dndzone");
  4493. }
  4494. var itemWithMissingId = items.find(function (item) {
  4495. return !{}.hasOwnProperty.call(item, ITEM_ID_KEY);
  4496. });
  4497. if (itemWithMissingId) {
  4498. throw new Error("missing '".concat(ITEM_ID_KEY, "' property for item ").concat(toString$1(itemWithMissingId)));
  4499. }
  4500. if (dropTargetClasses && !Array.isArray(dropTargetClasses)) {
  4501. throw new Error("dropTargetClasses should be an array but instead it is a ".concat(_typeof(dropTargetClasses), ", ").concat(toString$1(dropTargetClasses)));
  4502. }
  4503. }
  4504. /* src/gui/choiceList/ChoiceList.svelte generated by Svelte v3.47.0 */
  4505. function add_css$5(target) {
  4506. append_styles(target, "svelte-jb273g", ".choiceList.svelte-jb273g{width:auto;border:0 solid black;overflow-y:auto;height:auto}");
  4507. }
  4508. function get_each_context$2(ctx, list, i) {
  4509. const child_ctx = ctx.slice();
  4510. child_ctx[21] = list[i];
  4511. child_ctx[22] = list;
  4512. child_ctx[23] = i;
  4513. return child_ctx;
  4514. }
  4515. // (51:8) {:else}
  4516. function create_else_block$1(ctx) {
  4517. let multichoicelistitem;
  4518. let updating_dragDisabled;
  4519. let updating_collapseId;
  4520. let updating_choice;
  4521. let current;
  4522. function multichoicelistitem_dragDisabled_binding(value) {
  4523. /*multichoicelistitem_dragDisabled_binding*/ ctx[13](value);
  4524. }
  4525. function multichoicelistitem_collapseId_binding(value) {
  4526. /*multichoicelistitem_collapseId_binding*/ ctx[14](value);
  4527. }
  4528. function multichoicelistitem_choice_binding(value) {
  4529. /*multichoicelistitem_choice_binding*/ ctx[15](value, /*choice*/ ctx[21], /*each_value*/ ctx[22], /*choice_index*/ ctx[23]);
  4530. }
  4531. let multichoicelistitem_props = {};
  4532. if (/*dragDisabled*/ ctx[3] !== void 0) {
  4533. multichoicelistitem_props.dragDisabled = /*dragDisabled*/ ctx[3];
  4534. }
  4535. if (/*collapseId*/ ctx[2] !== void 0) {
  4536. multichoicelistitem_props.collapseId = /*collapseId*/ ctx[2];
  4537. }
  4538. if (/*choice*/ ctx[21] !== void 0) {
  4539. multichoicelistitem_props.choice = /*choice*/ ctx[21];
  4540. }
  4541. multichoicelistitem = new MultiChoiceListItem({ props: multichoicelistitem_props });
  4542. binding_callbacks.push(() => bind(multichoicelistitem, 'dragDisabled', multichoicelistitem_dragDisabled_binding));
  4543. binding_callbacks.push(() => bind(multichoicelistitem, 'collapseId', multichoicelistitem_collapseId_binding));
  4544. binding_callbacks.push(() => bind(multichoicelistitem, 'choice', multichoicelistitem_choice_binding));
  4545. multichoicelistitem.$on("mousedown", /*startDrag*/ ctx[6]);
  4546. multichoicelistitem.$on("touchstart", /*startDrag*/ ctx[6]);
  4547. multichoicelistitem.$on("deleteChoice", /*deleteChoice_handler_1*/ ctx[16]);
  4548. multichoicelistitem.$on("configureChoice", /*configureChoice_handler_1*/ ctx[17]);
  4549. multichoicelistitem.$on("toggleCommand", /*toggleCommand_handler_1*/ ctx[18]);
  4550. return {
  4551. c() {
  4552. create_component(multichoicelistitem.$$.fragment);
  4553. },
  4554. m(target, anchor) {
  4555. mount_component(multichoicelistitem, target, anchor);
  4556. current = true;
  4557. },
  4558. p(new_ctx, dirty) {
  4559. ctx = new_ctx;
  4560. const multichoicelistitem_changes = {};
  4561. if (!updating_dragDisabled && dirty & /*dragDisabled*/ 8) {
  4562. updating_dragDisabled = true;
  4563. multichoicelistitem_changes.dragDisabled = /*dragDisabled*/ ctx[3];
  4564. add_flush_callback(() => updating_dragDisabled = false);
  4565. }
  4566. if (!updating_collapseId && dirty & /*collapseId*/ 4) {
  4567. updating_collapseId = true;
  4568. multichoicelistitem_changes.collapseId = /*collapseId*/ ctx[2];
  4569. add_flush_callback(() => updating_collapseId = false);
  4570. }
  4571. if (!updating_choice && dirty & /*choices, SHADOW_PLACEHOLDER_ITEM_ID*/ 3) {
  4572. updating_choice = true;
  4573. multichoicelistitem_changes.choice = /*choice*/ ctx[21];
  4574. add_flush_callback(() => updating_choice = false);
  4575. }
  4576. multichoicelistitem.$set(multichoicelistitem_changes);
  4577. },
  4578. i(local) {
  4579. if (current) return;
  4580. transition_in(multichoicelistitem.$$.fragment, local);
  4581. current = true;
  4582. },
  4583. o(local) {
  4584. transition_out(multichoicelistitem.$$.fragment, local);
  4585. current = false;
  4586. },
  4587. d(detaching) {
  4588. destroy_component(multichoicelistitem, detaching);
  4589. }
  4590. };
  4591. }
  4592. // (41:8) {#if choice.type !== ChoiceType.Multi}
  4593. function create_if_block$1(ctx) {
  4594. let choicelistitem;
  4595. let updating_dragDisabled;
  4596. let updating_choice;
  4597. let current;
  4598. function choicelistitem_dragDisabled_binding(value) {
  4599. /*choicelistitem_dragDisabled_binding*/ ctx[8](value);
  4600. }
  4601. function choicelistitem_choice_binding(value) {
  4602. /*choicelistitem_choice_binding*/ ctx[9](value, /*choice*/ ctx[21], /*each_value*/ ctx[22], /*choice_index*/ ctx[23]);
  4603. }
  4604. let choicelistitem_props = {};
  4605. if (/*dragDisabled*/ ctx[3] !== void 0) {
  4606. choicelistitem_props.dragDisabled = /*dragDisabled*/ ctx[3];
  4607. }
  4608. if (/*choice*/ ctx[21] !== void 0) {
  4609. choicelistitem_props.choice = /*choice*/ ctx[21];
  4610. }
  4611. choicelistitem = new ChoiceListItem({ props: choicelistitem_props });
  4612. binding_callbacks.push(() => bind(choicelistitem, 'dragDisabled', choicelistitem_dragDisabled_binding));
  4613. binding_callbacks.push(() => bind(choicelistitem, 'choice', choicelistitem_choice_binding));
  4614. choicelistitem.$on("mousedown", /*startDrag*/ ctx[6]);
  4615. choicelistitem.$on("touchstart", /*startDrag*/ ctx[6]);
  4616. choicelistitem.$on("deleteChoice", /*deleteChoice_handler*/ ctx[10]);
  4617. choicelistitem.$on("configureChoice", /*configureChoice_handler*/ ctx[11]);
  4618. choicelistitem.$on("toggleCommand", /*toggleCommand_handler*/ ctx[12]);
  4619. return {
  4620. c() {
  4621. create_component(choicelistitem.$$.fragment);
  4622. },
  4623. m(target, anchor) {
  4624. mount_component(choicelistitem, target, anchor);
  4625. current = true;
  4626. },
  4627. p(new_ctx, dirty) {
  4628. ctx = new_ctx;
  4629. const choicelistitem_changes = {};
  4630. if (!updating_dragDisabled && dirty & /*dragDisabled*/ 8) {
  4631. updating_dragDisabled = true;
  4632. choicelistitem_changes.dragDisabled = /*dragDisabled*/ ctx[3];
  4633. add_flush_callback(() => updating_dragDisabled = false);
  4634. }
  4635. if (!updating_choice && dirty & /*choices, SHADOW_PLACEHOLDER_ITEM_ID*/ 3) {
  4636. updating_choice = true;
  4637. choicelistitem_changes.choice = /*choice*/ ctx[21];
  4638. add_flush_callback(() => updating_choice = false);
  4639. }
  4640. choicelistitem.$set(choicelistitem_changes);
  4641. },
  4642. i(local) {
  4643. if (current) return;
  4644. transition_in(choicelistitem.$$.fragment, local);
  4645. current = true;
  4646. },
  4647. o(local) {
  4648. transition_out(choicelistitem.$$.fragment, local);
  4649. current = false;
  4650. },
  4651. d(detaching) {
  4652. destroy_component(choicelistitem, detaching);
  4653. }
  4654. };
  4655. }
  4656. // (40:4) {#each choices.filter(c => c.id !== SHADOW_PLACEHOLDER_ITEM_ID) as choice(choice.id)}
  4657. function create_each_block$2(key_1, ctx) {
  4658. let first;
  4659. let current_block_type_index;
  4660. let if_block;
  4661. let if_block_anchor;
  4662. let current;
  4663. const if_block_creators = [create_if_block$1, create_else_block$1];
  4664. const if_blocks = [];
  4665. function select_block_type(ctx, dirty) {
  4666. if (/*choice*/ ctx[21].type !== ChoiceType.Multi) return 0;
  4667. return 1;
  4668. }
  4669. current_block_type_index = select_block_type(ctx);
  4670. if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  4671. return {
  4672. key: key_1,
  4673. first: null,
  4674. c() {
  4675. first = empty();
  4676. if_block.c();
  4677. if_block_anchor = empty();
  4678. this.first = first;
  4679. },
  4680. m(target, anchor) {
  4681. insert(target, first, anchor);
  4682. if_blocks[current_block_type_index].m(target, anchor);
  4683. insert(target, if_block_anchor, anchor);
  4684. current = true;
  4685. },
  4686. p(new_ctx, dirty) {
  4687. ctx = new_ctx;
  4688. let previous_block_index = current_block_type_index;
  4689. current_block_type_index = select_block_type(ctx);
  4690. if (current_block_type_index === previous_block_index) {
  4691. if_blocks[current_block_type_index].p(ctx, dirty);
  4692. } else {
  4693. group_outros();
  4694. transition_out(if_blocks[previous_block_index], 1, 1, () => {
  4695. if_blocks[previous_block_index] = null;
  4696. });
  4697. check_outros();
  4698. if_block = if_blocks[current_block_type_index];
  4699. if (!if_block) {
  4700. if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  4701. if_block.c();
  4702. } else {
  4703. if_block.p(ctx, dirty);
  4704. }
  4705. transition_in(if_block, 1);
  4706. if_block.m(if_block_anchor.parentNode, if_block_anchor);
  4707. }
  4708. },
  4709. i(local) {
  4710. if (current) return;
  4711. transition_in(if_block);
  4712. current = true;
  4713. },
  4714. o(local) {
  4715. transition_out(if_block);
  4716. current = false;
  4717. },
  4718. d(detaching) {
  4719. if (detaching) detach(first);
  4720. if_blocks[current_block_type_index].d(detaching);
  4721. if (detaching) detach(if_block_anchor);
  4722. }
  4723. };
  4724. }
  4725. function create_fragment$8(ctx) {
  4726. let div;
  4727. let each_blocks = [];
  4728. let each_1_lookup = new Map();
  4729. let div_style_value;
  4730. let dndzone_action;
  4731. let current;
  4732. let mounted;
  4733. let dispose;
  4734. let each_value = /*choices*/ ctx[0].filter(/*func*/ ctx[7]);
  4735. const get_key = ctx => /*choice*/ ctx[21].id;
  4736. for (let i = 0; i < each_value.length; i += 1) {
  4737. let child_ctx = get_each_context$2(ctx, each_value, i);
  4738. let key = get_key(child_ctx);
  4739. each_1_lookup.set(key, each_blocks[i] = create_each_block$2(key, child_ctx));
  4740. }
  4741. return {
  4742. c() {
  4743. div = element("div");
  4744. for (let i = 0; i < each_blocks.length; i += 1) {
  4745. each_blocks[i].c();
  4746. }
  4747. attr(div, "class", "choiceList svelte-jb273g");
  4748. attr(div, "style", div_style_value = /*choices*/ ctx[0].length === 0
  4749. ? 'padding-bottom: 0.5rem'
  4750. : '');
  4751. },
  4752. m(target, anchor) {
  4753. insert(target, div, anchor);
  4754. for (let i = 0; i < each_blocks.length; i += 1) {
  4755. each_blocks[i].m(div, null);
  4756. }
  4757. current = true;
  4758. if (!mounted) {
  4759. dispose = [
  4760. action_destroyer(dndzone_action = dndzone$2.call(null, div, {
  4761. items: /*choices*/ ctx[0],
  4762. dragDisabled: /*dragDisabled*/ ctx[3],
  4763. dropTargetStyle: {}
  4764. })),
  4765. listen(div, "consider", /*handleConsider*/ ctx[4]),
  4766. listen(div, "finalize", /*handleSort*/ ctx[5])
  4767. ];
  4768. mounted = true;
  4769. }
  4770. },
  4771. p(ctx, [dirty]) {
  4772. if (dirty & /*dragDisabled, choices, SHADOW_PLACEHOLDER_ITEM_ID, startDrag, ChoiceType, collapseId*/ 79) {
  4773. each_value = /*choices*/ ctx[0].filter(/*func*/ ctx[7]);
  4774. group_outros();
  4775. each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value, each_1_lookup, div, outro_and_destroy_block, create_each_block$2, null, get_each_context$2);
  4776. check_outros();
  4777. }
  4778. if (!current || dirty & /*choices*/ 1 && div_style_value !== (div_style_value = /*choices*/ ctx[0].length === 0
  4779. ? 'padding-bottom: 0.5rem'
  4780. : '')) {
  4781. attr(div, "style", div_style_value);
  4782. }
  4783. if (dndzone_action && is_function(dndzone_action.update) && dirty & /*choices, dragDisabled*/ 9) dndzone_action.update.call(null, {
  4784. items: /*choices*/ ctx[0],
  4785. dragDisabled: /*dragDisabled*/ ctx[3],
  4786. dropTargetStyle: {}
  4787. });
  4788. },
  4789. i(local) {
  4790. if (current) return;
  4791. for (let i = 0; i < each_value.length; i += 1) {
  4792. transition_in(each_blocks[i]);
  4793. }
  4794. current = true;
  4795. },
  4796. o(local) {
  4797. for (let i = 0; i < each_blocks.length; i += 1) {
  4798. transition_out(each_blocks[i]);
  4799. }
  4800. current = false;
  4801. },
  4802. d(detaching) {
  4803. if (detaching) detach(div);
  4804. for (let i = 0; i < each_blocks.length; i += 1) {
  4805. each_blocks[i].d();
  4806. }
  4807. mounted = false;
  4808. run_all(dispose);
  4809. }
  4810. };
  4811. }
  4812. function instance$8($$self, $$props, $$invalidate) {
  4813. let { choices = [] } = $$props;
  4814. let collapseId;
  4815. let dragDisabled = true;
  4816. const dispatcher = createEventDispatcher();
  4817. function emitChoicesReordered() {
  4818. dispatcher('reorderChoices', { choices });
  4819. }
  4820. function handleConsider(e) {
  4821. let { items: newItems, info: { id } } = e.detail;
  4822. $$invalidate(2, collapseId = id);
  4823. $$invalidate(0, choices = newItems);
  4824. }
  4825. function handleSort(e) {
  4826. let { items: newItems, info: { source } } = e.detail;
  4827. $$invalidate(2, collapseId = "");
  4828. $$invalidate(0, choices = newItems);
  4829. if (source === SOURCES.POINTER) {
  4830. $$invalidate(3, dragDisabled = true);
  4831. }
  4832. emitChoicesReordered();
  4833. }
  4834. function startDrag(e) {
  4835. e.preventDefault();
  4836. $$invalidate(3, dragDisabled = false);
  4837. }
  4838. const func = c => c.id !== SHADOW_PLACEHOLDER_ITEM_ID;
  4839. function choicelistitem_dragDisabled_binding(value) {
  4840. dragDisabled = value;
  4841. $$invalidate(3, dragDisabled);
  4842. }
  4843. function choicelistitem_choice_binding(value, choice, each_value, choice_index) {
  4844. each_value[choice_index] = value;
  4845. $$invalidate(0, choices);
  4846. }
  4847. function deleteChoice_handler(event) {
  4848. bubble.call(this, $$self, event);
  4849. }
  4850. function configureChoice_handler(event) {
  4851. bubble.call(this, $$self, event);
  4852. }
  4853. function toggleCommand_handler(event) {
  4854. bubble.call(this, $$self, event);
  4855. }
  4856. function multichoicelistitem_dragDisabled_binding(value) {
  4857. dragDisabled = value;
  4858. $$invalidate(3, dragDisabled);
  4859. }
  4860. function multichoicelistitem_collapseId_binding(value) {
  4861. collapseId = value;
  4862. $$invalidate(2, collapseId);
  4863. }
  4864. function multichoicelistitem_choice_binding(value, choice, each_value, choice_index) {
  4865. each_value[choice_index] = value;
  4866. $$invalidate(0, choices);
  4867. }
  4868. function deleteChoice_handler_1(event) {
  4869. bubble.call(this, $$self, event);
  4870. }
  4871. function configureChoice_handler_1(event) {
  4872. bubble.call(this, $$self, event);
  4873. }
  4874. function toggleCommand_handler_1(event) {
  4875. bubble.call(this, $$self, event);
  4876. }
  4877. $$self.$$set = $$props => {
  4878. if ('choices' in $$props) $$invalidate(0, choices = $$props.choices);
  4879. };
  4880. return [
  4881. choices,
  4882. SHADOW_PLACEHOLDER_ITEM_ID,
  4883. collapseId,
  4884. dragDisabled,
  4885. handleConsider,
  4886. handleSort,
  4887. startDrag,
  4888. func,
  4889. choicelistitem_dragDisabled_binding,
  4890. choicelistitem_choice_binding,
  4891. deleteChoice_handler,
  4892. configureChoice_handler,
  4893. toggleCommand_handler,
  4894. multichoicelistitem_dragDisabled_binding,
  4895. multichoicelistitem_collapseId_binding,
  4896. multichoicelistitem_choice_binding,
  4897. deleteChoice_handler_1,
  4898. configureChoice_handler_1,
  4899. toggleCommand_handler_1
  4900. ];
  4901. }
  4902. class ChoiceList extends SvelteComponent {
  4903. constructor(options) {
  4904. super();
  4905. init(this, options, instance$8, create_fragment$8, safe_not_equal, { choices: 0 }, add_css$5);
  4906. }
  4907. }
  4908. /* src/gui/choiceList/AddChoiceBox.svelte generated by Svelte v3.47.0 */
  4909. function add_css$4(target) {
  4910. append_styles(target, "svelte-1newuee", ".addChoiceBox.svelte-1newuee{margin-top:1em;display:flex;flex-direction:row;align-items:center;gap:10px;justify-content:center}@media(max-width: 800px){.addChoiceBox.svelte-1newuee{flex-direction:column}}#addChoiceTypeSelector.svelte-1newuee{font-size:16px;padding:3px;border-radius:3px}");
  4911. }
  4912. function create_fragment$7(ctx) {
  4913. let div;
  4914. let input;
  4915. let t0;
  4916. let select;
  4917. let option0;
  4918. let t1_value = ChoiceType.Template + "";
  4919. let t1;
  4920. let option1;
  4921. let t2_value = ChoiceType.Capture + "";
  4922. let t2;
  4923. let option2;
  4924. let t3_value = ChoiceType.Macro + "";
  4925. let t3;
  4926. let option3;
  4927. let t4_value = ChoiceType.Multi + "";
  4928. let t4;
  4929. let t5;
  4930. let button;
  4931. let mounted;
  4932. let dispose;
  4933. return {
  4934. c() {
  4935. div = element("div");
  4936. input = element("input");
  4937. t0 = space();
  4938. select = element("select");
  4939. option0 = element("option");
  4940. t1 = text(t1_value);
  4941. option1 = element("option");
  4942. t2 = text(t2_value);
  4943. option2 = element("option");
  4944. t3 = text(t3_value);
  4945. option3 = element("option");
  4946. t4 = text(t4_value);
  4947. t5 = space();
  4948. button = element("button");
  4949. button.textContent = "Add Choice";
  4950. attr(input, "type", "text");
  4951. attr(input, "placeholder", "Name");
  4952. option0.__value = ChoiceType.Template;
  4953. option0.value = option0.__value;
  4954. option1.__value = ChoiceType.Capture;
  4955. option1.value = option1.__value;
  4956. option2.__value = ChoiceType.Macro;
  4957. option2.value = option2.__value;
  4958. option3.__value = ChoiceType.Multi;
  4959. option3.value = option3.__value;
  4960. attr(select, "id", "addChoiceTypeSelector");
  4961. attr(select, "class", "svelte-1newuee");
  4962. if (/*type*/ ctx[1] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[4].call(select));
  4963. attr(button, "class", "mod-cta");
  4964. attr(div, "class", "addChoiceBox svelte-1newuee");
  4965. },
  4966. m(target, anchor) {
  4967. insert(target, div, anchor);
  4968. append(div, input);
  4969. set_input_value(input, /*name*/ ctx[0]);
  4970. append(div, t0);
  4971. append(div, select);
  4972. append(select, option0);
  4973. append(option0, t1);
  4974. append(select, option1);
  4975. append(option1, t2);
  4976. append(select, option2);
  4977. append(option2, t3);
  4978. append(select, option3);
  4979. append(option3, t4);
  4980. select_option(select, /*type*/ ctx[1]);
  4981. append(div, t5);
  4982. append(div, button);
  4983. if (!mounted) {
  4984. dispose = [
  4985. listen(input, "input", /*input_input_handler*/ ctx[3]),
  4986. listen(select, "change", /*select_change_handler*/ ctx[4]),
  4987. listen(button, "click", /*addChoice*/ ctx[2])
  4988. ];
  4989. mounted = true;
  4990. }
  4991. },
  4992. p(ctx, [dirty]) {
  4993. if (dirty & /*name*/ 1 && input.value !== /*name*/ ctx[0]) {
  4994. set_input_value(input, /*name*/ ctx[0]);
  4995. }
  4996. if (dirty & /*type, ChoiceType*/ 2) {
  4997. select_option(select, /*type*/ ctx[1]);
  4998. }
  4999. },
  5000. i: noop,
  5001. o: noop,
  5002. d(detaching) {
  5003. if (detaching) detach(div);
  5004. mounted = false;
  5005. run_all(dispose);
  5006. }
  5007. };
  5008. }
  5009. function instance$7($$self, $$props, $$invalidate) {
  5010. let name;
  5011. let type;
  5012. const dispatch = createEventDispatcher();
  5013. function addChoice() {
  5014. if (!name) {
  5015. new obsidian.Notice("Choice name is invalid.");
  5016. return;
  5017. }
  5018. dispatch('addChoice', { name, type });
  5019. $$invalidate(0, name = "");
  5020. }
  5021. function input_input_handler() {
  5022. name = this.value;
  5023. $$invalidate(0, name);
  5024. }
  5025. function select_change_handler() {
  5026. type = select_value(this);
  5027. $$invalidate(1, type);
  5028. }
  5029. return [name, type, addChoice, input_input_handler, select_change_handler];
  5030. }
  5031. class AddChoiceBox extends SvelteComponent {
  5032. constructor(options) {
  5033. super();
  5034. init(this, options, instance$7, create_fragment$7, safe_not_equal, {}, add_css$4);
  5035. }
  5036. }
  5037. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  5038. // require the crypto API and do not support built-in fallback to lower quality random number
  5039. // generators (like Math.random()).
  5040. var getRandomValues;
  5041. var rnds8 = new Uint8Array(16);
  5042. function rng() {
  5043. // lazy load so that environments that need to polyfill have a chance to do so
  5044. if (!getRandomValues) {
  5045. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  5046. // find the complete implementation of crypto (msCrypto) on IE11.
  5047. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  5048. if (!getRandomValues) {
  5049. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  5050. }
  5051. }
  5052. return getRandomValues(rnds8);
  5053. }
  5054. var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  5055. function validate(uuid) {
  5056. return typeof uuid === 'string' && REGEX.test(uuid);
  5057. }
  5058. /**
  5059. * Convert array of 16 byte values to UUID string format of the form:
  5060. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  5061. */
  5062. var byteToHex = [];
  5063. for (var i = 0; i < 256; ++i) {
  5064. byteToHex.push((i + 0x100).toString(16).substr(1));
  5065. }
  5066. function stringify(arr) {
  5067. var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  5068. // Note: Be careful editing this code! It's been tuned for performance
  5069. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  5070. var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
  5071. // of the following:
  5072. // - One or more input array values don't map to a hex octet (leading to
  5073. // "undefined" in the uuid)
  5074. // - Invalid input values for the RFC `version` or `variant` fields
  5075. if (!validate(uuid)) {
  5076. throw TypeError('Stringified UUID is invalid');
  5077. }
  5078. return uuid;
  5079. }
  5080. function v4(options, buf, offset) {
  5081. options = options || {};
  5082. var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  5083. rnds[6] = rnds[6] & 0x0f | 0x40;
  5084. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  5085. if (buf) {
  5086. offset = offset || 0;
  5087. for (var i = 0; i < 16; ++i) {
  5088. buf[offset + i] = rnds[i];
  5089. }
  5090. return buf;
  5091. }
  5092. return stringify(rnds);
  5093. }
  5094. class Choice {
  5095. constructor(name, type) {
  5096. this.id = v4();
  5097. this.name = name;
  5098. this.type = type;
  5099. this.command = false;
  5100. }
  5101. }
  5102. var NewTabDirection;
  5103. (function (NewTabDirection) {
  5104. NewTabDirection["vertical"] = "vertical";
  5105. NewTabDirection["horizontal"] = "horizontal";
  5106. })(NewTabDirection || (NewTabDirection = {}));
  5107. class TemplateChoice extends Choice {
  5108. constructor(name) {
  5109. super(name, ChoiceType.Template);
  5110. this.templatePath = "";
  5111. this.fileNameFormat = { enabled: false, format: "" };
  5112. this.folder = { enabled: false, folders: [], chooseWhenCreatingNote: false, createInSameFolderAsActiveFile: false };
  5113. this.appendLink = false;
  5114. this.incrementFileName = false;
  5115. this.openFileInNewTab = { enabled: false, direction: NewTabDirection.vertical, focus: true };
  5116. this.openFile = false;
  5117. this.openFileInMode = 'default';
  5118. }
  5119. static Load(choice) {
  5120. return choice;
  5121. }
  5122. }
  5123. class MacroChoice extends Choice {
  5124. constructor(name) {
  5125. super(name, ChoiceType.Macro);
  5126. this.macroId = null;
  5127. }
  5128. }
  5129. class CaptureChoice extends Choice {
  5130. constructor(name) {
  5131. super(name, ChoiceType.Capture);
  5132. this.appendLink = false;
  5133. this.captureTo = "";
  5134. this.captureToActiveFile = false;
  5135. this.createFileIfItDoesntExist = { enabled: false, createWithTemplate: false, template: "" };
  5136. this.format = { enabled: false, format: "" };
  5137. this.insertAfter = { enabled: false, after: "", insertAtEnd: false, createIfNotFound: false, createIfNotFoundLocation: "top" };
  5138. this.prepend = false;
  5139. this.task = false;
  5140. this.openFileInNewTab = { enabled: false, direction: NewTabDirection.vertical, focus: true };
  5141. this.openFile = false;
  5142. this.openFileInMode = 'default';
  5143. }
  5144. static Load(choice) {
  5145. return choice;
  5146. }
  5147. }
  5148. class MultiChoice extends Choice {
  5149. constructor(name) {
  5150. super(name, ChoiceType.Multi);
  5151. this.choices = [];
  5152. }
  5153. addChoice(choice) {
  5154. this.choices.push(choice);
  5155. return this;
  5156. }
  5157. addChoices(choices) {
  5158. this.choices.push(...choices);
  5159. return this;
  5160. }
  5161. }
  5162. class GenericYesNoPrompt extends obsidian.Modal {
  5163. constructor(app, header, text) {
  5164. super(app);
  5165. this.header = header;
  5166. this.text = text;
  5167. this.didSubmit = false;
  5168. this.waitForClose = new Promise((resolve, reject) => {
  5169. this.resolvePromise = resolve;
  5170. this.rejectPromise = reject;
  5171. });
  5172. this.open();
  5173. this.display();
  5174. }
  5175. static Prompt(app, header, text) {
  5176. const newPromptModal = new GenericYesNoPrompt(app, header, text);
  5177. return newPromptModal.waitForClose;
  5178. }
  5179. display() {
  5180. this.containerEl.addClass('quickAddModal', 'qaYesNoPrompt');
  5181. this.contentEl.empty();
  5182. this.titleEl.textContent = this.header;
  5183. this.contentEl.createEl('p', { text: this.text });
  5184. const buttonsDiv = this.contentEl.createDiv({ cls: 'yesNoPromptButtonContainer' });
  5185. new obsidian.ButtonComponent(buttonsDiv)
  5186. .setButtonText('No')
  5187. .onClick(() => this.submit(false));
  5188. const yesButton = new obsidian.ButtonComponent(buttonsDiv)
  5189. .setButtonText('Yes')
  5190. .onClick(() => this.submit(true))
  5191. .setWarning();
  5192. yesButton.buttonEl.focus();
  5193. }
  5194. submit(input) {
  5195. this.input = input;
  5196. this.didSubmit = true;
  5197. this.close();
  5198. }
  5199. onClose() {
  5200. super.onClose();
  5201. if (!this.didSubmit)
  5202. this.rejectPromise("No answer given.");
  5203. else
  5204. this.resolvePromise(this.input);
  5205. }
  5206. }
  5207. var top = 'top';
  5208. var bottom = 'bottom';
  5209. var right = 'right';
  5210. var left = 'left';
  5211. var auto = 'auto';
  5212. var basePlacements = [top, bottom, right, left];
  5213. var start = 'start';
  5214. var end = 'end';
  5215. var clippingParents = 'clippingParents';
  5216. var viewport = 'viewport';
  5217. var popper = 'popper';
  5218. var reference = 'reference';
  5219. var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
  5220. return acc.concat([placement + "-" + start, placement + "-" + end]);
  5221. }, []);
  5222. var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
  5223. return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
  5224. }, []); // modifiers that need to read the DOM
  5225. var beforeRead = 'beforeRead';
  5226. var read = 'read';
  5227. var afterRead = 'afterRead'; // pure-logic modifiers
  5228. var beforeMain = 'beforeMain';
  5229. var main = 'main';
  5230. var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
  5231. var beforeWrite = 'beforeWrite';
  5232. var write = 'write';
  5233. var afterWrite = 'afterWrite';
  5234. var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
  5235. function getNodeName(element) {
  5236. return element ? (element.nodeName || '').toLowerCase() : null;
  5237. }
  5238. function getWindow(node) {
  5239. if (node == null) {
  5240. return window;
  5241. }
  5242. if (node.toString() !== '[object Window]') {
  5243. var ownerDocument = node.ownerDocument;
  5244. return ownerDocument ? ownerDocument.defaultView || window : window;
  5245. }
  5246. return node;
  5247. }
  5248. function isElement(node) {
  5249. var OwnElement = getWindow(node).Element;
  5250. return node instanceof OwnElement || node instanceof Element;
  5251. }
  5252. function isHTMLElement(node) {
  5253. var OwnElement = getWindow(node).HTMLElement;
  5254. return node instanceof OwnElement || node instanceof HTMLElement;
  5255. }
  5256. function isShadowRoot(node) {
  5257. // IE 11 has no ShadowRoot
  5258. if (typeof ShadowRoot === 'undefined') {
  5259. return false;
  5260. }
  5261. var OwnElement = getWindow(node).ShadowRoot;
  5262. return node instanceof OwnElement || node instanceof ShadowRoot;
  5263. }
  5264. // and applies them to the HTMLElements such as popper and arrow
  5265. function applyStyles(_ref) {
  5266. var state = _ref.state;
  5267. Object.keys(state.elements).forEach(function (name) {
  5268. var style = state.styles[name] || {};
  5269. var attributes = state.attributes[name] || {};
  5270. var element = state.elements[name]; // arrow is optional + virtual elements
  5271. if (!isHTMLElement(element) || !getNodeName(element)) {
  5272. return;
  5273. } // Flow doesn't support to extend this property, but it's the most
  5274. // effective way to apply styles to an HTMLElement
  5275. // $FlowFixMe[cannot-write]
  5276. Object.assign(element.style, style);
  5277. Object.keys(attributes).forEach(function (name) {
  5278. var value = attributes[name];
  5279. if (value === false) {
  5280. element.removeAttribute(name);
  5281. } else {
  5282. element.setAttribute(name, value === true ? '' : value);
  5283. }
  5284. });
  5285. });
  5286. }
  5287. function effect$2(_ref2) {
  5288. var state = _ref2.state;
  5289. var initialStyles = {
  5290. popper: {
  5291. position: state.options.strategy,
  5292. left: '0',
  5293. top: '0',
  5294. margin: '0'
  5295. },
  5296. arrow: {
  5297. position: 'absolute'
  5298. },
  5299. reference: {}
  5300. };
  5301. Object.assign(state.elements.popper.style, initialStyles.popper);
  5302. state.styles = initialStyles;
  5303. if (state.elements.arrow) {
  5304. Object.assign(state.elements.arrow.style, initialStyles.arrow);
  5305. }
  5306. return function () {
  5307. Object.keys(state.elements).forEach(function (name) {
  5308. var element = state.elements[name];
  5309. var attributes = state.attributes[name] || {};
  5310. var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
  5311. var style = styleProperties.reduce(function (style, property) {
  5312. style[property] = '';
  5313. return style;
  5314. }, {}); // arrow is optional + virtual elements
  5315. if (!isHTMLElement(element) || !getNodeName(element)) {
  5316. return;
  5317. }
  5318. Object.assign(element.style, style);
  5319. Object.keys(attributes).forEach(function (attribute) {
  5320. element.removeAttribute(attribute);
  5321. });
  5322. });
  5323. };
  5324. } // eslint-disable-next-line import/no-unused-modules
  5325. var applyStyles$1 = {
  5326. name: 'applyStyles',
  5327. enabled: true,
  5328. phase: 'write',
  5329. fn: applyStyles,
  5330. effect: effect$2,
  5331. requires: ['computeStyles']
  5332. };
  5333. function getBasePlacement(placement) {
  5334. return placement.split('-')[0];
  5335. }
  5336. var max = Math.max;
  5337. var min = Math.min;
  5338. var round = Math.round;
  5339. function getBoundingClientRect(element, includeScale) {
  5340. if (includeScale === void 0) {
  5341. includeScale = false;
  5342. }
  5343. var rect = element.getBoundingClientRect();
  5344. var scaleX = 1;
  5345. var scaleY = 1;
  5346. if (isHTMLElement(element) && includeScale) {
  5347. var offsetHeight = element.offsetHeight;
  5348. var offsetWidth = element.offsetWidth; // Do not attempt to divide by 0, otherwise we get `Infinity` as scale
  5349. // Fallback to 1 in case both values are `0`
  5350. if (offsetWidth > 0) {
  5351. scaleX = round(rect.width) / offsetWidth || 1;
  5352. }
  5353. if (offsetHeight > 0) {
  5354. scaleY = round(rect.height) / offsetHeight || 1;
  5355. }
  5356. }
  5357. return {
  5358. width: rect.width / scaleX,
  5359. height: rect.height / scaleY,
  5360. top: rect.top / scaleY,
  5361. right: rect.right / scaleX,
  5362. bottom: rect.bottom / scaleY,
  5363. left: rect.left / scaleX,
  5364. x: rect.left / scaleX,
  5365. y: rect.top / scaleY
  5366. };
  5367. }
  5368. // means it doesn't take into account transforms.
  5369. function getLayoutRect(element) {
  5370. var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
  5371. // Fixes https://github.com/popperjs/popper-core/issues/1223
  5372. var width = element.offsetWidth;
  5373. var height = element.offsetHeight;
  5374. if (Math.abs(clientRect.width - width) <= 1) {
  5375. width = clientRect.width;
  5376. }
  5377. if (Math.abs(clientRect.height - height) <= 1) {
  5378. height = clientRect.height;
  5379. }
  5380. return {
  5381. x: element.offsetLeft,
  5382. y: element.offsetTop,
  5383. width: width,
  5384. height: height
  5385. };
  5386. }
  5387. function contains(parent, child) {
  5388. var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
  5389. if (parent.contains(child)) {
  5390. return true;
  5391. } // then fallback to custom implementation with Shadow DOM support
  5392. else if (rootNode && isShadowRoot(rootNode)) {
  5393. var next = child;
  5394. do {
  5395. if (next && parent.isSameNode(next)) {
  5396. return true;
  5397. } // $FlowFixMe[prop-missing]: need a better way to handle this...
  5398. next = next.parentNode || next.host;
  5399. } while (next);
  5400. } // Give up, the result is false
  5401. return false;
  5402. }
  5403. function getComputedStyle$1(element) {
  5404. return getWindow(element).getComputedStyle(element);
  5405. }
  5406. function isTableElement(element) {
  5407. return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
  5408. }
  5409. function getDocumentElement(element) {
  5410. // $FlowFixMe[incompatible-return]: assume body is always available
  5411. return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
  5412. element.document) || window.document).documentElement;
  5413. }
  5414. function getParentNode(element) {
  5415. if (getNodeName(element) === 'html') {
  5416. return element;
  5417. }
  5418. return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
  5419. // $FlowFixMe[incompatible-return]
  5420. // $FlowFixMe[prop-missing]
  5421. element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
  5422. element.parentNode || ( // DOM Element detected
  5423. isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
  5424. // $FlowFixMe[incompatible-call]: HTMLElement is a Node
  5425. getDocumentElement(element) // fallback
  5426. );
  5427. }
  5428. function getTrueOffsetParent(element) {
  5429. if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
  5430. getComputedStyle$1(element).position === 'fixed') {
  5431. return null;
  5432. }
  5433. return element.offsetParent;
  5434. } // `.offsetParent` reports `null` for fixed elements, while absolute elements
  5435. // return the containing block
  5436. function getContainingBlock(element) {
  5437. var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;
  5438. var isIE = navigator.userAgent.indexOf('Trident') !== -1;
  5439. if (isIE && isHTMLElement(element)) {
  5440. // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
  5441. var elementCss = getComputedStyle$1(element);
  5442. if (elementCss.position === 'fixed') {
  5443. return null;
  5444. }
  5445. }
  5446. var currentNode = getParentNode(element);
  5447. if (isShadowRoot(currentNode)) {
  5448. currentNode = currentNode.host;
  5449. }
  5450. while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
  5451. var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that
  5452. // create a containing block.
  5453. // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
  5454. if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
  5455. return currentNode;
  5456. } else {
  5457. currentNode = currentNode.parentNode;
  5458. }
  5459. }
  5460. return null;
  5461. } // Gets the closest ancestor positioned element. Handles some edge cases,
  5462. // such as table ancestors and cross browser bugs.
  5463. function getOffsetParent(element) {
  5464. var window = getWindow(element);
  5465. var offsetParent = getTrueOffsetParent(element);
  5466. while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') {
  5467. offsetParent = getTrueOffsetParent(offsetParent);
  5468. }
  5469. if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) {
  5470. return window;
  5471. }
  5472. return offsetParent || getContainingBlock(element) || window;
  5473. }
  5474. function getMainAxisFromPlacement(placement) {
  5475. return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
  5476. }
  5477. function within(min$1, value, max$1) {
  5478. return max(min$1, min(value, max$1));
  5479. }
  5480. function withinMaxClamp(min, value, max) {
  5481. var v = within(min, value, max);
  5482. return v > max ? max : v;
  5483. }
  5484. function getFreshSideObject() {
  5485. return {
  5486. top: 0,
  5487. right: 0,
  5488. bottom: 0,
  5489. left: 0
  5490. };
  5491. }
  5492. function mergePaddingObject(paddingObject) {
  5493. return Object.assign({}, getFreshSideObject(), paddingObject);
  5494. }
  5495. function expandToHashMap(value, keys) {
  5496. return keys.reduce(function (hashMap, key) {
  5497. hashMap[key] = value;
  5498. return hashMap;
  5499. }, {});
  5500. }
  5501. var toPaddingObject = function toPaddingObject(padding, state) {
  5502. padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
  5503. placement: state.placement
  5504. })) : padding;
  5505. return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
  5506. };
  5507. function arrow(_ref) {
  5508. var _state$modifiersData$;
  5509. var state = _ref.state,
  5510. name = _ref.name,
  5511. options = _ref.options;
  5512. var arrowElement = state.elements.arrow;
  5513. var popperOffsets = state.modifiersData.popperOffsets;
  5514. var basePlacement = getBasePlacement(state.placement);
  5515. var axis = getMainAxisFromPlacement(basePlacement);
  5516. var isVertical = [left, right].indexOf(basePlacement) >= 0;
  5517. var len = isVertical ? 'height' : 'width';
  5518. if (!arrowElement || !popperOffsets) {
  5519. return;
  5520. }
  5521. var paddingObject = toPaddingObject(options.padding, state);
  5522. var arrowRect = getLayoutRect(arrowElement);
  5523. var minProp = axis === 'y' ? top : left;
  5524. var maxProp = axis === 'y' ? bottom : right;
  5525. var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
  5526. var startDiff = popperOffsets[axis] - state.rects.reference[axis];
  5527. var arrowOffsetParent = getOffsetParent(arrowElement);
  5528. var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  5529. var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
  5530. // outside of the popper bounds
  5531. var min = paddingObject[minProp];
  5532. var max = clientSize - arrowRect[len] - paddingObject[maxProp];
  5533. var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  5534. var offset = within(min, center, max); // Prevents breaking syntax highlighting...
  5535. var axisProp = axis;
  5536. state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
  5537. }
  5538. function effect$1(_ref2) {
  5539. var state = _ref2.state,
  5540. options = _ref2.options;
  5541. var _options$element = options.element,
  5542. arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
  5543. if (arrowElement == null) {
  5544. return;
  5545. } // CSS selector
  5546. if (typeof arrowElement === 'string') {
  5547. arrowElement = state.elements.popper.querySelector(arrowElement);
  5548. if (!arrowElement) {
  5549. return;
  5550. }
  5551. }
  5552. if (process.env.NODE_ENV !== "production") {
  5553. if (!isHTMLElement(arrowElement)) {
  5554. console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', 'the arrow.'].join(' '));
  5555. }
  5556. }
  5557. if (!contains(state.elements.popper, arrowElement)) {
  5558. if (process.env.NODE_ENV !== "production") {
  5559. console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', 'element.'].join(' '));
  5560. }
  5561. return;
  5562. }
  5563. state.elements.arrow = arrowElement;
  5564. } // eslint-disable-next-line import/no-unused-modules
  5565. var arrow$1 = {
  5566. name: 'arrow',
  5567. enabled: true,
  5568. phase: 'main',
  5569. fn: arrow,
  5570. effect: effect$1,
  5571. requires: ['popperOffsets'],
  5572. requiresIfExists: ['preventOverflow']
  5573. };
  5574. function getVariation(placement) {
  5575. return placement.split('-')[1];
  5576. }
  5577. var unsetSides = {
  5578. top: 'auto',
  5579. right: 'auto',
  5580. bottom: 'auto',
  5581. left: 'auto'
  5582. }; // Round the offsets to the nearest suitable subpixel based on the DPR.
  5583. // Zooming can change the DPR, but it seems to report a value that will
  5584. // cleanly divide the values into the appropriate subpixels.
  5585. function roundOffsetsByDPR(_ref) {
  5586. var x = _ref.x,
  5587. y = _ref.y;
  5588. var win = window;
  5589. var dpr = win.devicePixelRatio || 1;
  5590. return {
  5591. x: round(x * dpr) / dpr || 0,
  5592. y: round(y * dpr) / dpr || 0
  5593. };
  5594. }
  5595. function mapToStyles(_ref2) {
  5596. var _Object$assign2;
  5597. var popper = _ref2.popper,
  5598. popperRect = _ref2.popperRect,
  5599. placement = _ref2.placement,
  5600. variation = _ref2.variation,
  5601. offsets = _ref2.offsets,
  5602. position = _ref2.position,
  5603. gpuAcceleration = _ref2.gpuAcceleration,
  5604. adaptive = _ref2.adaptive,
  5605. roundOffsets = _ref2.roundOffsets,
  5606. isFixed = _ref2.isFixed;
  5607. var _offsets$x = offsets.x,
  5608. x = _offsets$x === void 0 ? 0 : _offsets$x,
  5609. _offsets$y = offsets.y,
  5610. y = _offsets$y === void 0 ? 0 : _offsets$y;
  5611. var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
  5612. x: x,
  5613. y: y
  5614. }) : {
  5615. x: x,
  5616. y: y
  5617. };
  5618. x = _ref3.x;
  5619. y = _ref3.y;
  5620. var hasX = offsets.hasOwnProperty('x');
  5621. var hasY = offsets.hasOwnProperty('y');
  5622. var sideX = left;
  5623. var sideY = top;
  5624. var win = window;
  5625. if (adaptive) {
  5626. var offsetParent = getOffsetParent(popper);
  5627. var heightProp = 'clientHeight';
  5628. var widthProp = 'clientWidth';
  5629. if (offsetParent === getWindow(popper)) {
  5630. offsetParent = getDocumentElement(popper);
  5631. if (getComputedStyle$1(offsetParent).position !== 'static' && position === 'absolute') {
  5632. heightProp = 'scrollHeight';
  5633. widthProp = 'scrollWidth';
  5634. }
  5635. } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
  5636. offsetParent = offsetParent;
  5637. if (placement === top || (placement === left || placement === right) && variation === end) {
  5638. sideY = bottom;
  5639. var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]
  5640. offsetParent[heightProp];
  5641. y -= offsetY - popperRect.height;
  5642. y *= gpuAcceleration ? 1 : -1;
  5643. }
  5644. if (placement === left || (placement === top || placement === bottom) && variation === end) {
  5645. sideX = right;
  5646. var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]
  5647. offsetParent[widthProp];
  5648. x -= offsetX - popperRect.width;
  5649. x *= gpuAcceleration ? 1 : -1;
  5650. }
  5651. }
  5652. var commonStyles = Object.assign({
  5653. position: position
  5654. }, adaptive && unsetSides);
  5655. var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
  5656. x: x,
  5657. y: y
  5658. }) : {
  5659. x: x,
  5660. y: y
  5661. };
  5662. x = _ref4.x;
  5663. y = _ref4.y;
  5664. if (gpuAcceleration) {
  5665. var _Object$assign;
  5666. return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  5667. }
  5668. return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
  5669. }
  5670. function computeStyles(_ref5) {
  5671. var state = _ref5.state,
  5672. options = _ref5.options;
  5673. var _options$gpuAccelerat = options.gpuAcceleration,
  5674. gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
  5675. _options$adaptive = options.adaptive,
  5676. adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
  5677. _options$roundOffsets = options.roundOffsets,
  5678. roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  5679. if (process.env.NODE_ENV !== "production") {
  5680. var transitionProperty = getComputedStyle$1(state.elements.popper).transitionProperty || '';
  5681. if (adaptive && ['transform', 'top', 'right', 'bottom', 'left'].some(function (property) {
  5682. return transitionProperty.indexOf(property) >= 0;
  5683. })) {
  5684. console.warn(['Popper: Detected CSS transitions on at least one of the following', 'CSS properties: "transform", "top", "right", "bottom", "left".', '\n\n', 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', 'for smooth transitions, or remove these properties from the CSS', 'transition declaration on the popper element if only transitioning', 'opacity or background-color for example.', '\n\n', 'We recommend using the popper element as a wrapper around an inner', 'element that can have any CSS property transitioned for animations.'].join(' '));
  5685. }
  5686. }
  5687. var commonStyles = {
  5688. placement: getBasePlacement(state.placement),
  5689. variation: getVariation(state.placement),
  5690. popper: state.elements.popper,
  5691. popperRect: state.rects.popper,
  5692. gpuAcceleration: gpuAcceleration,
  5693. isFixed: state.options.strategy === 'fixed'
  5694. };
  5695. if (state.modifiersData.popperOffsets != null) {
  5696. state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
  5697. offsets: state.modifiersData.popperOffsets,
  5698. position: state.options.strategy,
  5699. adaptive: adaptive,
  5700. roundOffsets: roundOffsets
  5701. })));
  5702. }
  5703. if (state.modifiersData.arrow != null) {
  5704. state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
  5705. offsets: state.modifiersData.arrow,
  5706. position: 'absolute',
  5707. adaptive: false,
  5708. roundOffsets: roundOffsets
  5709. })));
  5710. }
  5711. state.attributes.popper = Object.assign({}, state.attributes.popper, {
  5712. 'data-popper-placement': state.placement
  5713. });
  5714. } // eslint-disable-next-line import/no-unused-modules
  5715. var computeStyles$1 = {
  5716. name: 'computeStyles',
  5717. enabled: true,
  5718. phase: 'beforeWrite',
  5719. fn: computeStyles,
  5720. data: {}
  5721. };
  5722. var passive = {
  5723. passive: true
  5724. };
  5725. function effect(_ref) {
  5726. var state = _ref.state,
  5727. instance = _ref.instance,
  5728. options = _ref.options;
  5729. var _options$scroll = options.scroll,
  5730. scroll = _options$scroll === void 0 ? true : _options$scroll,
  5731. _options$resize = options.resize,
  5732. resize = _options$resize === void 0 ? true : _options$resize;
  5733. var window = getWindow(state.elements.popper);
  5734. var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
  5735. if (scroll) {
  5736. scrollParents.forEach(function (scrollParent) {
  5737. scrollParent.addEventListener('scroll', instance.update, passive);
  5738. });
  5739. }
  5740. if (resize) {
  5741. window.addEventListener('resize', instance.update, passive);
  5742. }
  5743. return function () {
  5744. if (scroll) {
  5745. scrollParents.forEach(function (scrollParent) {
  5746. scrollParent.removeEventListener('scroll', instance.update, passive);
  5747. });
  5748. }
  5749. if (resize) {
  5750. window.removeEventListener('resize', instance.update, passive);
  5751. }
  5752. };
  5753. } // eslint-disable-next-line import/no-unused-modules
  5754. var eventListeners = {
  5755. name: 'eventListeners',
  5756. enabled: true,
  5757. phase: 'write',
  5758. fn: function fn() {},
  5759. effect: effect,
  5760. data: {}
  5761. };
  5762. var hash$1 = {
  5763. left: 'right',
  5764. right: 'left',
  5765. bottom: 'top',
  5766. top: 'bottom'
  5767. };
  5768. function getOppositePlacement(placement) {
  5769. return placement.replace(/left|right|bottom|top/g, function (matched) {
  5770. return hash$1[matched];
  5771. });
  5772. }
  5773. var hash = {
  5774. start: 'end',
  5775. end: 'start'
  5776. };
  5777. function getOppositeVariationPlacement(placement) {
  5778. return placement.replace(/start|end/g, function (matched) {
  5779. return hash[matched];
  5780. });
  5781. }
  5782. function getWindowScroll(node) {
  5783. var win = getWindow(node);
  5784. var scrollLeft = win.pageXOffset;
  5785. var scrollTop = win.pageYOffset;
  5786. return {
  5787. scrollLeft: scrollLeft,
  5788. scrollTop: scrollTop
  5789. };
  5790. }
  5791. function getWindowScrollBarX(element) {
  5792. // If <html> has a CSS width greater than the viewport, then this will be
  5793. // incorrect for RTL.
  5794. // Popper 1 is broken in this case and never had a bug report so let's assume
  5795. // it's not an issue. I don't think anyone ever specifies width on <html>
  5796. // anyway.
  5797. // Browsers where the left scrollbar doesn't cause an issue report `0` for
  5798. // this (e.g. Edge 2019, IE11, Safari)
  5799. return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
  5800. }
  5801. function getViewportRect(element) {
  5802. var win = getWindow(element);
  5803. var html = getDocumentElement(element);
  5804. var visualViewport = win.visualViewport;
  5805. var width = html.clientWidth;
  5806. var height = html.clientHeight;
  5807. var x = 0;
  5808. var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
  5809. // can be obscured underneath it.
  5810. // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
  5811. // if it isn't open, so if this isn't available, the popper will be detected
  5812. // to overflow the bottom of the screen too early.
  5813. if (visualViewport) {
  5814. width = visualViewport.width;
  5815. height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently)
  5816. // In Chrome, it returns a value very close to 0 (+/-) but contains rounding
  5817. // errors due to floating point numbers, so we need to check precision.
  5818. // Safari returns a number <= 0, usually < -1 when pinch-zoomed
  5819. // Feature detection fails in mobile emulation mode in Chrome.
  5820. // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
  5821. // 0.001
  5822. // Fallback here: "Not Safari" userAgent
  5823. if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  5824. x = visualViewport.offsetLeft;
  5825. y = visualViewport.offsetTop;
  5826. }
  5827. }
  5828. return {
  5829. width: width,
  5830. height: height,
  5831. x: x + getWindowScrollBarX(element),
  5832. y: y
  5833. };
  5834. }
  5835. // of the `<html>` and `<body>` rect bounds if horizontally scrollable
  5836. function getDocumentRect(element) {
  5837. var _element$ownerDocumen;
  5838. var html = getDocumentElement(element);
  5839. var winScroll = getWindowScroll(element);
  5840. var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  5841. var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  5842. var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  5843. var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  5844. var y = -winScroll.scrollTop;
  5845. if (getComputedStyle$1(body || html).direction === 'rtl') {
  5846. x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  5847. }
  5848. return {
  5849. width: width,
  5850. height: height,
  5851. x: x,
  5852. y: y
  5853. };
  5854. }
  5855. function isScrollParent(element) {
  5856. // Firefox wants us to check `-x` and `-y` variations as well
  5857. var _getComputedStyle = getComputedStyle$1(element),
  5858. overflow = _getComputedStyle.overflow,
  5859. overflowX = _getComputedStyle.overflowX,
  5860. overflowY = _getComputedStyle.overflowY;
  5861. return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
  5862. }
  5863. function getScrollParent(node) {
  5864. if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
  5865. // $FlowFixMe[incompatible-return]: assume body is always available
  5866. return node.ownerDocument.body;
  5867. }
  5868. if (isHTMLElement(node) && isScrollParent(node)) {
  5869. return node;
  5870. }
  5871. return getScrollParent(getParentNode(node));
  5872. }
  5873. /*
  5874. given a DOM element, return the list of all scroll parents, up the list of ancesors
  5875. until we get to the top window object. This list is what we attach scroll listeners
  5876. to, because if any of these parent elements scroll, we'll need to re-calculate the
  5877. reference element's position.
  5878. */
  5879. function listScrollParents(element, list) {
  5880. var _element$ownerDocumen;
  5881. if (list === void 0) {
  5882. list = [];
  5883. }
  5884. var scrollParent = getScrollParent(element);
  5885. var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  5886. var win = getWindow(scrollParent);
  5887. var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  5888. var updatedList = list.concat(target);
  5889. return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
  5890. updatedList.concat(listScrollParents(getParentNode(target)));
  5891. }
  5892. function rectToClientRect(rect) {
  5893. return Object.assign({}, rect, {
  5894. left: rect.x,
  5895. top: rect.y,
  5896. right: rect.x + rect.width,
  5897. bottom: rect.y + rect.height
  5898. });
  5899. }
  5900. function getInnerBoundingClientRect(element) {
  5901. var rect = getBoundingClientRect(element);
  5902. rect.top = rect.top + element.clientTop;
  5903. rect.left = rect.left + element.clientLeft;
  5904. rect.bottom = rect.top + element.clientHeight;
  5905. rect.right = rect.left + element.clientWidth;
  5906. rect.width = element.clientWidth;
  5907. rect.height = element.clientHeight;
  5908. rect.x = rect.left;
  5909. rect.y = rect.top;
  5910. return rect;
  5911. }
  5912. function getClientRectFromMixedType(element, clippingParent) {
  5913. return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
  5914. } // A "clipping parent" is an overflowable container with the characteristic of
  5915. // clipping (or hiding) overflowing elements with a position different from
  5916. // `initial`
  5917. function getClippingParents(element) {
  5918. var clippingParents = listScrollParents(getParentNode(element));
  5919. var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0;
  5920. var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
  5921. if (!isElement(clipperElement)) {
  5922. return [];
  5923. } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
  5924. return clippingParents.filter(function (clippingParent) {
  5925. return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
  5926. });
  5927. } // Gets the maximum area that the element is visible in due to any number of
  5928. // clipping parents
  5929. function getClippingRect(element, boundary, rootBoundary) {
  5930. var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
  5931. var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
  5932. var firstClippingParent = clippingParents[0];
  5933. var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
  5934. var rect = getClientRectFromMixedType(element, clippingParent);
  5935. accRect.top = max(rect.top, accRect.top);
  5936. accRect.right = min(rect.right, accRect.right);
  5937. accRect.bottom = min(rect.bottom, accRect.bottom);
  5938. accRect.left = max(rect.left, accRect.left);
  5939. return accRect;
  5940. }, getClientRectFromMixedType(element, firstClippingParent));
  5941. clippingRect.width = clippingRect.right - clippingRect.left;
  5942. clippingRect.height = clippingRect.bottom - clippingRect.top;
  5943. clippingRect.x = clippingRect.left;
  5944. clippingRect.y = clippingRect.top;
  5945. return clippingRect;
  5946. }
  5947. function computeOffsets(_ref) {
  5948. var reference = _ref.reference,
  5949. element = _ref.element,
  5950. placement = _ref.placement;
  5951. var basePlacement = placement ? getBasePlacement(placement) : null;
  5952. var variation = placement ? getVariation(placement) : null;
  5953. var commonX = reference.x + reference.width / 2 - element.width / 2;
  5954. var commonY = reference.y + reference.height / 2 - element.height / 2;
  5955. var offsets;
  5956. switch (basePlacement) {
  5957. case top:
  5958. offsets = {
  5959. x: commonX,
  5960. y: reference.y - element.height
  5961. };
  5962. break;
  5963. case bottom:
  5964. offsets = {
  5965. x: commonX,
  5966. y: reference.y + reference.height
  5967. };
  5968. break;
  5969. case right:
  5970. offsets = {
  5971. x: reference.x + reference.width,
  5972. y: commonY
  5973. };
  5974. break;
  5975. case left:
  5976. offsets = {
  5977. x: reference.x - element.width,
  5978. y: commonY
  5979. };
  5980. break;
  5981. default:
  5982. offsets = {
  5983. x: reference.x,
  5984. y: reference.y
  5985. };
  5986. }
  5987. var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
  5988. if (mainAxis != null) {
  5989. var len = mainAxis === 'y' ? 'height' : 'width';
  5990. switch (variation) {
  5991. case start:
  5992. offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
  5993. break;
  5994. case end:
  5995. offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
  5996. break;
  5997. }
  5998. }
  5999. return offsets;
  6000. }
  6001. function detectOverflow(state, options) {
  6002. if (options === void 0) {
  6003. options = {};
  6004. }
  6005. var _options = options,
  6006. _options$placement = _options.placement,
  6007. placement = _options$placement === void 0 ? state.placement : _options$placement,
  6008. _options$boundary = _options.boundary,
  6009. boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
  6010. _options$rootBoundary = _options.rootBoundary,
  6011. rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
  6012. _options$elementConte = _options.elementContext,
  6013. elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
  6014. _options$altBoundary = _options.altBoundary,
  6015. altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
  6016. _options$padding = _options.padding,
  6017. padding = _options$padding === void 0 ? 0 : _options$padding;
  6018. var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
  6019. var altContext = elementContext === popper ? reference : popper;
  6020. var popperRect = state.rects.popper;
  6021. var element = state.elements[altBoundary ? altContext : elementContext];
  6022. var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
  6023. var referenceClientRect = getBoundingClientRect(state.elements.reference);
  6024. var popperOffsets = computeOffsets({
  6025. reference: referenceClientRect,
  6026. element: popperRect,
  6027. strategy: 'absolute',
  6028. placement: placement
  6029. });
  6030. var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
  6031. var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
  6032. // 0 or negative = within the clipping rect
  6033. var overflowOffsets = {
  6034. top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
  6035. bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
  6036. left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
  6037. right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  6038. };
  6039. var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
  6040. if (elementContext === popper && offsetData) {
  6041. var offset = offsetData[placement];
  6042. Object.keys(overflowOffsets).forEach(function (key) {
  6043. var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
  6044. var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
  6045. overflowOffsets[key] += offset[axis] * multiply;
  6046. });
  6047. }
  6048. return overflowOffsets;
  6049. }
  6050. function computeAutoPlacement(state, options) {
  6051. if (options === void 0) {
  6052. options = {};
  6053. }
  6054. var _options = options,
  6055. placement = _options.placement,
  6056. boundary = _options.boundary,
  6057. rootBoundary = _options.rootBoundary,
  6058. padding = _options.padding,
  6059. flipVariations = _options.flipVariations,
  6060. _options$allowedAutoP = _options.allowedAutoPlacements,
  6061. allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
  6062. var variation = getVariation(placement);
  6063. var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
  6064. return getVariation(placement) === variation;
  6065. }) : basePlacements;
  6066. var allowedPlacements = placements$1.filter(function (placement) {
  6067. return allowedAutoPlacements.indexOf(placement) >= 0;
  6068. });
  6069. if (allowedPlacements.length === 0) {
  6070. allowedPlacements = placements$1;
  6071. if (process.env.NODE_ENV !== "production") {
  6072. console.error(['Popper: The `allowedAutoPlacements` option did not allow any', 'placements. Ensure the `placement` option matches the variation', 'of the allowed placements.', 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(' '));
  6073. }
  6074. } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
  6075. var overflows = allowedPlacements.reduce(function (acc, placement) {
  6076. acc[placement] = detectOverflow(state, {
  6077. placement: placement,
  6078. boundary: boundary,
  6079. rootBoundary: rootBoundary,
  6080. padding: padding
  6081. })[getBasePlacement(placement)];
  6082. return acc;
  6083. }, {});
  6084. return Object.keys(overflows).sort(function (a, b) {
  6085. return overflows[a] - overflows[b];
  6086. });
  6087. }
  6088. function getExpandedFallbackPlacements(placement) {
  6089. if (getBasePlacement(placement) === auto) {
  6090. return [];
  6091. }
  6092. var oppositePlacement = getOppositePlacement(placement);
  6093. return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
  6094. }
  6095. function flip(_ref) {
  6096. var state = _ref.state,
  6097. options = _ref.options,
  6098. name = _ref.name;
  6099. if (state.modifiersData[name]._skip) {
  6100. return;
  6101. }
  6102. var _options$mainAxis = options.mainAxis,
  6103. checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
  6104. _options$altAxis = options.altAxis,
  6105. checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
  6106. specifiedFallbackPlacements = options.fallbackPlacements,
  6107. padding = options.padding,
  6108. boundary = options.boundary,
  6109. rootBoundary = options.rootBoundary,
  6110. altBoundary = options.altBoundary,
  6111. _options$flipVariatio = options.flipVariations,
  6112. flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
  6113. allowedAutoPlacements = options.allowedAutoPlacements;
  6114. var preferredPlacement = state.options.placement;
  6115. var basePlacement = getBasePlacement(preferredPlacement);
  6116. var isBasePlacement = basePlacement === preferredPlacement;
  6117. var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  6118. var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
  6119. return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
  6120. placement: placement,
  6121. boundary: boundary,
  6122. rootBoundary: rootBoundary,
  6123. padding: padding,
  6124. flipVariations: flipVariations,
  6125. allowedAutoPlacements: allowedAutoPlacements
  6126. }) : placement);
  6127. }, []);
  6128. var referenceRect = state.rects.reference;
  6129. var popperRect = state.rects.popper;
  6130. var checksMap = new Map();
  6131. var makeFallbackChecks = true;
  6132. var firstFittingPlacement = placements[0];
  6133. for (var i = 0; i < placements.length; i++) {
  6134. var placement = placements[i];
  6135. var _basePlacement = getBasePlacement(placement);
  6136. var isStartVariation = getVariation(placement) === start;
  6137. var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
  6138. var len = isVertical ? 'width' : 'height';
  6139. var overflow = detectOverflow(state, {
  6140. placement: placement,
  6141. boundary: boundary,
  6142. rootBoundary: rootBoundary,
  6143. altBoundary: altBoundary,
  6144. padding: padding
  6145. });
  6146. var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
  6147. if (referenceRect[len] > popperRect[len]) {
  6148. mainVariationSide = getOppositePlacement(mainVariationSide);
  6149. }
  6150. var altVariationSide = getOppositePlacement(mainVariationSide);
  6151. var checks = [];
  6152. if (checkMainAxis) {
  6153. checks.push(overflow[_basePlacement] <= 0);
  6154. }
  6155. if (checkAltAxis) {
  6156. checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
  6157. }
  6158. if (checks.every(function (check) {
  6159. return check;
  6160. })) {
  6161. firstFittingPlacement = placement;
  6162. makeFallbackChecks = false;
  6163. break;
  6164. }
  6165. checksMap.set(placement, checks);
  6166. }
  6167. if (makeFallbackChecks) {
  6168. // `2` may be desired in some cases – research later
  6169. var numberOfChecks = flipVariations ? 3 : 1;
  6170. var _loop = function _loop(_i) {
  6171. var fittingPlacement = placements.find(function (placement) {
  6172. var checks = checksMap.get(placement);
  6173. if (checks) {
  6174. return checks.slice(0, _i).every(function (check) {
  6175. return check;
  6176. });
  6177. }
  6178. });
  6179. if (fittingPlacement) {
  6180. firstFittingPlacement = fittingPlacement;
  6181. return "break";
  6182. }
  6183. };
  6184. for (var _i = numberOfChecks; _i > 0; _i--) {
  6185. var _ret = _loop(_i);
  6186. if (_ret === "break") break;
  6187. }
  6188. }
  6189. if (state.placement !== firstFittingPlacement) {
  6190. state.modifiersData[name]._skip = true;
  6191. state.placement = firstFittingPlacement;
  6192. state.reset = true;
  6193. }
  6194. } // eslint-disable-next-line import/no-unused-modules
  6195. var flip$1 = {
  6196. name: 'flip',
  6197. enabled: true,
  6198. phase: 'main',
  6199. fn: flip,
  6200. requiresIfExists: ['offset'],
  6201. data: {
  6202. _skip: false
  6203. }
  6204. };
  6205. function getSideOffsets(overflow, rect, preventedOffsets) {
  6206. if (preventedOffsets === void 0) {
  6207. preventedOffsets = {
  6208. x: 0,
  6209. y: 0
  6210. };
  6211. }
  6212. return {
  6213. top: overflow.top - rect.height - preventedOffsets.y,
  6214. right: overflow.right - rect.width + preventedOffsets.x,
  6215. bottom: overflow.bottom - rect.height + preventedOffsets.y,
  6216. left: overflow.left - rect.width - preventedOffsets.x
  6217. };
  6218. }
  6219. function isAnySideFullyClipped(overflow) {
  6220. return [top, right, bottom, left].some(function (side) {
  6221. return overflow[side] >= 0;
  6222. });
  6223. }
  6224. function hide(_ref) {
  6225. var state = _ref.state,
  6226. name = _ref.name;
  6227. var referenceRect = state.rects.reference;
  6228. var popperRect = state.rects.popper;
  6229. var preventedOffsets = state.modifiersData.preventOverflow;
  6230. var referenceOverflow = detectOverflow(state, {
  6231. elementContext: 'reference'
  6232. });
  6233. var popperAltOverflow = detectOverflow(state, {
  6234. altBoundary: true
  6235. });
  6236. var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  6237. var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  6238. var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  6239. var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  6240. state.modifiersData[name] = {
  6241. referenceClippingOffsets: referenceClippingOffsets,
  6242. popperEscapeOffsets: popperEscapeOffsets,
  6243. isReferenceHidden: isReferenceHidden,
  6244. hasPopperEscaped: hasPopperEscaped
  6245. };
  6246. state.attributes.popper = Object.assign({}, state.attributes.popper, {
  6247. 'data-popper-reference-hidden': isReferenceHidden,
  6248. 'data-popper-escaped': hasPopperEscaped
  6249. });
  6250. } // eslint-disable-next-line import/no-unused-modules
  6251. var hide$1 = {
  6252. name: 'hide',
  6253. enabled: true,
  6254. phase: 'main',
  6255. requiresIfExists: ['preventOverflow'],
  6256. fn: hide
  6257. };
  6258. function distanceAndSkiddingToXY(placement, rects, offset) {
  6259. var basePlacement = getBasePlacement(placement);
  6260. var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
  6261. var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
  6262. placement: placement
  6263. })) : offset,
  6264. skidding = _ref[0],
  6265. distance = _ref[1];
  6266. skidding = skidding || 0;
  6267. distance = (distance || 0) * invertDistance;
  6268. return [left, right].indexOf(basePlacement) >= 0 ? {
  6269. x: distance,
  6270. y: skidding
  6271. } : {
  6272. x: skidding,
  6273. y: distance
  6274. };
  6275. }
  6276. function offset(_ref2) {
  6277. var state = _ref2.state,
  6278. options = _ref2.options,
  6279. name = _ref2.name;
  6280. var _options$offset = options.offset,
  6281. offset = _options$offset === void 0 ? [0, 0] : _options$offset;
  6282. var data = placements.reduce(function (acc, placement) {
  6283. acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
  6284. return acc;
  6285. }, {});
  6286. var _data$state$placement = data[state.placement],
  6287. x = _data$state$placement.x,
  6288. y = _data$state$placement.y;
  6289. if (state.modifiersData.popperOffsets != null) {
  6290. state.modifiersData.popperOffsets.x += x;
  6291. state.modifiersData.popperOffsets.y += y;
  6292. }
  6293. state.modifiersData[name] = data;
  6294. } // eslint-disable-next-line import/no-unused-modules
  6295. var offset$1 = {
  6296. name: 'offset',
  6297. enabled: true,
  6298. phase: 'main',
  6299. requires: ['popperOffsets'],
  6300. fn: offset
  6301. };
  6302. function popperOffsets(_ref) {
  6303. var state = _ref.state,
  6304. name = _ref.name;
  6305. // Offsets are the actual position the popper needs to have to be
  6306. // properly positioned near its reference element
  6307. // This is the most basic placement, and will be adjusted by
  6308. // the modifiers in the next step
  6309. state.modifiersData[name] = computeOffsets({
  6310. reference: state.rects.reference,
  6311. element: state.rects.popper,
  6312. strategy: 'absolute',
  6313. placement: state.placement
  6314. });
  6315. } // eslint-disable-next-line import/no-unused-modules
  6316. var popperOffsets$1 = {
  6317. name: 'popperOffsets',
  6318. enabled: true,
  6319. phase: 'read',
  6320. fn: popperOffsets,
  6321. data: {}
  6322. };
  6323. function getAltAxis(axis) {
  6324. return axis === 'x' ? 'y' : 'x';
  6325. }
  6326. function preventOverflow(_ref) {
  6327. var state = _ref.state,
  6328. options = _ref.options,
  6329. name = _ref.name;
  6330. var _options$mainAxis = options.mainAxis,
  6331. checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
  6332. _options$altAxis = options.altAxis,
  6333. checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
  6334. boundary = options.boundary,
  6335. rootBoundary = options.rootBoundary,
  6336. altBoundary = options.altBoundary,
  6337. padding = options.padding,
  6338. _options$tether = options.tether,
  6339. tether = _options$tether === void 0 ? true : _options$tether,
  6340. _options$tetherOffset = options.tetherOffset,
  6341. tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  6342. var overflow = detectOverflow(state, {
  6343. boundary: boundary,
  6344. rootBoundary: rootBoundary,
  6345. padding: padding,
  6346. altBoundary: altBoundary
  6347. });
  6348. var basePlacement = getBasePlacement(state.placement);
  6349. var variation = getVariation(state.placement);
  6350. var isBasePlacement = !variation;
  6351. var mainAxis = getMainAxisFromPlacement(basePlacement);
  6352. var altAxis = getAltAxis(mainAxis);
  6353. var popperOffsets = state.modifiersData.popperOffsets;
  6354. var referenceRect = state.rects.reference;
  6355. var popperRect = state.rects.popper;
  6356. var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
  6357. placement: state.placement
  6358. })) : tetherOffset;
  6359. var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
  6360. mainAxis: tetherOffsetValue,
  6361. altAxis: tetherOffsetValue
  6362. } : Object.assign({
  6363. mainAxis: 0,
  6364. altAxis: 0
  6365. }, tetherOffsetValue);
  6366. var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
  6367. var data = {
  6368. x: 0,
  6369. y: 0
  6370. };
  6371. if (!popperOffsets) {
  6372. return;
  6373. }
  6374. if (checkMainAxis) {
  6375. var _offsetModifierState$;
  6376. var mainSide = mainAxis === 'y' ? top : left;
  6377. var altSide = mainAxis === 'y' ? bottom : right;
  6378. var len = mainAxis === 'y' ? 'height' : 'width';
  6379. var offset = popperOffsets[mainAxis];
  6380. var min$1 = offset + overflow[mainSide];
  6381. var max$1 = offset - overflow[altSide];
  6382. var additive = tether ? -popperRect[len] / 2 : 0;
  6383. var minLen = variation === start ? referenceRect[len] : popperRect[len];
  6384. var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
  6385. // outside the reference bounds
  6386. var arrowElement = state.elements.arrow;
  6387. var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
  6388. width: 0,
  6389. height: 0
  6390. };
  6391. var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
  6392. var arrowPaddingMin = arrowPaddingObject[mainSide];
  6393. var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
  6394. // to include its full size in the calculation. If the reference is small
  6395. // and near the edge of a boundary, the popper can overflow even if the
  6396. // reference is not overflowing as well (e.g. virtual elements with no
  6397. // width or height)
  6398. var arrowLen = within(0, referenceRect[len], arrowRect[len]);
  6399. var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
  6400. var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
  6401. var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
  6402. var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
  6403. var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
  6404. var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
  6405. var tetherMax = offset + maxOffset - offsetModifierValue;
  6406. var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
  6407. popperOffsets[mainAxis] = preventedOffset;
  6408. data[mainAxis] = preventedOffset - offset;
  6409. }
  6410. if (checkAltAxis) {
  6411. var _offsetModifierState$2;
  6412. var _mainSide = mainAxis === 'x' ? top : left;
  6413. var _altSide = mainAxis === 'x' ? bottom : right;
  6414. var _offset = popperOffsets[altAxis];
  6415. var _len = altAxis === 'y' ? 'height' : 'width';
  6416. var _min = _offset + overflow[_mainSide];
  6417. var _max = _offset - overflow[_altSide];
  6418. var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
  6419. var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
  6420. var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
  6421. var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
  6422. var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
  6423. popperOffsets[altAxis] = _preventedOffset;
  6424. data[altAxis] = _preventedOffset - _offset;
  6425. }
  6426. state.modifiersData[name] = data;
  6427. } // eslint-disable-next-line import/no-unused-modules
  6428. var preventOverflow$1 = {
  6429. name: 'preventOverflow',
  6430. enabled: true,
  6431. phase: 'main',
  6432. fn: preventOverflow,
  6433. requiresIfExists: ['offset']
  6434. };
  6435. function getHTMLElementScroll(element) {
  6436. return {
  6437. scrollLeft: element.scrollLeft,
  6438. scrollTop: element.scrollTop
  6439. };
  6440. }
  6441. function getNodeScroll(node) {
  6442. if (node === getWindow(node) || !isHTMLElement(node)) {
  6443. return getWindowScroll(node);
  6444. } else {
  6445. return getHTMLElementScroll(node);
  6446. }
  6447. }
  6448. function isElementScaled(element) {
  6449. var rect = element.getBoundingClientRect();
  6450. var scaleX = round(rect.width) / element.offsetWidth || 1;
  6451. var scaleY = round(rect.height) / element.offsetHeight || 1;
  6452. return scaleX !== 1 || scaleY !== 1;
  6453. } // Returns the composite rect of an element relative to its offsetParent.
  6454. // Composite means it takes into account transforms as well as layout.
  6455. function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  6456. if (isFixed === void 0) {
  6457. isFixed = false;
  6458. }
  6459. var isOffsetParentAnElement = isHTMLElement(offsetParent);
  6460. var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
  6461. var documentElement = getDocumentElement(offsetParent);
  6462. var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled);
  6463. var scroll = {
  6464. scrollLeft: 0,
  6465. scrollTop: 0
  6466. };
  6467. var offsets = {
  6468. x: 0,
  6469. y: 0
  6470. };
  6471. if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
  6472. if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
  6473. isScrollParent(documentElement)) {
  6474. scroll = getNodeScroll(offsetParent);
  6475. }
  6476. if (isHTMLElement(offsetParent)) {
  6477. offsets = getBoundingClientRect(offsetParent, true);
  6478. offsets.x += offsetParent.clientLeft;
  6479. offsets.y += offsetParent.clientTop;
  6480. } else if (documentElement) {
  6481. offsets.x = getWindowScrollBarX(documentElement);
  6482. }
  6483. }
  6484. return {
  6485. x: rect.left + scroll.scrollLeft - offsets.x,
  6486. y: rect.top + scroll.scrollTop - offsets.y,
  6487. width: rect.width,
  6488. height: rect.height
  6489. };
  6490. }
  6491. function order(modifiers) {
  6492. var map = new Map();
  6493. var visited = new Set();
  6494. var result = [];
  6495. modifiers.forEach(function (modifier) {
  6496. map.set(modifier.name, modifier);
  6497. }); // On visiting object, check for its dependencies and visit them recursively
  6498. function sort(modifier) {
  6499. visited.add(modifier.name);
  6500. var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
  6501. requires.forEach(function (dep) {
  6502. if (!visited.has(dep)) {
  6503. var depModifier = map.get(dep);
  6504. if (depModifier) {
  6505. sort(depModifier);
  6506. }
  6507. }
  6508. });
  6509. result.push(modifier);
  6510. }
  6511. modifiers.forEach(function (modifier) {
  6512. if (!visited.has(modifier.name)) {
  6513. // check for visited object
  6514. sort(modifier);
  6515. }
  6516. });
  6517. return result;
  6518. }
  6519. function orderModifiers(modifiers) {
  6520. // order based on dependencies
  6521. var orderedModifiers = order(modifiers); // order based on phase
  6522. return modifierPhases.reduce(function (acc, phase) {
  6523. return acc.concat(orderedModifiers.filter(function (modifier) {
  6524. return modifier.phase === phase;
  6525. }));
  6526. }, []);
  6527. }
  6528. function debounce(fn) {
  6529. var pending;
  6530. return function () {
  6531. if (!pending) {
  6532. pending = new Promise(function (resolve) {
  6533. Promise.resolve().then(function () {
  6534. pending = undefined;
  6535. resolve(fn());
  6536. });
  6537. });
  6538. }
  6539. return pending;
  6540. };
  6541. }
  6542. function format$1(str) {
  6543. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6544. args[_key - 1] = arguments[_key];
  6545. }
  6546. return [].concat(args).reduce(function (p, c) {
  6547. return p.replace(/%s/, c);
  6548. }, str);
  6549. }
  6550. var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
  6551. var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
  6552. var VALID_PROPERTIES = ['name', 'enabled', 'phase', 'fn', 'effect', 'requires', 'options'];
  6553. function validateModifiers(modifiers) {
  6554. modifiers.forEach(function (modifier) {
  6555. [].concat(Object.keys(modifier), VALID_PROPERTIES) // IE11-compatible replacement for `new Set(iterable)`
  6556. .filter(function (value, index, self) {
  6557. return self.indexOf(value) === index;
  6558. }).forEach(function (key) {
  6559. switch (key) {
  6560. case 'name':
  6561. if (typeof modifier.name !== 'string') {
  6562. console.error(format$1(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', "\"" + String(modifier.name) + "\""));
  6563. }
  6564. break;
  6565. case 'enabled':
  6566. if (typeof modifier.enabled !== 'boolean') {
  6567. console.error(format$1(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', "\"" + String(modifier.enabled) + "\""));
  6568. }
  6569. break;
  6570. case 'phase':
  6571. if (modifierPhases.indexOf(modifier.phase) < 0) {
  6572. console.error(format$1(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(', '), "\"" + String(modifier.phase) + "\""));
  6573. }
  6574. break;
  6575. case 'fn':
  6576. if (typeof modifier.fn !== 'function') {
  6577. console.error(format$1(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', "\"" + String(modifier.fn) + "\""));
  6578. }
  6579. break;
  6580. case 'effect':
  6581. if (modifier.effect != null && typeof modifier.effect !== 'function') {
  6582. console.error(format$1(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', "\"" + String(modifier.fn) + "\""));
  6583. }
  6584. break;
  6585. case 'requires':
  6586. if (modifier.requires != null && !Array.isArray(modifier.requires)) {
  6587. console.error(format$1(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', "\"" + String(modifier.requires) + "\""));
  6588. }
  6589. break;
  6590. case 'requiresIfExists':
  6591. if (!Array.isArray(modifier.requiresIfExists)) {
  6592. console.error(format$1(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', "\"" + String(modifier.requiresIfExists) + "\""));
  6593. }
  6594. break;
  6595. case 'options':
  6596. case 'data':
  6597. break;
  6598. default:
  6599. console.error("PopperJS: an invalid property has been provided to the \"" + modifier.name + "\" modifier, valid properties are " + VALID_PROPERTIES.map(function (s) {
  6600. return "\"" + s + "\"";
  6601. }).join(', ') + "; but \"" + key + "\" was provided.");
  6602. }
  6603. modifier.requires && modifier.requires.forEach(function (requirement) {
  6604. if (modifiers.find(function (mod) {
  6605. return mod.name === requirement;
  6606. }) == null) {
  6607. console.error(format$1(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
  6608. }
  6609. });
  6610. });
  6611. });
  6612. }
  6613. function uniqueBy(arr, fn) {
  6614. var identifiers = new Set();
  6615. return arr.filter(function (item) {
  6616. var identifier = fn(item);
  6617. if (!identifiers.has(identifier)) {
  6618. identifiers.add(identifier);
  6619. return true;
  6620. }
  6621. });
  6622. }
  6623. function mergeByName(modifiers) {
  6624. var merged = modifiers.reduce(function (merged, current) {
  6625. var existing = merged[current.name];
  6626. merged[current.name] = existing ? Object.assign({}, existing, current, {
  6627. options: Object.assign({}, existing.options, current.options),
  6628. data: Object.assign({}, existing.data, current.data)
  6629. }) : current;
  6630. return merged;
  6631. }, {}); // IE11 does not support Object.values
  6632. return Object.keys(merged).map(function (key) {
  6633. return merged[key];
  6634. });
  6635. }
  6636. var INVALID_ELEMENT_ERROR = 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';
  6637. var INFINITE_LOOP_ERROR = 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';
  6638. var DEFAULT_OPTIONS = {
  6639. placement: 'bottom',
  6640. modifiers: [],
  6641. strategy: 'absolute'
  6642. };
  6643. function areValidElements() {
  6644. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  6645. args[_key] = arguments[_key];
  6646. }
  6647. return !args.some(function (element) {
  6648. return !(element && typeof element.getBoundingClientRect === 'function');
  6649. });
  6650. }
  6651. function popperGenerator(generatorOptions) {
  6652. if (generatorOptions === void 0) {
  6653. generatorOptions = {};
  6654. }
  6655. var _generatorOptions = generatorOptions,
  6656. _generatorOptions$def = _generatorOptions.defaultModifiers,
  6657. defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
  6658. _generatorOptions$def2 = _generatorOptions.defaultOptions,
  6659. defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  6660. return function createPopper(reference, popper, options) {
  6661. if (options === void 0) {
  6662. options = defaultOptions;
  6663. }
  6664. var state = {
  6665. placement: 'bottom',
  6666. orderedModifiers: [],
  6667. options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
  6668. modifiersData: {},
  6669. elements: {
  6670. reference: reference,
  6671. popper: popper
  6672. },
  6673. attributes: {},
  6674. styles: {}
  6675. };
  6676. var effectCleanupFns = [];
  6677. var isDestroyed = false;
  6678. var instance = {
  6679. state: state,
  6680. setOptions: function setOptions(setOptionsAction) {
  6681. var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
  6682. cleanupModifierEffects();
  6683. state.options = Object.assign({}, defaultOptions, state.options, options);
  6684. state.scrollParents = {
  6685. reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
  6686. popper: listScrollParents(popper)
  6687. }; // Orders the modifiers based on their dependencies and `phase`
  6688. // properties
  6689. var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
  6690. state.orderedModifiers = orderedModifiers.filter(function (m) {
  6691. return m.enabled;
  6692. }); // Validate the provided modifiers so that the consumer will get warned
  6693. // if one of the modifiers is invalid for any reason
  6694. if (process.env.NODE_ENV !== "production") {
  6695. var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) {
  6696. var name = _ref.name;
  6697. return name;
  6698. });
  6699. validateModifiers(modifiers);
  6700. if (getBasePlacement(state.options.placement) === auto) {
  6701. var flipModifier = state.orderedModifiers.find(function (_ref2) {
  6702. var name = _ref2.name;
  6703. return name === 'flip';
  6704. });
  6705. if (!flipModifier) {
  6706. console.error(['Popper: "auto" placements require the "flip" modifier be', 'present and enabled to work.'].join(' '));
  6707. }
  6708. }
  6709. var _getComputedStyle = getComputedStyle$1(popper),
  6710. marginTop = _getComputedStyle.marginTop,
  6711. marginRight = _getComputedStyle.marginRight,
  6712. marginBottom = _getComputedStyle.marginBottom,
  6713. marginLeft = _getComputedStyle.marginLeft; // We no longer take into account `margins` on the popper, and it can
  6714. // cause bugs with positioning, so we'll warn the consumer
  6715. if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) {
  6716. return parseFloat(margin);
  6717. })) {
  6718. console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', 'between the popper and its reference element or boundary.', 'To replicate margin, use the `offset` modifier, as well as', 'the `padding` option in the `preventOverflow` and `flip`', 'modifiers.'].join(' '));
  6719. }
  6720. }
  6721. runModifierEffects();
  6722. return instance.update();
  6723. },
  6724. // Sync update – it will always be executed, even if not necessary. This
  6725. // is useful for low frequency updates where sync behavior simplifies the
  6726. // logic.
  6727. // For high frequency updates (e.g. `resize` and `scroll` events), always
  6728. // prefer the async Popper#update method
  6729. forceUpdate: function forceUpdate() {
  6730. if (isDestroyed) {
  6731. return;
  6732. }
  6733. var _state$elements = state.elements,
  6734. reference = _state$elements.reference,
  6735. popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
  6736. // anymore
  6737. if (!areValidElements(reference, popper)) {
  6738. if (process.env.NODE_ENV !== "production") {
  6739. console.error(INVALID_ELEMENT_ERROR);
  6740. }
  6741. return;
  6742. } // Store the reference and popper rects to be read by modifiers
  6743. state.rects = {
  6744. reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
  6745. popper: getLayoutRect(popper)
  6746. }; // Modifiers have the ability to reset the current update cycle. The
  6747. // most common use case for this is the `flip` modifier changing the
  6748. // placement, which then needs to re-run all the modifiers, because the
  6749. // logic was previously ran for the previous placement and is therefore
  6750. // stale/incorrect
  6751. state.reset = false;
  6752. state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
  6753. // is filled with the initial data specified by the modifier. This means
  6754. // it doesn't persist and is fresh on each update.
  6755. // To ensure persistent data, use `${name}#persistent`
  6756. state.orderedModifiers.forEach(function (modifier) {
  6757. return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
  6758. });
  6759. var __debug_loops__ = 0;
  6760. for (var index = 0; index < state.orderedModifiers.length; index++) {
  6761. if (process.env.NODE_ENV !== "production") {
  6762. __debug_loops__ += 1;
  6763. if (__debug_loops__ > 100) {
  6764. console.error(INFINITE_LOOP_ERROR);
  6765. break;
  6766. }
  6767. }
  6768. if (state.reset === true) {
  6769. state.reset = false;
  6770. index = -1;
  6771. continue;
  6772. }
  6773. var _state$orderedModifie = state.orderedModifiers[index],
  6774. fn = _state$orderedModifie.fn,
  6775. _state$orderedModifie2 = _state$orderedModifie.options,
  6776. _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
  6777. name = _state$orderedModifie.name;
  6778. if (typeof fn === 'function') {
  6779. state = fn({
  6780. state: state,
  6781. options: _options,
  6782. name: name,
  6783. instance: instance
  6784. }) || state;
  6785. }
  6786. }
  6787. },
  6788. // Async and optimistically optimized update – it will not be executed if
  6789. // not necessary (debounced to run at most once-per-tick)
  6790. update: debounce(function () {
  6791. return new Promise(function (resolve) {
  6792. instance.forceUpdate();
  6793. resolve(state);
  6794. });
  6795. }),
  6796. destroy: function destroy() {
  6797. cleanupModifierEffects();
  6798. isDestroyed = true;
  6799. }
  6800. };
  6801. if (!areValidElements(reference, popper)) {
  6802. if (process.env.NODE_ENV !== "production") {
  6803. console.error(INVALID_ELEMENT_ERROR);
  6804. }
  6805. return instance;
  6806. }
  6807. instance.setOptions(options).then(function (state) {
  6808. if (!isDestroyed && options.onFirstUpdate) {
  6809. options.onFirstUpdate(state);
  6810. }
  6811. }); // Modifiers have the ability to execute arbitrary code before the first
  6812. // update cycle runs. They will be executed in the same order as the update
  6813. // cycle. This is useful when a modifier adds some persistent data that
  6814. // other modifiers need to use, but the modifier is run after the dependent
  6815. // one.
  6816. function runModifierEffects() {
  6817. state.orderedModifiers.forEach(function (_ref3) {
  6818. var name = _ref3.name,
  6819. _ref3$options = _ref3.options,
  6820. options = _ref3$options === void 0 ? {} : _ref3$options,
  6821. effect = _ref3.effect;
  6822. if (typeof effect === 'function') {
  6823. var cleanupFn = effect({
  6824. state: state,
  6825. name: name,
  6826. instance: instance,
  6827. options: options
  6828. });
  6829. var noopFn = function noopFn() {};
  6830. effectCleanupFns.push(cleanupFn || noopFn);
  6831. }
  6832. });
  6833. }
  6834. function cleanupModifierEffects() {
  6835. effectCleanupFns.forEach(function (fn) {
  6836. return fn();
  6837. });
  6838. effectCleanupFns = [];
  6839. }
  6840. return instance;
  6841. };
  6842. }
  6843. var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
  6844. var createPopper = /*#__PURE__*/popperGenerator({
  6845. defaultModifiers: defaultModifiers
  6846. }); // eslint-disable-next-line import/no-unused-modules
  6847. // Credits go to Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes
  6848. const wrapAround = (value, size) => {
  6849. return ((value % size) + size) % size;
  6850. };
  6851. class Suggest {
  6852. constructor(owner, containerEl, scope) {
  6853. this.owner = owner;
  6854. this.containerEl = containerEl;
  6855. containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this));
  6856. containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this));
  6857. scope.register([], "ArrowUp", (event) => {
  6858. if (!event.isComposing) {
  6859. this.setSelectedItem(this.selectedItem - 1, true);
  6860. return false;
  6861. }
  6862. });
  6863. scope.register([], "ArrowDown", (event) => {
  6864. if (!event.isComposing) {
  6865. this.setSelectedItem(this.selectedItem + 1, true);
  6866. return false;
  6867. }
  6868. });
  6869. scope.register([], "Enter", (event) => {
  6870. if (!event.isComposing) {
  6871. this.useSelectedItem(event);
  6872. return false;
  6873. }
  6874. });
  6875. }
  6876. onSuggestionClick(event, el) {
  6877. event.preventDefault();
  6878. const item = this.suggestions.indexOf(el);
  6879. this.setSelectedItem(item, false);
  6880. this.useSelectedItem(event);
  6881. }
  6882. onSuggestionMouseover(_event, el) {
  6883. const item = this.suggestions.indexOf(el);
  6884. this.setSelectedItem(item, false);
  6885. }
  6886. setSuggestions(values) {
  6887. this.containerEl.empty();
  6888. const suggestionEls = [];
  6889. values.forEach((value) => {
  6890. const suggestionEl = this.containerEl.createDiv("suggestion-item");
  6891. this.owner.renderSuggestion(value, suggestionEl);
  6892. suggestionEls.push(suggestionEl);
  6893. });
  6894. this.values = values;
  6895. this.suggestions = suggestionEls;
  6896. this.setSelectedItem(0, false);
  6897. }
  6898. useSelectedItem(event) {
  6899. const currentValue = this.values[this.selectedItem];
  6900. if (currentValue) {
  6901. this.owner.selectSuggestion(currentValue, event);
  6902. }
  6903. }
  6904. setSelectedItem(selectedIndex, scrollIntoView) {
  6905. const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length);
  6906. const prevSelectedSuggestion = this.suggestions[this.selectedItem];
  6907. const selectedSuggestion = this.suggestions[normalizedIndex];
  6908. prevSelectedSuggestion === null || prevSelectedSuggestion === void 0 ? void 0 : prevSelectedSuggestion.removeClass("is-selected");
  6909. selectedSuggestion === null || selectedSuggestion === void 0 ? void 0 : selectedSuggestion.addClass("is-selected");
  6910. this.selectedItem = normalizedIndex;
  6911. if (scrollIntoView) {
  6912. selectedSuggestion.scrollIntoView(false);
  6913. }
  6914. }
  6915. }
  6916. class TextInputSuggest {
  6917. constructor(app, inputEl) {
  6918. this.app = app;
  6919. this.inputEl = inputEl;
  6920. this.scope = new obsidian.Scope();
  6921. this.suggestEl = createDiv("suggestion-container");
  6922. const suggestion = this.suggestEl.createDiv("suggestion");
  6923. this.suggest = new Suggest(this, suggestion, this.scope);
  6924. this.scope.register([], "Escape", this.close.bind(this));
  6925. this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
  6926. this.inputEl.addEventListener("focus", this.onInputChanged.bind(this));
  6927. this.inputEl.addEventListener("blur", this.close.bind(this));
  6928. this.suggestEl.on("mousedown", ".suggestion-container", (event) => {
  6929. event.preventDefault();
  6930. });
  6931. }
  6932. onInputChanged() {
  6933. const inputStr = this.inputEl.value;
  6934. const suggestions = this.getSuggestions(inputStr);
  6935. if (!suggestions) {
  6936. this.close();
  6937. return;
  6938. }
  6939. if (suggestions.length > 0) {
  6940. this.suggest.setSuggestions(suggestions);
  6941. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6942. this.open(this.app.dom.appContainerEl, this.inputEl);
  6943. }
  6944. else {
  6945. this.close();
  6946. }
  6947. }
  6948. open(container, inputEl) {
  6949. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6950. this.app.keymap.pushScope(this.scope);
  6951. container.appendChild(this.suggestEl);
  6952. this.popper = createPopper(inputEl, this.suggestEl, {
  6953. placement: "bottom-start",
  6954. modifiers: [
  6955. {
  6956. name: "sameWidth",
  6957. enabled: true,
  6958. fn: ({ state, instance }) => {
  6959. // Note: positioning needs to be calculated twice -
  6960. // first pass - positioning it according to the width of the popper
  6961. // second pass - position it with the width bound to the reference element
  6962. // we need to early exit to avoid an infinite loop
  6963. const targetWidth = `${state.rects.reference.width}px`;
  6964. if (state.styles.popper.width === targetWidth) {
  6965. return;
  6966. }
  6967. state.styles.popper.width = targetWidth;
  6968. instance.update();
  6969. },
  6970. phase: "beforeWrite",
  6971. requires: ["computeStyles"],
  6972. },
  6973. ],
  6974. });
  6975. }
  6976. close() {
  6977. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6978. this.app.keymap.popScope(this.scope);
  6979. this.suggest.setSuggestions([]);
  6980. if (this.popper)
  6981. this.popper.destroy();
  6982. this.suggestEl.detach();
  6983. }
  6984. }
  6985. const VALUE_SYNTAX = "{{VALUE}}";
  6986. const DATE_SYNTAX = "{{DATE}}";
  6987. const NAME_SYNTAX = "{{NAME}}";
  6988. const VARIABLE_SYNTAX = "{{VALUE:<VARIABLE NAME>}}";
  6989. const MATH_VALUE_SYNTAX = "{{MVALUE}}";
  6990. const LINKCURRENT_SYNTAX = "{{LINKCURRENT}}";
  6991. const FILE_NAME_FORMAT_SYNTAX = [
  6992. DATE_SYNTAX, "{{DATE:<DATEFORMAT>}}", "{{VDATE:<VARIABLE NAME>, <DATE FORMAT>}}",
  6993. VALUE_SYNTAX, NAME_SYNTAX, VARIABLE_SYNTAX,
  6994. ];
  6995. const FILE_NUMBER_REGEX = new RegExp(/([0-9]*)\.md$/);
  6996. const NUMBER_REGEX = new RegExp(/^-?[0-9]*$/);
  6997. const CREATE_IF_NOT_FOUND_TOP = "top";
  6998. const CREATE_IF_NOT_FOUND_BOTTOM = "bottom";
  6999. // == Format Syntax == //
  7000. const DATE_REGEX = new RegExp(/{{DATE(\+-?[0-9]+)?}}/);
  7001. const DATE_REGEX_FORMATTED = new RegExp(/{{DATE:([^}\n\r+]*)(\+-?[0-9]+)?}}/);
  7002. const NAME_VALUE_REGEX = new RegExp(/{{NAME}}|{{VALUE}}/);
  7003. const VARIABLE_REGEX = new RegExp(/{{VALUE:([^\n\r}]*)}}/);
  7004. const DATE_VARIABLE_REGEX = new RegExp(/{{VDATE:([^\n\r},]*),\s*([^\n\r},]*)}}/);
  7005. const LINK_TO_CURRENT_FILE_REGEX = new RegExp(/{{LINKCURRENT}}/);
  7006. const MARKDOWN_FILE_EXTENSION_REGEX = new RegExp(/\.md$/);
  7007. const JAVASCRIPT_FILE_EXTENSION_REGEX = new RegExp(/\.js$/);
  7008. const MACRO_REGEX = new RegExp(/{{MACRO:([^\n\r}]*)}}/);
  7009. const TEMPLATE_REGEX = new RegExp(/{{TEMPLATE:([^\n\r}]*.md)}}/);
  7010. const LINEBREAK_REGEX = new RegExp(/\\n/);
  7011. const INLINE_JAVASCRIPT_REGEX = new RegExp(/`{3,}js quickadd([\s\S]*?)`{3,}/);
  7012. const MATH_VALUE_REGEX = new RegExp(/{{MVALUE}}/);
  7013. // This is not an accurate wikilink regex - but works for its intended purpose.
  7014. const FILE_LINK_REGEX = new RegExp(/\[\[([^\]]*)$/);
  7015. const TAG_REGEX = new RegExp(/#([^ ]*)$/);
  7016. // == Format Syntax Suggestion == //
  7017. const DATE_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[D]?[A]?[T]?[E]?[}]?[}]?$/i);
  7018. const DATE_FORMAT_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[D]?[A]?[T]?[E]?[:]?$|{{DATE:[^\n\r}]*}}$/i);
  7019. const NAME_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[N]?[A]?[M]?[E]?[}]?[}]?$/i);
  7020. const VALUE_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[}]?[}]?$/i);
  7021. const VARIABLE_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[V]?[A]?[L]?[U]?[E]?[:]?$|{{VALUE:[^\n\r}]*}}$/i);
  7022. const VARIABLE_DATE_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[V]?[D]?[A]?[T]?[E]?[:]?$|{{VDATE:[^\n\r}]*}}$/i);
  7023. const LINKCURRENT_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[L]?[I]?[N]?[K]?[C]?[U]?[R]?[R]?[E]?[N]?[T]?[}]?[}]?$/i);
  7024. const TEMPLATE_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[T]?[E]?[M]?[P]?[L]?[A]?[T]?[E]?[:]?$|{{TEMPLATE:[^\n\r}]*[}]?[}]?$/i);
  7025. const MACRO_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[M]?[A]?[C]?[R]?[O]?[:]?$|{{MACRO:[^\n\r}]*}}$/i);
  7026. const MATH_VALUE_SYNTAX_SUGGEST_REGEX = new RegExp(/{{[M]?[V]?[A]?[L]?[U]?[E]?[}]?[}]?/i);
  7027. // == File Exists (Template Choice) == //
  7028. const fileExistsAppendToBottom = "Append to the bottom of the file";
  7029. const fileExistsAppendToTop = "Append to the top of the file";
  7030. const fileExistsOverwriteFile = "Overwrite the file";
  7031. const fileExistsDoNothing = "Nothing";
  7032. const fileExistsChoices = [fileExistsAppendToBottom, fileExistsAppendToTop, fileExistsOverwriteFile, fileExistsDoNothing];
  7033. // == MISC == //
  7034. const WIKI_LINK_REGEX = new RegExp(/\[\[([^\]]*)\]\]/);
  7035. /**
  7036. * Fuse.js v6.4.6 - Lightweight fuzzy-search (http://fusejs.io)
  7037. *
  7038. * Copyright (c) 2021 Kiro Risk (http://kiro.me)
  7039. * All Rights Reserved. Apache Software License 2.0
  7040. *
  7041. * http://www.apache.org/licenses/LICENSE-2.0
  7042. */
  7043. function isArray(value) {
  7044. return !Array.isArray
  7045. ? getTag(value) === '[object Array]'
  7046. : Array.isArray(value)
  7047. }
  7048. // Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js
  7049. const INFINITY = 1 / 0;
  7050. function baseToString(value) {
  7051. // Exit early for strings to avoid a performance hit in some environments.
  7052. if (typeof value == 'string') {
  7053. return value
  7054. }
  7055. let result = value + '';
  7056. return result == '0' && 1 / value == -INFINITY ? '-0' : result
  7057. }
  7058. function toString(value) {
  7059. return value == null ? '' : baseToString(value)
  7060. }
  7061. function isString(value) {
  7062. return typeof value === 'string'
  7063. }
  7064. function isNumber(value) {
  7065. return typeof value === 'number'
  7066. }
  7067. // Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js
  7068. function isBoolean(value) {
  7069. return (
  7070. value === true ||
  7071. value === false ||
  7072. (isObjectLike(value) && getTag(value) == '[object Boolean]')
  7073. )
  7074. }
  7075. function isObject(value) {
  7076. return typeof value === 'object'
  7077. }
  7078. // Checks if `value` is object-like.
  7079. function isObjectLike(value) {
  7080. return isObject(value) && value !== null
  7081. }
  7082. function isDefined(value) {
  7083. return value !== undefined && value !== null
  7084. }
  7085. function isBlank(value) {
  7086. return !value.trim().length
  7087. }
  7088. // Gets the `toStringTag` of `value`.
  7089. // Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js
  7090. function getTag(value) {
  7091. return value == null
  7092. ? value === undefined
  7093. ? '[object Undefined]'
  7094. : '[object Null]'
  7095. : Object.prototype.toString.call(value)
  7096. }
  7097. const EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available';
  7098. const INCORRECT_INDEX_TYPE = "Incorrect 'index' type";
  7099. const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) =>
  7100. `Invalid value for key ${key}`;
  7101. const PATTERN_LENGTH_TOO_LARGE = (max) =>
  7102. `Pattern length exceeds max of ${max}.`;
  7103. const MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`;
  7104. const INVALID_KEY_WEIGHT_VALUE = (key) =>
  7105. `Property 'weight' in key '${key}' must be a positive integer`;
  7106. const hasOwn = Object.prototype.hasOwnProperty;
  7107. class KeyStore {
  7108. constructor(keys) {
  7109. this._keys = [];
  7110. this._keyMap = {};
  7111. let totalWeight = 0;
  7112. keys.forEach((key) => {
  7113. let obj = createKey(key);
  7114. totalWeight += obj.weight;
  7115. this._keys.push(obj);
  7116. this._keyMap[obj.id] = obj;
  7117. totalWeight += obj.weight;
  7118. });
  7119. // Normalize weights so that their sum is equal to 1
  7120. this._keys.forEach((key) => {
  7121. key.weight /= totalWeight;
  7122. });
  7123. }
  7124. get(keyId) {
  7125. return this._keyMap[keyId]
  7126. }
  7127. keys() {
  7128. return this._keys
  7129. }
  7130. toJSON() {
  7131. return JSON.stringify(this._keys)
  7132. }
  7133. }
  7134. function createKey(key) {
  7135. let path = null;
  7136. let id = null;
  7137. let src = null;
  7138. let weight = 1;
  7139. if (isString(key) || isArray(key)) {
  7140. src = key;
  7141. path = createKeyPath(key);
  7142. id = createKeyId(key);
  7143. } else {
  7144. if (!hasOwn.call(key, 'name')) {
  7145. throw new Error(MISSING_KEY_PROPERTY('name'))
  7146. }
  7147. const name = key.name;
  7148. src = name;
  7149. if (hasOwn.call(key, 'weight')) {
  7150. weight = key.weight;
  7151. if (weight <= 0) {
  7152. throw new Error(INVALID_KEY_WEIGHT_VALUE(name))
  7153. }
  7154. }
  7155. path = createKeyPath(name);
  7156. id = createKeyId(name);
  7157. }
  7158. return { path, id, weight, src }
  7159. }
  7160. function createKeyPath(key) {
  7161. return isArray(key) ? key : key.split('.')
  7162. }
  7163. function createKeyId(key) {
  7164. return isArray(key) ? key.join('.') : key
  7165. }
  7166. function get(obj, path) {
  7167. let list = [];
  7168. let arr = false;
  7169. const deepGet = (obj, path, index) => {
  7170. if (!isDefined(obj)) {
  7171. return
  7172. }
  7173. if (!path[index]) {
  7174. // If there's no path left, we've arrived at the object we care about.
  7175. list.push(obj);
  7176. } else {
  7177. let key = path[index];
  7178. const value = obj[key];
  7179. if (!isDefined(value)) {
  7180. return
  7181. }
  7182. // If we're at the last value in the path, and if it's a string/number/bool,
  7183. // add it to the list
  7184. if (
  7185. index === path.length - 1 &&
  7186. (isString(value) || isNumber(value) || isBoolean(value))
  7187. ) {
  7188. list.push(toString(value));
  7189. } else if (isArray(value)) {
  7190. arr = true;
  7191. // Search each item in the array.
  7192. for (let i = 0, len = value.length; i < len; i += 1) {
  7193. deepGet(value[i], path, index + 1);
  7194. }
  7195. } else if (path.length) {
  7196. // An object. Recurse further.
  7197. deepGet(value, path, index + 1);
  7198. }
  7199. }
  7200. };
  7201. // Backwards compatibility (since path used to be a string)
  7202. deepGet(obj, isString(path) ? path.split('.') : path, 0);
  7203. return arr ? list : list[0]
  7204. }
  7205. const MatchOptions = {
  7206. // Whether the matches should be included in the result set. When `true`, each record in the result
  7207. // set will include the indices of the matched characters.
  7208. // These can consequently be used for highlighting purposes.
  7209. includeMatches: false,
  7210. // When `true`, the matching function will continue to the end of a search pattern even if
  7211. // a perfect match has already been located in the string.
  7212. findAllMatches: false,
  7213. // Minimum number of characters that must be matched before a result is considered a match
  7214. minMatchCharLength: 1
  7215. };
  7216. const BasicOptions = {
  7217. // When `true`, the algorithm continues searching to the end of the input even if a perfect
  7218. // match is found before the end of the same input.
  7219. isCaseSensitive: false,
  7220. // When true, the matching function will continue to the end of a search pattern even if
  7221. includeScore: false,
  7222. // List of properties that will be searched. This also supports nested properties.
  7223. keys: [],
  7224. // Whether to sort the result list, by score
  7225. shouldSort: true,
  7226. // Default sort function: sort by ascending score, ascending index
  7227. sortFn: (a, b) =>
  7228. a.score === b.score ? (a.idx < b.idx ? -1 : 1) : a.score < b.score ? -1 : 1
  7229. };
  7230. const FuzzyOptions = {
  7231. // Approximately where in the text is the pattern expected to be found?
  7232. location: 0,
  7233. // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
  7234. // (of both letters and location), a threshold of '1.0' would match anything.
  7235. threshold: 0.6,
  7236. // Determines how close the match must be to the fuzzy location (specified above).
  7237. // An exact letter match which is 'distance' characters away from the fuzzy location
  7238. // would score as a complete mismatch. A distance of '0' requires the match be at
  7239. // the exact location specified, a threshold of '1000' would require a perfect match
  7240. // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
  7241. distance: 100
  7242. };
  7243. const AdvancedOptions = {
  7244. // When `true`, it enables the use of unix-like search commands
  7245. useExtendedSearch: false,
  7246. // The get function to use when fetching an object's properties.
  7247. // The default will search nested paths *ie foo.bar.baz*
  7248. getFn: get,
  7249. // When `true`, search will ignore `location` and `distance`, so it won't matter
  7250. // where in the string the pattern appears.
  7251. // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
  7252. ignoreLocation: false,
  7253. // When `true`, the calculation for the relevance score (used for sorting) will
  7254. // ignore the field-length norm.
  7255. // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
  7256. ignoreFieldNorm: false
  7257. };
  7258. var Config = {
  7259. ...BasicOptions,
  7260. ...MatchOptions,
  7261. ...FuzzyOptions,
  7262. ...AdvancedOptions
  7263. };
  7264. const SPACE = /[^ ]+/g;
  7265. // Field-length norm: the shorter the field, the higher the weight.
  7266. // Set to 3 decimals to reduce index size.
  7267. function norm(mantissa = 3) {
  7268. const cache = new Map();
  7269. const m = Math.pow(10, mantissa);
  7270. return {
  7271. get(value) {
  7272. const numTokens = value.match(SPACE).length;
  7273. if (cache.has(numTokens)) {
  7274. return cache.get(numTokens)
  7275. }
  7276. const norm = 1 / Math.sqrt(numTokens);
  7277. // In place of `toFixed(mantissa)`, for faster computation
  7278. const n = parseFloat(Math.round(norm * m) / m);
  7279. cache.set(numTokens, n);
  7280. return n
  7281. },
  7282. clear() {
  7283. cache.clear();
  7284. }
  7285. }
  7286. }
  7287. class FuseIndex {
  7288. constructor({ getFn = Config.getFn } = {}) {
  7289. this.norm = norm(3);
  7290. this.getFn = getFn;
  7291. this.isCreated = false;
  7292. this.setIndexRecords();
  7293. }
  7294. setSources(docs = []) {
  7295. this.docs = docs;
  7296. }
  7297. setIndexRecords(records = []) {
  7298. this.records = records;
  7299. }
  7300. setKeys(keys = []) {
  7301. this.keys = keys;
  7302. this._keysMap = {};
  7303. keys.forEach((key, idx) => {
  7304. this._keysMap[key.id] = idx;
  7305. });
  7306. }
  7307. create() {
  7308. if (this.isCreated || !this.docs.length) {
  7309. return
  7310. }
  7311. this.isCreated = true;
  7312. // List is Array<String>
  7313. if (isString(this.docs[0])) {
  7314. this.docs.forEach((doc, docIndex) => {
  7315. this._addString(doc, docIndex);
  7316. });
  7317. } else {
  7318. // List is Array<Object>
  7319. this.docs.forEach((doc, docIndex) => {
  7320. this._addObject(doc, docIndex);
  7321. });
  7322. }
  7323. this.norm.clear();
  7324. }
  7325. // Adds a doc to the end of the index
  7326. add(doc) {
  7327. const idx = this.size();
  7328. if (isString(doc)) {
  7329. this._addString(doc, idx);
  7330. } else {
  7331. this._addObject(doc, idx);
  7332. }
  7333. }
  7334. // Removes the doc at the specified index of the index
  7335. removeAt(idx) {
  7336. this.records.splice(idx, 1);
  7337. // Change ref index of every subsquent doc
  7338. for (let i = idx, len = this.size(); i < len; i += 1) {
  7339. this.records[i].i -= 1;
  7340. }
  7341. }
  7342. getValueForItemAtKeyId(item, keyId) {
  7343. return item[this._keysMap[keyId]]
  7344. }
  7345. size() {
  7346. return this.records.length
  7347. }
  7348. _addString(doc, docIndex) {
  7349. if (!isDefined(doc) || isBlank(doc)) {
  7350. return
  7351. }
  7352. let record = {
  7353. v: doc,
  7354. i: docIndex,
  7355. n: this.norm.get(doc)
  7356. };
  7357. this.records.push(record);
  7358. }
  7359. _addObject(doc, docIndex) {
  7360. let record = { i: docIndex, $: {} };
  7361. // Iterate over every key (i.e, path), and fetch the value at that key
  7362. this.keys.forEach((key, keyIndex) => {
  7363. // console.log(key)
  7364. let value = this.getFn(doc, key.path);
  7365. if (!isDefined(value)) {
  7366. return
  7367. }
  7368. if (isArray(value)) {
  7369. let subRecords = [];
  7370. const stack = [{ nestedArrIndex: -1, value }];
  7371. while (stack.length) {
  7372. const { nestedArrIndex, value } = stack.pop();
  7373. if (!isDefined(value)) {
  7374. continue
  7375. }
  7376. if (isString(value) && !isBlank(value)) {
  7377. let subRecord = {
  7378. v: value,
  7379. i: nestedArrIndex,
  7380. n: this.norm.get(value)
  7381. };
  7382. subRecords.push(subRecord);
  7383. } else if (isArray(value)) {
  7384. value.forEach((item, k) => {
  7385. stack.push({
  7386. nestedArrIndex: k,
  7387. value: item
  7388. });
  7389. });
  7390. }
  7391. }
  7392. record.$[keyIndex] = subRecords;
  7393. } else if (!isBlank(value)) {
  7394. let subRecord = {
  7395. v: value,
  7396. n: this.norm.get(value)
  7397. };
  7398. record.$[keyIndex] = subRecord;
  7399. }
  7400. });
  7401. this.records.push(record);
  7402. }
  7403. toJSON() {
  7404. return {
  7405. keys: this.keys,
  7406. records: this.records
  7407. }
  7408. }
  7409. }
  7410. function createIndex(keys, docs, { getFn = Config.getFn } = {}) {
  7411. const myIndex = new FuseIndex({ getFn });
  7412. myIndex.setKeys(keys.map(createKey));
  7413. myIndex.setSources(docs);
  7414. myIndex.create();
  7415. return myIndex
  7416. }
  7417. function parseIndex(data, { getFn = Config.getFn } = {}) {
  7418. const { keys, records } = data;
  7419. const myIndex = new FuseIndex({ getFn });
  7420. myIndex.setKeys(keys);
  7421. myIndex.setIndexRecords(records);
  7422. return myIndex
  7423. }
  7424. function computeScore(
  7425. pattern,
  7426. {
  7427. errors = 0,
  7428. currentLocation = 0,
  7429. expectedLocation = 0,
  7430. distance = Config.distance,
  7431. ignoreLocation = Config.ignoreLocation
  7432. } = {}
  7433. ) {
  7434. const accuracy = errors / pattern.length;
  7435. if (ignoreLocation) {
  7436. return accuracy
  7437. }
  7438. const proximity = Math.abs(expectedLocation - currentLocation);
  7439. if (!distance) {
  7440. // Dodge divide by zero error.
  7441. return proximity ? 1.0 : accuracy
  7442. }
  7443. return accuracy + proximity / distance
  7444. }
  7445. function convertMaskToIndices(
  7446. matchmask = [],
  7447. minMatchCharLength = Config.minMatchCharLength
  7448. ) {
  7449. let indices = [];
  7450. let start = -1;
  7451. let end = -1;
  7452. let i = 0;
  7453. for (let len = matchmask.length; i < len; i += 1) {
  7454. let match = matchmask[i];
  7455. if (match && start === -1) {
  7456. start = i;
  7457. } else if (!match && start !== -1) {
  7458. end = i - 1;
  7459. if (end - start + 1 >= minMatchCharLength) {
  7460. indices.push([start, end]);
  7461. }
  7462. start = -1;
  7463. }
  7464. }
  7465. // (i-1 - start) + 1 => i - start
  7466. if (matchmask[i - 1] && i - start >= minMatchCharLength) {
  7467. indices.push([start, i - 1]);
  7468. }
  7469. return indices
  7470. }
  7471. // Machine word size
  7472. const MAX_BITS = 32;
  7473. function search(
  7474. text,
  7475. pattern,
  7476. patternAlphabet,
  7477. {
  7478. location = Config.location,
  7479. distance = Config.distance,
  7480. threshold = Config.threshold,
  7481. findAllMatches = Config.findAllMatches,
  7482. minMatchCharLength = Config.minMatchCharLength,
  7483. includeMatches = Config.includeMatches,
  7484. ignoreLocation = Config.ignoreLocation
  7485. } = {}
  7486. ) {
  7487. if (pattern.length > MAX_BITS) {
  7488. throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS))
  7489. }
  7490. const patternLen = pattern.length;
  7491. // Set starting location at beginning text and initialize the alphabet.
  7492. const textLen = text.length;
  7493. // Handle the case when location > text.length
  7494. const expectedLocation = Math.max(0, Math.min(location, textLen));
  7495. // Highest score beyond which we give up.
  7496. let currentThreshold = threshold;
  7497. // Is there a nearby exact match? (speedup)
  7498. let bestLocation = expectedLocation;
  7499. // Performance: only computer matches when the minMatchCharLength > 1
  7500. // OR if `includeMatches` is true.
  7501. const computeMatches = minMatchCharLength > 1 || includeMatches;
  7502. // A mask of the matches, used for building the indices
  7503. const matchMask = computeMatches ? Array(textLen) : [];
  7504. let index;
  7505. // Get all exact matches, here for speed up
  7506. while ((index = text.indexOf(pattern, bestLocation)) > -1) {
  7507. let score = computeScore(pattern, {
  7508. currentLocation: index,
  7509. expectedLocation,
  7510. distance,
  7511. ignoreLocation
  7512. });
  7513. currentThreshold = Math.min(score, currentThreshold);
  7514. bestLocation = index + patternLen;
  7515. if (computeMatches) {
  7516. let i = 0;
  7517. while (i < patternLen) {
  7518. matchMask[index + i] = 1;
  7519. i += 1;
  7520. }
  7521. }
  7522. }
  7523. // Reset the best location
  7524. bestLocation = -1;
  7525. let lastBitArr = [];
  7526. let finalScore = 1;
  7527. let binMax = patternLen + textLen;
  7528. const mask = 1 << (patternLen - 1);
  7529. for (let i = 0; i < patternLen; i += 1) {
  7530. // Scan for the best match; each iteration allows for one more error.
  7531. // Run a binary search to determine how far from the match location we can stray
  7532. // at this error level.
  7533. let binMin = 0;
  7534. let binMid = binMax;
  7535. while (binMin < binMid) {
  7536. const score = computeScore(pattern, {
  7537. errors: i,
  7538. currentLocation: expectedLocation + binMid,
  7539. expectedLocation,
  7540. distance,
  7541. ignoreLocation
  7542. });
  7543. if (score <= currentThreshold) {
  7544. binMin = binMid;
  7545. } else {
  7546. binMax = binMid;
  7547. }
  7548. binMid = Math.floor((binMax - binMin) / 2 + binMin);
  7549. }
  7550. // Use the result from this iteration as the maximum for the next.
  7551. binMax = binMid;
  7552. let start = Math.max(1, expectedLocation - binMid + 1);
  7553. let finish = findAllMatches
  7554. ? textLen
  7555. : Math.min(expectedLocation + binMid, textLen) + patternLen;
  7556. // Initialize the bit array
  7557. let bitArr = Array(finish + 2);
  7558. bitArr[finish + 1] = (1 << i) - 1;
  7559. for (let j = finish; j >= start; j -= 1) {
  7560. let currentLocation = j - 1;
  7561. let charMatch = patternAlphabet[text.charAt(currentLocation)];
  7562. if (computeMatches) {
  7563. // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)
  7564. matchMask[currentLocation] = +!!charMatch;
  7565. }
  7566. // First pass: exact match
  7567. bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch;
  7568. // Subsequent passes: fuzzy match
  7569. if (i) {
  7570. bitArr[j] |=
  7571. ((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1 | lastBitArr[j + 1];
  7572. }
  7573. if (bitArr[j] & mask) {
  7574. finalScore = computeScore(pattern, {
  7575. errors: i,
  7576. currentLocation,
  7577. expectedLocation,
  7578. distance,
  7579. ignoreLocation
  7580. });
  7581. // This match will almost certainly be better than any existing match.
  7582. // But check anyway.
  7583. if (finalScore <= currentThreshold) {
  7584. // Indeed it is
  7585. currentThreshold = finalScore;
  7586. bestLocation = currentLocation;
  7587. // Already passed `loc`, downhill from here on in.
  7588. if (bestLocation <= expectedLocation) {
  7589. break
  7590. }
  7591. // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.
  7592. start = Math.max(1, 2 * expectedLocation - bestLocation);
  7593. }
  7594. }
  7595. }
  7596. // No hope for a (better) match at greater error levels.
  7597. const score = computeScore(pattern, {
  7598. errors: i + 1,
  7599. currentLocation: expectedLocation,
  7600. expectedLocation,
  7601. distance,
  7602. ignoreLocation
  7603. });
  7604. if (score > currentThreshold) {
  7605. break
  7606. }
  7607. lastBitArr = bitArr;
  7608. }
  7609. const result = {
  7610. isMatch: bestLocation >= 0,
  7611. // Count exact matches (those with a score of 0) to be "almost" exact
  7612. score: Math.max(0.001, finalScore)
  7613. };
  7614. if (computeMatches) {
  7615. const indices = convertMaskToIndices(matchMask, minMatchCharLength);
  7616. if (!indices.length) {
  7617. result.isMatch = false;
  7618. } else if (includeMatches) {
  7619. result.indices = indices;
  7620. }
  7621. }
  7622. return result
  7623. }
  7624. function createPatternAlphabet(pattern) {
  7625. let mask = {};
  7626. for (let i = 0, len = pattern.length; i < len; i += 1) {
  7627. const char = pattern.charAt(i);
  7628. mask[char] = (mask[char] || 0) | (1 << (len - i - 1));
  7629. }
  7630. return mask
  7631. }
  7632. class BitapSearch {
  7633. constructor(
  7634. pattern,
  7635. {
  7636. location = Config.location,
  7637. threshold = Config.threshold,
  7638. distance = Config.distance,
  7639. includeMatches = Config.includeMatches,
  7640. findAllMatches = Config.findAllMatches,
  7641. minMatchCharLength = Config.minMatchCharLength,
  7642. isCaseSensitive = Config.isCaseSensitive,
  7643. ignoreLocation = Config.ignoreLocation
  7644. } = {}
  7645. ) {
  7646. this.options = {
  7647. location,
  7648. threshold,
  7649. distance,
  7650. includeMatches,
  7651. findAllMatches,
  7652. minMatchCharLength,
  7653. isCaseSensitive,
  7654. ignoreLocation
  7655. };
  7656. this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
  7657. this.chunks = [];
  7658. if (!this.pattern.length) {
  7659. return
  7660. }
  7661. const addChunk = (pattern, startIndex) => {
  7662. this.chunks.push({
  7663. pattern,
  7664. alphabet: createPatternAlphabet(pattern),
  7665. startIndex
  7666. });
  7667. };
  7668. const len = this.pattern.length;
  7669. if (len > MAX_BITS) {
  7670. let i = 0;
  7671. const remainder = len % MAX_BITS;
  7672. const end = len - remainder;
  7673. while (i < end) {
  7674. addChunk(this.pattern.substr(i, MAX_BITS), i);
  7675. i += MAX_BITS;
  7676. }
  7677. if (remainder) {
  7678. const startIndex = len - MAX_BITS;
  7679. addChunk(this.pattern.substr(startIndex), startIndex);
  7680. }
  7681. } else {
  7682. addChunk(this.pattern, 0);
  7683. }
  7684. }
  7685. searchIn(text) {
  7686. const { isCaseSensitive, includeMatches } = this.options;
  7687. if (!isCaseSensitive) {
  7688. text = text.toLowerCase();
  7689. }
  7690. // Exact match
  7691. if (this.pattern === text) {
  7692. let result = {
  7693. isMatch: true,
  7694. score: 0
  7695. };
  7696. if (includeMatches) {
  7697. result.indices = [[0, text.length - 1]];
  7698. }
  7699. return result
  7700. }
  7701. // Otherwise, use Bitap algorithm
  7702. const {
  7703. location,
  7704. distance,
  7705. threshold,
  7706. findAllMatches,
  7707. minMatchCharLength,
  7708. ignoreLocation
  7709. } = this.options;
  7710. let allIndices = [];
  7711. let totalScore = 0;
  7712. let hasMatches = false;
  7713. this.chunks.forEach(({ pattern, alphabet, startIndex }) => {
  7714. const { isMatch, score, indices } = search(text, pattern, alphabet, {
  7715. location: location + startIndex,
  7716. distance,
  7717. threshold,
  7718. findAllMatches,
  7719. minMatchCharLength,
  7720. includeMatches,
  7721. ignoreLocation
  7722. });
  7723. if (isMatch) {
  7724. hasMatches = true;
  7725. }
  7726. totalScore += score;
  7727. if (isMatch && indices) {
  7728. allIndices = [...allIndices, ...indices];
  7729. }
  7730. });
  7731. let result = {
  7732. isMatch: hasMatches,
  7733. score: hasMatches ? totalScore / this.chunks.length : 1
  7734. };
  7735. if (hasMatches && includeMatches) {
  7736. result.indices = allIndices;
  7737. }
  7738. return result
  7739. }
  7740. }
  7741. class BaseMatch {
  7742. constructor(pattern) {
  7743. this.pattern = pattern;
  7744. }
  7745. static isMultiMatch(pattern) {
  7746. return getMatch(pattern, this.multiRegex)
  7747. }
  7748. static isSingleMatch(pattern) {
  7749. return getMatch(pattern, this.singleRegex)
  7750. }
  7751. search(/*text*/) {}
  7752. }
  7753. function getMatch(pattern, exp) {
  7754. const matches = pattern.match(exp);
  7755. return matches ? matches[1] : null
  7756. }
  7757. // Token: 'file
  7758. class ExactMatch extends BaseMatch {
  7759. constructor(pattern) {
  7760. super(pattern);
  7761. }
  7762. static get type() {
  7763. return 'exact'
  7764. }
  7765. static get multiRegex() {
  7766. return /^="(.*)"$/
  7767. }
  7768. static get singleRegex() {
  7769. return /^=(.*)$/
  7770. }
  7771. search(text) {
  7772. const isMatch = text === this.pattern;
  7773. return {
  7774. isMatch,
  7775. score: isMatch ? 0 : 1,
  7776. indices: [0, this.pattern.length - 1]
  7777. }
  7778. }
  7779. }
  7780. // Token: !fire
  7781. class InverseExactMatch extends BaseMatch {
  7782. constructor(pattern) {
  7783. super(pattern);
  7784. }
  7785. static get type() {
  7786. return 'inverse-exact'
  7787. }
  7788. static get multiRegex() {
  7789. return /^!"(.*)"$/
  7790. }
  7791. static get singleRegex() {
  7792. return /^!(.*)$/
  7793. }
  7794. search(text) {
  7795. const index = text.indexOf(this.pattern);
  7796. const isMatch = index === -1;
  7797. return {
  7798. isMatch,
  7799. score: isMatch ? 0 : 1,
  7800. indices: [0, text.length - 1]
  7801. }
  7802. }
  7803. }
  7804. // Token: ^file
  7805. class PrefixExactMatch extends BaseMatch {
  7806. constructor(pattern) {
  7807. super(pattern);
  7808. }
  7809. static get type() {
  7810. return 'prefix-exact'
  7811. }
  7812. static get multiRegex() {
  7813. return /^\^"(.*)"$/
  7814. }
  7815. static get singleRegex() {
  7816. return /^\^(.*)$/
  7817. }
  7818. search(text) {
  7819. const isMatch = text.startsWith(this.pattern);
  7820. return {
  7821. isMatch,
  7822. score: isMatch ? 0 : 1,
  7823. indices: [0, this.pattern.length - 1]
  7824. }
  7825. }
  7826. }
  7827. // Token: !^fire
  7828. class InversePrefixExactMatch extends BaseMatch {
  7829. constructor(pattern) {
  7830. super(pattern);
  7831. }
  7832. static get type() {
  7833. return 'inverse-prefix-exact'
  7834. }
  7835. static get multiRegex() {
  7836. return /^!\^"(.*)"$/
  7837. }
  7838. static get singleRegex() {
  7839. return /^!\^(.*)$/
  7840. }
  7841. search(text) {
  7842. const isMatch = !text.startsWith(this.pattern);
  7843. return {
  7844. isMatch,
  7845. score: isMatch ? 0 : 1,
  7846. indices: [0, text.length - 1]
  7847. }
  7848. }
  7849. }
  7850. // Token: .file$
  7851. class SuffixExactMatch extends BaseMatch {
  7852. constructor(pattern) {
  7853. super(pattern);
  7854. }
  7855. static get type() {
  7856. return 'suffix-exact'
  7857. }
  7858. static get multiRegex() {
  7859. return /^"(.*)"\$$/
  7860. }
  7861. static get singleRegex() {
  7862. return /^(.*)\$$/
  7863. }
  7864. search(text) {
  7865. const isMatch = text.endsWith(this.pattern);
  7866. return {
  7867. isMatch,
  7868. score: isMatch ? 0 : 1,
  7869. indices: [text.length - this.pattern.length, text.length - 1]
  7870. }
  7871. }
  7872. }
  7873. // Token: !.file$
  7874. class InverseSuffixExactMatch extends BaseMatch {
  7875. constructor(pattern) {
  7876. super(pattern);
  7877. }
  7878. static get type() {
  7879. return 'inverse-suffix-exact'
  7880. }
  7881. static get multiRegex() {
  7882. return /^!"(.*)"\$$/
  7883. }
  7884. static get singleRegex() {
  7885. return /^!(.*)\$$/
  7886. }
  7887. search(text) {
  7888. const isMatch = !text.endsWith(this.pattern);
  7889. return {
  7890. isMatch,
  7891. score: isMatch ? 0 : 1,
  7892. indices: [0, text.length - 1]
  7893. }
  7894. }
  7895. }
  7896. class FuzzyMatch extends BaseMatch {
  7897. constructor(
  7898. pattern,
  7899. {
  7900. location = Config.location,
  7901. threshold = Config.threshold,
  7902. distance = Config.distance,
  7903. includeMatches = Config.includeMatches,
  7904. findAllMatches = Config.findAllMatches,
  7905. minMatchCharLength = Config.minMatchCharLength,
  7906. isCaseSensitive = Config.isCaseSensitive,
  7907. ignoreLocation = Config.ignoreLocation
  7908. } = {}
  7909. ) {
  7910. super(pattern);
  7911. this._bitapSearch = new BitapSearch(pattern, {
  7912. location,
  7913. threshold,
  7914. distance,
  7915. includeMatches,
  7916. findAllMatches,
  7917. minMatchCharLength,
  7918. isCaseSensitive,
  7919. ignoreLocation
  7920. });
  7921. }
  7922. static get type() {
  7923. return 'fuzzy'
  7924. }
  7925. static get multiRegex() {
  7926. return /^"(.*)"$/
  7927. }
  7928. static get singleRegex() {
  7929. return /^(.*)$/
  7930. }
  7931. search(text) {
  7932. return this._bitapSearch.searchIn(text)
  7933. }
  7934. }
  7935. // Token: 'file
  7936. class IncludeMatch extends BaseMatch {
  7937. constructor(pattern) {
  7938. super(pattern);
  7939. }
  7940. static get type() {
  7941. return 'include'
  7942. }
  7943. static get multiRegex() {
  7944. return /^'"(.*)"$/
  7945. }
  7946. static get singleRegex() {
  7947. return /^'(.*)$/
  7948. }
  7949. search(text) {
  7950. let location = 0;
  7951. let index;
  7952. const indices = [];
  7953. const patternLen = this.pattern.length;
  7954. // Get all exact matches
  7955. while ((index = text.indexOf(this.pattern, location)) > -1) {
  7956. location = index + patternLen;
  7957. indices.push([index, location - 1]);
  7958. }
  7959. const isMatch = !!indices.length;
  7960. return {
  7961. isMatch,
  7962. score: isMatch ? 0 : 1,
  7963. indices
  7964. }
  7965. }
  7966. }
  7967. // ❗Order is important. DO NOT CHANGE.
  7968. const searchers = [
  7969. ExactMatch,
  7970. IncludeMatch,
  7971. PrefixExactMatch,
  7972. InversePrefixExactMatch,
  7973. InverseSuffixExactMatch,
  7974. SuffixExactMatch,
  7975. InverseExactMatch,
  7976. FuzzyMatch
  7977. ];
  7978. const searchersLen = searchers.length;
  7979. // Regex to split by spaces, but keep anything in quotes together
  7980. const SPACE_RE = / +(?=([^\"]*\"[^\"]*\")*[^\"]*$)/;
  7981. const OR_TOKEN = '|';
  7982. // Return a 2D array representation of the query, for simpler parsing.
  7983. // Example:
  7984. // "^core go$ | rb$ | py$ xy$" => [["^core", "go$"], ["rb$"], ["py$", "xy$"]]
  7985. function parseQuery(pattern, options = {}) {
  7986. return pattern.split(OR_TOKEN).map((item) => {
  7987. let query = item
  7988. .trim()
  7989. .split(SPACE_RE)
  7990. .filter((item) => item && !!item.trim());
  7991. let results = [];
  7992. for (let i = 0, len = query.length; i < len; i += 1) {
  7993. const queryItem = query[i];
  7994. // 1. Handle multiple query match (i.e, once that are quoted, like `"hello world"`)
  7995. let found = false;
  7996. let idx = -1;
  7997. while (!found && ++idx < searchersLen) {
  7998. const searcher = searchers[idx];
  7999. let token = searcher.isMultiMatch(queryItem);
  8000. if (token) {
  8001. results.push(new searcher(token, options));
  8002. found = true;
  8003. }
  8004. }
  8005. if (found) {
  8006. continue
  8007. }
  8008. // 2. Handle single query matches (i.e, once that are *not* quoted)
  8009. idx = -1;
  8010. while (++idx < searchersLen) {
  8011. const searcher = searchers[idx];
  8012. let token = searcher.isSingleMatch(queryItem);
  8013. if (token) {
  8014. results.push(new searcher(token, options));
  8015. break
  8016. }
  8017. }
  8018. }
  8019. return results
  8020. })
  8021. }
  8022. // These extended matchers can return an array of matches, as opposed
  8023. // to a singl match
  8024. const MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]);
  8025. /**
  8026. * Command-like searching
  8027. * ======================
  8028. *
  8029. * Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`,
  8030. * search in a given text.
  8031. *
  8032. * Search syntax:
  8033. *
  8034. * | Token | Match type | Description |
  8035. * | ----------- | -------------------------- | -------------------------------------- |
  8036. * | `jscript` | fuzzy-match | Items that fuzzy match `jscript` |
  8037. * | `=scheme` | exact-match | Items that are `scheme` |
  8038. * | `'python` | include-match | Items that include `python` |
  8039. * | `!ruby` | inverse-exact-match | Items that do not include `ruby` |
  8040. * | `^java` | prefix-exact-match | Items that start with `java` |
  8041. * | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` |
  8042. * | `.js$` | suffix-exact-match | Items that end with `.js` |
  8043. * | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` |
  8044. *
  8045. * A single pipe character acts as an OR operator. For example, the following
  8046. * query matches entries that start with `core` and end with either`go`, `rb`,
  8047. * or`py`.
  8048. *
  8049. * ```
  8050. * ^core go$ | rb$ | py$
  8051. * ```
  8052. */
  8053. class ExtendedSearch {
  8054. constructor(
  8055. pattern,
  8056. {
  8057. isCaseSensitive = Config.isCaseSensitive,
  8058. includeMatches = Config.includeMatches,
  8059. minMatchCharLength = Config.minMatchCharLength,
  8060. ignoreLocation = Config.ignoreLocation,
  8061. findAllMatches = Config.findAllMatches,
  8062. location = Config.location,
  8063. threshold = Config.threshold,
  8064. distance = Config.distance
  8065. } = {}
  8066. ) {
  8067. this.query = null;
  8068. this.options = {
  8069. isCaseSensitive,
  8070. includeMatches,
  8071. minMatchCharLength,
  8072. findAllMatches,
  8073. ignoreLocation,
  8074. location,
  8075. threshold,
  8076. distance
  8077. };
  8078. this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
  8079. this.query = parseQuery(this.pattern, this.options);
  8080. }
  8081. static condition(_, options) {
  8082. return options.useExtendedSearch
  8083. }
  8084. searchIn(text) {
  8085. const query = this.query;
  8086. if (!query) {
  8087. return {
  8088. isMatch: false,
  8089. score: 1
  8090. }
  8091. }
  8092. const { includeMatches, isCaseSensitive } = this.options;
  8093. text = isCaseSensitive ? text : text.toLowerCase();
  8094. let numMatches = 0;
  8095. let allIndices = [];
  8096. let totalScore = 0;
  8097. // ORs
  8098. for (let i = 0, qLen = query.length; i < qLen; i += 1) {
  8099. const searchers = query[i];
  8100. // Reset indices
  8101. allIndices.length = 0;
  8102. numMatches = 0;
  8103. // ANDs
  8104. for (let j = 0, pLen = searchers.length; j < pLen; j += 1) {
  8105. const searcher = searchers[j];
  8106. const { isMatch, indices, score } = searcher.search(text);
  8107. if (isMatch) {
  8108. numMatches += 1;
  8109. totalScore += score;
  8110. if (includeMatches) {
  8111. const type = searcher.constructor.type;
  8112. if (MultiMatchSet.has(type)) {
  8113. allIndices = [...allIndices, ...indices];
  8114. } else {
  8115. allIndices.push(indices);
  8116. }
  8117. }
  8118. } else {
  8119. totalScore = 0;
  8120. numMatches = 0;
  8121. allIndices.length = 0;
  8122. break
  8123. }
  8124. }
  8125. // OR condition, so if TRUE, return
  8126. if (numMatches) {
  8127. let result = {
  8128. isMatch: true,
  8129. score: totalScore / numMatches
  8130. };
  8131. if (includeMatches) {
  8132. result.indices = allIndices;
  8133. }
  8134. return result
  8135. }
  8136. }
  8137. // Nothing was matched
  8138. return {
  8139. isMatch: false,
  8140. score: 1
  8141. }
  8142. }
  8143. }
  8144. const registeredSearchers = [];
  8145. function register(...args) {
  8146. registeredSearchers.push(...args);
  8147. }
  8148. function createSearcher(pattern, options) {
  8149. for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {
  8150. let searcherClass = registeredSearchers[i];
  8151. if (searcherClass.condition(pattern, options)) {
  8152. return new searcherClass(pattern, options)
  8153. }
  8154. }
  8155. return new BitapSearch(pattern, options)
  8156. }
  8157. const LogicalOperator = {
  8158. AND: '$and',
  8159. OR: '$or'
  8160. };
  8161. const KeyType = {
  8162. PATH: '$path',
  8163. PATTERN: '$val'
  8164. };
  8165. const isExpression = (query) =>
  8166. !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);
  8167. const isPath = (query) => !!query[KeyType.PATH];
  8168. const isLeaf = (query) =>
  8169. !isArray(query) && isObject(query) && !isExpression(query);
  8170. const convertToExplicit = (query) => ({
  8171. [LogicalOperator.AND]: Object.keys(query).map((key) => ({
  8172. [key]: query[key]
  8173. }))
  8174. });
  8175. // When `auto` is `true`, the parse function will infer and initialize and add
  8176. // the appropriate `Searcher` instance
  8177. function parse(query, options, { auto = true } = {}) {
  8178. const next = (query) => {
  8179. let keys = Object.keys(query);
  8180. const isQueryPath = isPath(query);
  8181. if (!isQueryPath && keys.length > 1 && !isExpression(query)) {
  8182. return next(convertToExplicit(query))
  8183. }
  8184. if (isLeaf(query)) {
  8185. const key = isQueryPath ? query[KeyType.PATH] : keys[0];
  8186. const pattern = isQueryPath ? query[KeyType.PATTERN] : query[key];
  8187. if (!isString(pattern)) {
  8188. throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key))
  8189. }
  8190. const obj = {
  8191. keyId: createKeyId(key),
  8192. pattern
  8193. };
  8194. if (auto) {
  8195. obj.searcher = createSearcher(pattern, options);
  8196. }
  8197. return obj
  8198. }
  8199. let node = {
  8200. children: [],
  8201. operator: keys[0]
  8202. };
  8203. keys.forEach((key) => {
  8204. const value = query[key];
  8205. if (isArray(value)) {
  8206. value.forEach((item) => {
  8207. node.children.push(next(item));
  8208. });
  8209. }
  8210. });
  8211. return node
  8212. };
  8213. if (!isExpression(query)) {
  8214. query = convertToExplicit(query);
  8215. }
  8216. return next(query)
  8217. }
  8218. // Practical scoring function
  8219. function computeScore$1(
  8220. results,
  8221. { ignoreFieldNorm = Config.ignoreFieldNorm }
  8222. ) {
  8223. results.forEach((result) => {
  8224. let totalScore = 1;
  8225. result.matches.forEach(({ key, norm, score }) => {
  8226. const weight = key ? key.weight : null;
  8227. totalScore *= Math.pow(
  8228. score === 0 && weight ? Number.EPSILON : score,
  8229. (weight || 1) * (ignoreFieldNorm ? 1 : norm)
  8230. );
  8231. });
  8232. result.score = totalScore;
  8233. });
  8234. }
  8235. function transformMatches(result, data) {
  8236. const matches = result.matches;
  8237. data.matches = [];
  8238. if (!isDefined(matches)) {
  8239. return
  8240. }
  8241. matches.forEach((match) => {
  8242. if (!isDefined(match.indices) || !match.indices.length) {
  8243. return
  8244. }
  8245. const { indices, value } = match;
  8246. let obj = {
  8247. indices,
  8248. value
  8249. };
  8250. if (match.key) {
  8251. obj.key = match.key.src;
  8252. }
  8253. if (match.idx > -1) {
  8254. obj.refIndex = match.idx;
  8255. }
  8256. data.matches.push(obj);
  8257. });
  8258. }
  8259. function transformScore(result, data) {
  8260. data.score = result.score;
  8261. }
  8262. function format(
  8263. results,
  8264. docs,
  8265. {
  8266. includeMatches = Config.includeMatches,
  8267. includeScore = Config.includeScore
  8268. } = {}
  8269. ) {
  8270. const transformers = [];
  8271. if (includeMatches) transformers.push(transformMatches);
  8272. if (includeScore) transformers.push(transformScore);
  8273. return results.map((result) => {
  8274. const { idx } = result;
  8275. const data = {
  8276. item: docs[idx],
  8277. refIndex: idx
  8278. };
  8279. if (transformers.length) {
  8280. transformers.forEach((transformer) => {
  8281. transformer(result, data);
  8282. });
  8283. }
  8284. return data
  8285. })
  8286. }
  8287. class Fuse {
  8288. constructor(docs, options = {}, index) {
  8289. this.options = { ...Config, ...options };
  8290. if (
  8291. this.options.useExtendedSearch &&
  8292. !true
  8293. ) {
  8294. throw new Error(EXTENDED_SEARCH_UNAVAILABLE)
  8295. }
  8296. this._keyStore = new KeyStore(this.options.keys);
  8297. this.setCollection(docs, index);
  8298. }
  8299. setCollection(docs, index) {
  8300. this._docs = docs;
  8301. if (index && !(index instanceof FuseIndex)) {
  8302. throw new Error(INCORRECT_INDEX_TYPE)
  8303. }
  8304. this._myIndex =
  8305. index ||
  8306. createIndex(this.options.keys, this._docs, {
  8307. getFn: this.options.getFn
  8308. });
  8309. }
  8310. add(doc) {
  8311. if (!isDefined(doc)) {
  8312. return
  8313. }
  8314. this._docs.push(doc);
  8315. this._myIndex.add(doc);
  8316. }
  8317. remove(predicate = (/* doc, idx */) => false) {
  8318. const results = [];
  8319. for (let i = 0, len = this._docs.length; i < len; i += 1) {
  8320. const doc = this._docs[i];
  8321. if (predicate(doc, i)) {
  8322. this.removeAt(i);
  8323. i -= 1;
  8324. len -= 1;
  8325. results.push(doc);
  8326. }
  8327. }
  8328. return results
  8329. }
  8330. removeAt(idx) {
  8331. this._docs.splice(idx, 1);
  8332. this._myIndex.removeAt(idx);
  8333. }
  8334. getIndex() {
  8335. return this._myIndex
  8336. }
  8337. search(query, { limit = -1 } = {}) {
  8338. const {
  8339. includeMatches,
  8340. includeScore,
  8341. shouldSort,
  8342. sortFn,
  8343. ignoreFieldNorm
  8344. } = this.options;
  8345. let results = isString(query)
  8346. ? isString(this._docs[0])
  8347. ? this._searchStringList(query)
  8348. : this._searchObjectList(query)
  8349. : this._searchLogical(query);
  8350. computeScore$1(results, { ignoreFieldNorm });
  8351. if (shouldSort) {
  8352. results.sort(sortFn);
  8353. }
  8354. if (isNumber(limit) && limit > -1) {
  8355. results = results.slice(0, limit);
  8356. }
  8357. return format(results, this._docs, {
  8358. includeMatches,
  8359. includeScore
  8360. })
  8361. }
  8362. _searchStringList(query) {
  8363. const searcher = createSearcher(query, this.options);
  8364. const { records } = this._myIndex;
  8365. const results = [];
  8366. // Iterate over every string in the index
  8367. records.forEach(({ v: text, i: idx, n: norm }) => {
  8368. if (!isDefined(text)) {
  8369. return
  8370. }
  8371. const { isMatch, score, indices } = searcher.searchIn(text);
  8372. if (isMatch) {
  8373. results.push({
  8374. item: text,
  8375. idx,
  8376. matches: [{ score, value: text, norm, indices }]
  8377. });
  8378. }
  8379. });
  8380. return results
  8381. }
  8382. _searchLogical(query) {
  8383. const expression = parse(query, this.options);
  8384. const evaluate = (node, item, idx) => {
  8385. if (!node.children) {
  8386. const { keyId, searcher } = node;
  8387. const matches = this._findMatches({
  8388. key: this._keyStore.get(keyId),
  8389. value: this._myIndex.getValueForItemAtKeyId(item, keyId),
  8390. searcher
  8391. });
  8392. if (matches && matches.length) {
  8393. return [
  8394. {
  8395. idx,
  8396. item,
  8397. matches
  8398. }
  8399. ]
  8400. }
  8401. return []
  8402. }
  8403. /*eslint indent: [2, 2, {"SwitchCase": 1}]*/
  8404. switch (node.operator) {
  8405. case LogicalOperator.AND: {
  8406. const res = [];
  8407. for (let i = 0, len = node.children.length; i < len; i += 1) {
  8408. const child = node.children[i];
  8409. const result = evaluate(child, item, idx);
  8410. if (result.length) {
  8411. res.push(...result);
  8412. } else {
  8413. return []
  8414. }
  8415. }
  8416. return res
  8417. }
  8418. case LogicalOperator.OR: {
  8419. const res = [];
  8420. for (let i = 0, len = node.children.length; i < len; i += 1) {
  8421. const child = node.children[i];
  8422. const result = evaluate(child, item, idx);
  8423. if (result.length) {
  8424. res.push(...result);
  8425. break
  8426. }
  8427. }
  8428. return res
  8429. }
  8430. }
  8431. };
  8432. const records = this._myIndex.records;
  8433. const resultMap = {};
  8434. const results = [];
  8435. records.forEach(({ $: item, i: idx }) => {
  8436. if (isDefined(item)) {
  8437. let expResults = evaluate(expression, item, idx);
  8438. if (expResults.length) {
  8439. // Dedupe when adding
  8440. if (!resultMap[idx]) {
  8441. resultMap[idx] = { idx, item, matches: [] };
  8442. results.push(resultMap[idx]);
  8443. }
  8444. expResults.forEach(({ matches }) => {
  8445. resultMap[idx].matches.push(...matches);
  8446. });
  8447. }
  8448. }
  8449. });
  8450. return results
  8451. }
  8452. _searchObjectList(query) {
  8453. const searcher = createSearcher(query, this.options);
  8454. const { keys, records } = this._myIndex;
  8455. const results = [];
  8456. // List is Array<Object>
  8457. records.forEach(({ $: item, i: idx }) => {
  8458. if (!isDefined(item)) {
  8459. return
  8460. }
  8461. let matches = [];
  8462. // Iterate over every key (i.e, path), and fetch the value at that key
  8463. keys.forEach((key, keyIndex) => {
  8464. matches.push(
  8465. ...this._findMatches({
  8466. key,
  8467. value: item[keyIndex],
  8468. searcher
  8469. })
  8470. );
  8471. });
  8472. if (matches.length) {
  8473. results.push({
  8474. idx,
  8475. item,
  8476. matches
  8477. });
  8478. }
  8479. });
  8480. return results
  8481. }
  8482. _findMatches({ key, value, searcher }) {
  8483. if (!isDefined(value)) {
  8484. return []
  8485. }
  8486. let matches = [];
  8487. if (isArray(value)) {
  8488. value.forEach(({ v: text, i: idx, n: norm }) => {
  8489. if (!isDefined(text)) {
  8490. return
  8491. }
  8492. const { isMatch, score, indices } = searcher.searchIn(text);
  8493. if (isMatch) {
  8494. matches.push({
  8495. score,
  8496. key,
  8497. value: text,
  8498. idx,
  8499. norm,
  8500. indices
  8501. });
  8502. }
  8503. });
  8504. } else {
  8505. const { v: text, n: norm } = value;
  8506. const { isMatch, score, indices } = searcher.searchIn(text);
  8507. if (isMatch) {
  8508. matches.push({ score, key, value: text, norm, indices });
  8509. }
  8510. }
  8511. return matches
  8512. }
  8513. }
  8514. Fuse.version = '6.4.6';
  8515. Fuse.createIndex = createIndex;
  8516. Fuse.parseIndex = parseIndex;
  8517. Fuse.config = Config;
  8518. {
  8519. Fuse.parseQuery = parse;
  8520. }
  8521. {
  8522. register(ExtendedSearch);
  8523. }
  8524. var FileSuggestionType;
  8525. (function (FileSuggestionType) {
  8526. FileSuggestionType[FileSuggestionType["File"] = 0] = "File";
  8527. FileSuggestionType[FileSuggestionType["Alias"] = 1] = "Alias";
  8528. FileSuggestionType[FileSuggestionType["Unresolved"] = 2] = "Unresolved";
  8529. })(FileSuggestionType || (FileSuggestionType = {}));
  8530. class SuggestionMap extends Map {
  8531. }
  8532. function buildFileMap(files, unresolvedLinkNames) {
  8533. const fileMap = new SuggestionMap();
  8534. for (const file of files) {
  8535. fileMap.set(file.path, {
  8536. file,
  8537. type: FileSuggestionType.File
  8538. });
  8539. for (const alias of file.alias) {
  8540. fileMap.set(alias, {
  8541. file,
  8542. type: FileSuggestionType.Alias,
  8543. });
  8544. }
  8545. }
  8546. for (const unresolvedLinkName of unresolvedLinkNames) {
  8547. fileMap.set(unresolvedLinkName, {
  8548. type: FileSuggestionType.Unresolved
  8549. });
  8550. }
  8551. return fileMap;
  8552. }
  8553. function getAliasesForFile(file, app) {
  8554. var _a, _b, _c, _d;
  8555. const fileMetadata = app.metadataCache.getFileCache(file);
  8556. const fileMetaAlias = (_d = (_b = (_a = fileMetadata === null || fileMetadata === void 0 ? void 0 : fileMetadata.frontmatter) === null || _a === void 0 ? void 0 : _a.alias) !== null && _b !== void 0 ? _b : (_c = fileMetadata === null || fileMetadata === void 0 ? void 0 : fileMetadata.frontmatter) === null || _c === void 0 ? void 0 : _c.aliases) !== null && _d !== void 0 ? _d : "";
  8557. let aliases = [];
  8558. if (typeof fileMetaAlias === "string" && fileMetaAlias) {
  8559. aliases.push(fileMetaAlias);
  8560. }
  8561. else if (Array.isArray(fileMetaAlias)) {
  8562. const filteredAliases = fileMetaAlias.filter(v => v && typeof v === "string");
  8563. if (filteredAliases.length) {
  8564. aliases.push(...filteredAliases); // remove null values
  8565. }
  8566. }
  8567. return Object.assign(Object.assign({}, file), { alias: aliases });
  8568. }
  8569. class SilentFileSuggester extends TextInputSuggest {
  8570. constructor(app, inputEl) {
  8571. super(app, inputEl);
  8572. this.app = app;
  8573. this.inputEl = inputEl;
  8574. this.lastInput = "";
  8575. const filesAndAliases = app.vault.getMarkdownFiles().map(file => getAliasesForFile(file, app));
  8576. const unresolvedLinkNames = this.getUnresolvedLinkNames(app);
  8577. const fileAndAliasMap = buildFileMap(filesAndAliases, unresolvedLinkNames);
  8578. this.fileNames = [...fileAndAliasMap.keys()];
  8579. this.fileMap = fileAndAliasMap;
  8580. }
  8581. getSuggestions(inputStr) {
  8582. const cursorPosition = this.inputEl.selectionStart;
  8583. const inputBeforeCursor = inputStr.substr(0, cursorPosition);
  8584. const fileLinkMatch = FILE_LINK_REGEX.exec(inputBeforeCursor);
  8585. if (!fileLinkMatch) {
  8586. return [];
  8587. }
  8588. const fileNameInput = fileLinkMatch[1];
  8589. this.lastInput = fileNameInput;
  8590. const fuse = new Fuse(this.fileNames, {
  8591. findAllMatches: true,
  8592. shouldSort: true,
  8593. isCaseSensitive: false,
  8594. minMatchCharLength: 1,
  8595. threshold: 0.3,
  8596. });
  8597. const MAX_ITEMS = 50;
  8598. const search = fuse.search(this.lastInput)
  8599. .slice(0, MAX_ITEMS)
  8600. .map(value => value.item);
  8601. return search;
  8602. }
  8603. renderSuggestion(item, el) {
  8604. const suggestionItem = this.fileMap.get(item);
  8605. switch (suggestionItem.type) {
  8606. case FileSuggestionType.File:
  8607. el.innerHTML = `
  8608. <span class="suggestion-main-text">${suggestionItem.file.basename}</span>
  8609. <span class="suggestion-sub-text">${suggestionItem.file.path}</span>
  8610. `;
  8611. break;
  8612. case FileSuggestionType.Alias:
  8613. el.innerHTML = `
  8614. <span class="suggestion-main-text">${item}</span>
  8615. <span class="suggestion-sub-text">${suggestionItem.file.path}</span>
  8616. `;
  8617. break;
  8618. case FileSuggestionType.Unresolved:
  8619. el.innerHTML = `
  8620. <span class="suggestion-main-text">${item}</span>
  8621. <span class="suggestion-sub-text">Unresolved link</span>
  8622. `;
  8623. break;
  8624. default:
  8625. el.innerHTML = `
  8626. <span class="suggestion-main-text">${item}</span>
  8627. <span class="suggestion-sub-text">Unknown</span>
  8628. `;
  8629. break;
  8630. }
  8631. el.classList.add("qaFileSuggestionItem");
  8632. }
  8633. selectSuggestion(item) {
  8634. const cursorPosition = this.inputEl.selectionStart;
  8635. const lastInputLength = this.lastInput.length;
  8636. const currentInputValue = this.inputEl.value;
  8637. let insertedEndPosition = 0;
  8638. const suggestionItem = this.fileMap.get(item);
  8639. if (suggestionItem.type === FileSuggestionType.File) {
  8640. insertedEndPosition = this.makeLinkObsidianMethod(suggestionItem.file, currentInputValue, cursorPosition, lastInputLength);
  8641. }
  8642. else if (suggestionItem.type === FileSuggestionType.Alias) {
  8643. insertedEndPosition = this.makeLinkObsidianMethod(suggestionItem.file, currentInputValue, cursorPosition, lastInputLength, item);
  8644. }
  8645. else {
  8646. insertedEndPosition = this.makeLinkManually(currentInputValue, item.replace(/.md$/, ''), cursorPosition, lastInputLength);
  8647. }
  8648. this.inputEl.trigger("input");
  8649. this.close();
  8650. this.inputEl.setSelectionRange(insertedEndPosition, insertedEndPosition);
  8651. }
  8652. makeLinkObsidianMethod(linkFile, currentInputValue, cursorPosition, lastInputLength, alias) {
  8653. // Need to get file again, otherwise it won't be recognized by the link generator. (hotfix, but not a good solution)
  8654. const file = this.app.vault.getAbstractFileByPath(linkFile.path);
  8655. const link = this.app.fileManager.generateMarkdownLink(file, '', '', alias !== null && alias !== void 0 ? alias : '');
  8656. this.inputEl.value = this.getNewInputValueForFileLink(currentInputValue, link, cursorPosition, lastInputLength);
  8657. return cursorPosition - lastInputLength + link.length + 2;
  8658. }
  8659. makeLinkManually(currentInputValue, item, cursorPosition, lastInputLength) {
  8660. this.inputEl.value = this.getNewInputValueForFileName(currentInputValue, item, cursorPosition, lastInputLength);
  8661. return cursorPosition - lastInputLength + item.length + 2;
  8662. }
  8663. getNewInputValueForFileLink(currentInputElValue, selectedItem, cursorPosition, lastInputLength) {
  8664. return `${currentInputElValue.substr(0, cursorPosition - lastInputLength - 2)}${selectedItem}${currentInputElValue.substr(cursorPosition)}`;
  8665. }
  8666. getNewInputValueForFileName(currentInputElValue, selectedItem, cursorPosition, lastInputLength) {
  8667. return `${currentInputElValue.substr(0, cursorPosition - lastInputLength)}${selectedItem}]]${currentInputElValue.substr(cursorPosition)}`;
  8668. }
  8669. getUnresolvedLinkNames(app) {
  8670. const unresolvedLinks = app.metadataCache.unresolvedLinks;
  8671. const unresolvedLinkNames = new Set();
  8672. for (const sourceFileName in unresolvedLinks) {
  8673. for (const unresolvedLink in unresolvedLinks[sourceFileName]) {
  8674. unresolvedLinkNames.add(unresolvedLink);
  8675. }
  8676. }
  8677. return Array.from(unresolvedLinkNames);
  8678. }
  8679. }
  8680. class SilentTagSuggester extends TextInputSuggest {
  8681. constructor(app, inputEl) {
  8682. super(app, inputEl);
  8683. this.app = app;
  8684. this.inputEl = inputEl;
  8685. this.lastInput = "";
  8686. // @ts-ignore
  8687. this.tags = Object.keys(app.metadataCache.getTags());
  8688. }
  8689. getSuggestions(inputStr) {
  8690. const cursorPosition = this.inputEl.selectionStart;
  8691. const inputBeforeCursor = inputStr.substr(0, cursorPosition);
  8692. const tagMatch = TAG_REGEX.exec(inputBeforeCursor);
  8693. if (!tagMatch) {
  8694. return [];
  8695. }
  8696. const tagInput = tagMatch[1];
  8697. this.lastInput = tagInput;
  8698. const suggestions = this.tags.filter(tag => tag.toLowerCase().contains(tagInput.toLowerCase()));
  8699. const fuse = new Fuse(suggestions, { findAllMatches: true, threshold: 0.8 });
  8700. const search = fuse.search(this.lastInput).map(value => value.item);
  8701. return search;
  8702. }
  8703. renderSuggestion(item, el) {
  8704. el.setText(item);
  8705. }
  8706. selectSuggestion(item) {
  8707. const cursorPosition = this.inputEl.selectionStart;
  8708. const lastInputLength = this.lastInput.length;
  8709. const currentInputValue = this.inputEl.value;
  8710. let insertedEndPosition = 0;
  8711. this.inputEl.value = this.getNewInputValueForTag(currentInputValue, item, cursorPosition, lastInputLength);
  8712. insertedEndPosition = cursorPosition - lastInputLength + item.length - 1;
  8713. this.inputEl.trigger("input");
  8714. this.close();
  8715. this.inputEl.setSelectionRange(insertedEndPosition, insertedEndPosition);
  8716. }
  8717. getNewInputValueForTag(currentInputElValue, selectedItem, cursorPosition, lastInputLength) {
  8718. return `${currentInputElValue.substr(0, cursorPosition - lastInputLength - 1)}${selectedItem}${currentInputElValue.substr(cursorPosition)}`;
  8719. }
  8720. }
  8721. class GenericInputPrompt extends obsidian.Modal {
  8722. constructor(app, header, placeholder, value) {
  8723. super(app);
  8724. this.header = header;
  8725. this.didSubmit = false;
  8726. this.submitClickCallback = (evt) => this.submit();
  8727. this.cancelClickCallback = (evt) => this.cancel();
  8728. this.submitEnterCallback = (evt) => {
  8729. if (evt.key === "Enter") {
  8730. evt.preventDefault();
  8731. this.submit();
  8732. }
  8733. };
  8734. this.placeholder = placeholder;
  8735. this.input = value;
  8736. this.waitForClose = new Promise((resolve, reject) => {
  8737. this.resolvePromise = resolve;
  8738. this.rejectPromise = reject;
  8739. });
  8740. this.display();
  8741. this.open();
  8742. this.fileSuggester = new SilentFileSuggester(app, this.inputComponent.inputEl);
  8743. this.tagSuggester = new SilentTagSuggester(app, this.inputComponent.inputEl);
  8744. }
  8745. static Prompt(app, header, placeholder, value) {
  8746. const newPromptModal = new GenericInputPrompt(app, header, placeholder, value);
  8747. return newPromptModal.waitForClose;
  8748. }
  8749. display() {
  8750. this.containerEl.addClass('quickAddModal', 'qaInputPrompt');
  8751. this.contentEl.empty();
  8752. this.titleEl.textContent = this.header;
  8753. const mainContentContainer = this.contentEl.createDiv();
  8754. this.inputComponent = this.createInputField(mainContentContainer, this.placeholder, this.input);
  8755. this.createButtonBar(mainContentContainer);
  8756. }
  8757. createInputField(container, placeholder, value) {
  8758. const textComponent = new obsidian.TextComponent(container);
  8759. textComponent.inputEl.style.width = "100%";
  8760. textComponent.setPlaceholder(placeholder !== null && placeholder !== void 0 ? placeholder : "")
  8761. .setValue(value !== null && value !== void 0 ? value : "")
  8762. .onChange(value => this.input = value)
  8763. .inputEl.addEventListener('keydown', this.submitEnterCallback);
  8764. return textComponent;
  8765. }
  8766. createButton(container, text, callback) {
  8767. const btn = new obsidian.ButtonComponent(container);
  8768. btn.setButtonText(text)
  8769. .onClick(callback);
  8770. return btn;
  8771. }
  8772. createButtonBar(mainContentContainer) {
  8773. const buttonBarContainer = mainContentContainer.createDiv();
  8774. this.createButton(buttonBarContainer, "Ok", this.submitClickCallback)
  8775. .setCta().buttonEl.style.marginRight = '0';
  8776. this.createButton(buttonBarContainer, "Cancel", this.cancelClickCallback);
  8777. buttonBarContainer.style.display = 'flex';
  8778. buttonBarContainer.style.flexDirection = 'row-reverse';
  8779. buttonBarContainer.style.justifyContent = 'flex-start';
  8780. buttonBarContainer.style.marginTop = '1rem';
  8781. }
  8782. submit() {
  8783. this.didSubmit = true;
  8784. this.close();
  8785. }
  8786. cancel() {
  8787. this.close();
  8788. }
  8789. resolveInput() {
  8790. if (!this.didSubmit)
  8791. this.rejectPromise("No input given.");
  8792. else
  8793. this.resolvePromise(this.input);
  8794. }
  8795. removeInputListener() {
  8796. this.inputComponent.inputEl.removeEventListener('keydown', this.submitEnterCallback);
  8797. }
  8798. onOpen() {
  8799. super.onOpen();
  8800. this.inputComponent.inputEl.focus();
  8801. this.inputComponent.inputEl.select();
  8802. }
  8803. onClose() {
  8804. super.onClose();
  8805. this.resolveInput();
  8806. this.removeInputListener();
  8807. }
  8808. }
  8809. class LogManager {
  8810. register(logger) {
  8811. LogManager.loggers.push(logger);
  8812. return this;
  8813. }
  8814. logError(message) {
  8815. LogManager.loggers.forEach(logger => logger.logError(message));
  8816. throw new Error();
  8817. }
  8818. logWarning(message) {
  8819. LogManager.loggers.forEach(logger => logger.logError(message));
  8820. }
  8821. logMessage(message) {
  8822. LogManager.loggers.forEach(logger => logger.logMessage(message));
  8823. }
  8824. }
  8825. LogManager.loggers = [];
  8826. const log = new LogManager();
  8827. class GenericTextSuggester extends TextInputSuggest {
  8828. constructor(app, inputEl, items) {
  8829. super(app, inputEl);
  8830. this.app = app;
  8831. this.inputEl = inputEl;
  8832. this.items = items;
  8833. }
  8834. getSuggestions(inputStr) {
  8835. const inputLowerCase = inputStr.toLowerCase();
  8836. const filtered = this.items.filter(item => {
  8837. if (item.toLowerCase().contains(inputLowerCase))
  8838. return item;
  8839. });
  8840. if (!filtered)
  8841. this.close();
  8842. if ((filtered === null || filtered === void 0 ? void 0 : filtered.length) > 0)
  8843. return filtered;
  8844. }
  8845. selectSuggestion(item) {
  8846. this.inputEl.value = item;
  8847. this.inputEl.trigger("input");
  8848. this.close();
  8849. }
  8850. renderSuggestion(value, el) {
  8851. if (value)
  8852. el.setText(value);
  8853. }
  8854. }
  8855. class ChoiceBuilder extends obsidian.Modal {
  8856. constructor(app) {
  8857. super(app);
  8858. this.didSubmit = false;
  8859. this.svelteElements = [];
  8860. this.waitForClose = new Promise((resolve, reject) => {
  8861. this.resolvePromise = resolve;
  8862. this.rejectPromise = reject;
  8863. });
  8864. this.containerEl.addClass('quickAddModal');
  8865. this.open();
  8866. }
  8867. reload() {
  8868. this.contentEl.empty();
  8869. this.display();
  8870. }
  8871. addFileSearchInputToSetting(setting, value, onChangeCallback) {
  8872. let component;
  8873. setting.addSearch(searchComponent => {
  8874. component = searchComponent;
  8875. searchComponent.setValue(value);
  8876. searchComponent.setPlaceholder("File path");
  8877. const markdownFiles = this.app.vault.getMarkdownFiles().map(f => f.path);
  8878. new GenericTextSuggester(this.app, searchComponent.inputEl, markdownFiles);
  8879. searchComponent.onChange(onChangeCallback);
  8880. });
  8881. return component;
  8882. }
  8883. addCenteredChoiceNameHeader(choice) {
  8884. const headerEl = this.contentEl.createEl('h2', { cls: "choiceNameHeader" });
  8885. headerEl.setText(choice.name);
  8886. headerEl.addEventListener('click', async (ev) => {
  8887. try {
  8888. const newName = await GenericInputPrompt.Prompt(this.app, choice.name, "Choice name", choice.name);
  8889. if (newName !== choice.name) {
  8890. choice.name = newName;
  8891. headerEl.setText(newName);
  8892. }
  8893. }
  8894. catch (e) {
  8895. log.logMessage(`No new name given for ${choice.name}`);
  8896. }
  8897. });
  8898. }
  8899. onClose() {
  8900. super.onClose();
  8901. this.resolvePromise(this.choice);
  8902. this.svelteElements.forEach(el => {
  8903. if (el && el.$destroy)
  8904. el.$destroy();
  8905. });
  8906. if (!this.didSubmit)
  8907. this.rejectPromise("No answer given.");
  8908. else
  8909. this.resolvePromise(this.input);
  8910. }
  8911. }
  8912. /* src/gui/ChoiceBuilder/FolderList.svelte generated by Svelte v3.47.0 */
  8913. function add_css$3(target) {
  8914. append_styles(target, "svelte-tuapcq", ".quickAddCommandListItem.svelte-tuapcq{display:flex;align-items:center;justify-content:space-between}@media(min-width: 768px){.quickAddFolderListGrid.svelte-tuapcq{display:grid;grid-template-columns:repeat(2, 1fr);column-gap:20px}}.quickAddCommandList.svelte-tuapcq{max-width:50%;margin:12px auto}.clickable.svelte-tuapcq{cursor:pointer}");
  8915. }
  8916. function get_each_context$1(ctx, list, i) {
  8917. const child_ctx = ctx.slice();
  8918. child_ctx[4] = list[i];
  8919. child_ctx[6] = i;
  8920. return child_ctx;
  8921. }
  8922. // (11:4) {#each folders as folder, i}
  8923. function create_each_block$1(ctx) {
  8924. let div;
  8925. let span0;
  8926. let t0_value = /*folder*/ ctx[4] + "";
  8927. let t0;
  8928. let t1;
  8929. let span1;
  8930. let icon;
  8931. let t2;
  8932. let current;
  8933. let mounted;
  8934. let dispose;
  8935. icon = new Icon({ props: { data: faTrash } });
  8936. function click_handler() {
  8937. return /*click_handler*/ ctx[3](/*folder*/ ctx[4]);
  8938. }
  8939. return {
  8940. c() {
  8941. div = element("div");
  8942. span0 = element("span");
  8943. t0 = text(t0_value);
  8944. t1 = space();
  8945. span1 = element("span");
  8946. create_component(icon.$$.fragment);
  8947. t2 = space();
  8948. attr(span1, "class", "clickable svelte-tuapcq");
  8949. attr(div, "class", "quickAddCommandListItem svelte-tuapcq");
  8950. },
  8951. m(target, anchor) {
  8952. insert(target, div, anchor);
  8953. append(div, span0);
  8954. append(span0, t0);
  8955. append(div, t1);
  8956. append(div, span1);
  8957. mount_component(icon, span1, null);
  8958. append(div, t2);
  8959. current = true;
  8960. if (!mounted) {
  8961. dispose = listen(span1, "click", click_handler);
  8962. mounted = true;
  8963. }
  8964. },
  8965. p(new_ctx, dirty) {
  8966. ctx = new_ctx;
  8967. if ((!current || dirty & /*folders*/ 1) && t0_value !== (t0_value = /*folder*/ ctx[4] + "")) set_data(t0, t0_value);
  8968. },
  8969. i(local) {
  8970. if (current) return;
  8971. transition_in(icon.$$.fragment, local);
  8972. current = true;
  8973. },
  8974. o(local) {
  8975. transition_out(icon.$$.fragment, local);
  8976. current = false;
  8977. },
  8978. d(detaching) {
  8979. if (detaching) detach(div);
  8980. destroy_component(icon);
  8981. mounted = false;
  8982. dispose();
  8983. }
  8984. };
  8985. }
  8986. function create_fragment$6(ctx) {
  8987. let div;
  8988. let current;
  8989. let each_value = /*folders*/ ctx[0];
  8990. let each_blocks = [];
  8991. for (let i = 0; i < each_value.length; i += 1) {
  8992. each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i));
  8993. }
  8994. const out = i => transition_out(each_blocks[i], 1, 1, () => {
  8995. each_blocks[i] = null;
  8996. });
  8997. return {
  8998. c() {
  8999. div = element("div");
  9000. for (let i = 0; i < each_blocks.length; i += 1) {
  9001. each_blocks[i].c();
  9002. }
  9003. attr(div, "class", "quickAddFolderListGrid quickAddCommandList svelte-tuapcq");
  9004. },
  9005. m(target, anchor) {
  9006. insert(target, div, anchor);
  9007. for (let i = 0; i < each_blocks.length; i += 1) {
  9008. each_blocks[i].m(div, null);
  9009. }
  9010. current = true;
  9011. },
  9012. p(ctx, [dirty]) {
  9013. if (dirty & /*deleteFolder, folders, faTrash*/ 3) {
  9014. each_value = /*folders*/ ctx[0];
  9015. let i;
  9016. for (i = 0; i < each_value.length; i += 1) {
  9017. const child_ctx = get_each_context$1(ctx, each_value, i);
  9018. if (each_blocks[i]) {
  9019. each_blocks[i].p(child_ctx, dirty);
  9020. transition_in(each_blocks[i], 1);
  9021. } else {
  9022. each_blocks[i] = create_each_block$1(child_ctx);
  9023. each_blocks[i].c();
  9024. transition_in(each_blocks[i], 1);
  9025. each_blocks[i].m(div, null);
  9026. }
  9027. }
  9028. group_outros();
  9029. for (i = each_value.length; i < each_blocks.length; i += 1) {
  9030. out(i);
  9031. }
  9032. check_outros();
  9033. }
  9034. },
  9035. i(local) {
  9036. if (current) return;
  9037. for (let i = 0; i < each_value.length; i += 1) {
  9038. transition_in(each_blocks[i]);
  9039. }
  9040. current = true;
  9041. },
  9042. o(local) {
  9043. each_blocks = each_blocks.filter(Boolean);
  9044. for (let i = 0; i < each_blocks.length; i += 1) {
  9045. transition_out(each_blocks[i]);
  9046. }
  9047. current = false;
  9048. },
  9049. d(detaching) {
  9050. if (detaching) detach(div);
  9051. destroy_each(each_blocks, detaching);
  9052. }
  9053. };
  9054. }
  9055. function instance$6($$self, $$props, $$invalidate) {
  9056. let { folders } = $$props;
  9057. let { deleteFolder } = $$props;
  9058. const updateFolders = newFolders => {
  9059. $$invalidate(0, folders = newFolders);
  9060. };
  9061. const click_handler = folder => deleteFolder(folder);
  9062. $$self.$$set = $$props => {
  9063. if ('folders' in $$props) $$invalidate(0, folders = $$props.folders);
  9064. if ('deleteFolder' in $$props) $$invalidate(1, deleteFolder = $$props.deleteFolder);
  9065. };
  9066. return [folders, deleteFolder, updateFolders, click_handler];
  9067. }
  9068. class FolderList extends SvelteComponent {
  9069. constructor(options) {
  9070. super();
  9071. init(
  9072. this,
  9073. options,
  9074. instance$6,
  9075. create_fragment$6,
  9076. safe_not_equal,
  9077. {
  9078. folders: 0,
  9079. deleteFolder: 1,
  9080. updateFolders: 2
  9081. },
  9082. add_css$3
  9083. );
  9084. }
  9085. get updateFolders() {
  9086. return this.$$.ctx[2];
  9087. }
  9088. }
  9089. function getTemplater(app) {
  9090. // @ts-ignore
  9091. return app.plugins.plugins["templater-obsidian"];
  9092. }
  9093. async function replaceTemplaterTemplatesInCreatedFile(app, file, force = false) {
  9094. const templater = getTemplater(app);
  9095. if (templater && (force || !(templater === null || templater === void 0 ? void 0 : templater.settings["trigger_on_file_creation"]))) {
  9096. app.workspace.getActiveFile();
  9097. await templater.templater.overwrite_file_commands(file);
  9098. }
  9099. }
  9100. async function templaterParseTemplate(app, templateContent, targetFile) {
  9101. const templater = getTemplater(app);
  9102. if (!templater)
  9103. return templateContent;
  9104. return await templater.templater.parse_template({ target_file: targetFile, run_mode: 4 }, templateContent);
  9105. }
  9106. function getCoreTemplatesPath(app) {
  9107. // @ts-ignore
  9108. const internalTemplatePlugin = app.internalPlugins.plugins.templates;
  9109. if (internalTemplatePlugin) {
  9110. const templateFolderPath = internalTemplatePlugin.instance.options.folder;
  9111. if (templateFolderPath)
  9112. return templateFolderPath;
  9113. }
  9114. }
  9115. function getTemplaterTemplatesPath(app) {
  9116. const templater = getTemplater(app);
  9117. if (templater) {
  9118. const templateFolderPath = templater.settings["template_folder"];
  9119. if (templateFolderPath)
  9120. return templateFolderPath;
  9121. }
  9122. }
  9123. function getTemplateFiles(app) {
  9124. let templateFiles = new Set();
  9125. const markdownFiles = app.vault.getMarkdownFiles();
  9126. const coreTemplatesPath = getCoreTemplatesPath(app);
  9127. const templaterTemplatesPath = getTemplaterTemplatesPath(app);
  9128. markdownFiles.forEach(file => {
  9129. if (file.path.contains(coreTemplatesPath) || file.path.contains(templaterTemplatesPath))
  9130. templateFiles.add(file);
  9131. });
  9132. return [...templateFiles];
  9133. }
  9134. function getTemplatePaths(app) {
  9135. return getTemplateFiles(app).map(file => file.path);
  9136. }
  9137. function getNaturalLanguageDates(app) {
  9138. // @ts-ignore
  9139. return app.plugins.plugins["nldates-obsidian"];
  9140. }
  9141. function getDate(input) {
  9142. let duration;
  9143. if (input.offset !== null && input.offset !== undefined && typeof input.offset === "number") {
  9144. duration = window.moment.duration(input.offset, "days");
  9145. }
  9146. return input.format ? window.moment().add(duration).format(input.format)
  9147. : window.moment().add(duration).format("YYYY-MM-DD");
  9148. }
  9149. function appendToCurrentLine(toAppend, app) {
  9150. try {
  9151. const activeView = app.workspace.getActiveViewOfType(obsidian.MarkdownView);
  9152. if (!activeView) {
  9153. log.logError(`unable to append '${toAppend}' to current line.`);
  9154. return;
  9155. }
  9156. activeView.editor.replaceSelection(toAppend);
  9157. }
  9158. catch (_a) {
  9159. log.logError(`unable to append '${toAppend}' to current line.`);
  9160. }
  9161. }
  9162. function findObsidianCommand(app, commandId) {
  9163. // @ts-ignore
  9164. return app.commands.findCommand(commandId);
  9165. }
  9166. function deleteObsidianCommand(app, commandId) {
  9167. if (findObsidianCommand(app, commandId)) {
  9168. // @ts-ignore
  9169. delete app.commands.commands[commandId];
  9170. // @ts-ignore
  9171. delete app.commands.editorCommands[commandId];
  9172. }
  9173. }
  9174. function getAllFolderPathsInVault(app) {
  9175. return app.vault.getAllLoadedFiles()
  9176. .filter(f => f instanceof obsidian.TFolder)
  9177. .map(folder => folder.path);
  9178. }
  9179. function getUserScriptMemberAccess(fullMemberPath) {
  9180. const fullMemberArray = fullMemberPath.split("::");
  9181. return {
  9182. basename: fullMemberArray[0],
  9183. memberAccess: fullMemberArray.slice(1)
  9184. };
  9185. }
  9186. function waitFor(ms) {
  9187. return new Promise(res => setTimeout(res, ms));
  9188. }
  9189. function getLinesInString(input) {
  9190. let lines = [];
  9191. let tempString = input;
  9192. while (tempString.contains("\n")) {
  9193. const lineEndIndex = tempString.indexOf("\n");
  9194. lines.push(tempString.slice(0, lineEndIndex));
  9195. tempString = tempString.slice(lineEndIndex + 1);
  9196. }
  9197. lines.push(tempString);
  9198. return lines;
  9199. }
  9200. // https://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript
  9201. function escapeRegExp(text) {
  9202. return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  9203. }
  9204. async function openFile(app, file, optional) {
  9205. let leaf;
  9206. if ((optional === null || optional === void 0 ? void 0 : optional.openInNewTab) && (optional === null || optional === void 0 ? void 0 : optional.direction)) {
  9207. leaf = app.workspace.splitActiveLeaf(optional.direction);
  9208. }
  9209. else {
  9210. leaf = app.workspace.getUnpinnedLeaf();
  9211. }
  9212. await leaf.openFile(file);
  9213. if ((optional === null || optional === void 0 ? void 0 : optional.mode) || (optional === null || optional === void 0 ? void 0 : optional.focus)) {
  9214. await leaf.setViewState(Object.assign(Object.assign({}, leaf.getViewState()), { state: optional.mode && optional.mode !== 'default' ? Object.assign(Object.assign({}, leaf.view.getState()), { mode: optional.mode }) : leaf.view.getState(), popstate: true }), { focus: optional === null || optional === void 0 ? void 0 : optional.focus });
  9215. }
  9216. }
  9217. // Slightly modified version of Templater's user script import implementation
  9218. // Source: https://github.com/SilentVoid13/Templater
  9219. async function getUserScript(command, app) {
  9220. // @ts-ignore
  9221. const file = app.vault.getAbstractFileByPath(command.path);
  9222. if (!file) {
  9223. log.logError(`failed to load file ${command.path}.`);
  9224. return;
  9225. }
  9226. if (file instanceof obsidian.TFile) {
  9227. let req = (s) => window.require && window.require(s);
  9228. let exp = {};
  9229. let mod = { exports: exp };
  9230. const fileContent = await app.vault.read(file);
  9231. const fn = window.eval(`(function(require, module, exports) { ${fileContent} \n})`);
  9232. fn(req, mod, exp);
  9233. // @ts-ignore
  9234. const userScript = exp['default'] || mod.exports;
  9235. if (!userScript)
  9236. return;
  9237. let script = userScript;
  9238. const { memberAccess } = getUserScriptMemberAccess(command.name);
  9239. if (memberAccess && memberAccess.length > 0) {
  9240. let member;
  9241. while (member = memberAccess.shift()) {
  9242. script = script[member];
  9243. }
  9244. }
  9245. return script;
  9246. }
  9247. }
  9248. class Formatter {
  9249. constructor() {
  9250. this.variables = new Map();
  9251. }
  9252. replacer(str, reg, replaceValue) {
  9253. return str.replace(reg, function () { return replaceValue; });
  9254. }
  9255. replaceDateInString(input) {
  9256. let output = input;
  9257. while (DATE_REGEX.test(output)) {
  9258. const dateMatch = DATE_REGEX.exec(output);
  9259. let offset;
  9260. if (dateMatch[1]) {
  9261. const offsetString = dateMatch[1].replace('+', '').trim();
  9262. const offsetIsInt = NUMBER_REGEX.test(offsetString);
  9263. if (offsetIsInt)
  9264. offset = parseInt(offsetString);
  9265. }
  9266. output = this.replacer(output, DATE_REGEX, getDate({ offset: offset }));
  9267. }
  9268. while (DATE_REGEX_FORMATTED.test(output)) {
  9269. const dateMatch = DATE_REGEX_FORMATTED.exec(output);
  9270. const format = dateMatch[1];
  9271. let offset;
  9272. if (dateMatch[2]) {
  9273. const offsetString = dateMatch[2].replace('+', '').trim();
  9274. const offsetIsInt = NUMBER_REGEX.test(offsetString);
  9275. if (offsetIsInt)
  9276. offset = parseInt(offsetString);
  9277. }
  9278. output = this.replacer(output, DATE_REGEX_FORMATTED, getDate({ format, offset }));
  9279. }
  9280. return output;
  9281. }
  9282. async replaceValueInString(input) {
  9283. let output = input;
  9284. while (NAME_VALUE_REGEX.test(output)) {
  9285. if (!this.value)
  9286. this.value = await this.promptForValue();
  9287. output = this.replacer(output, NAME_VALUE_REGEX, this.value);
  9288. }
  9289. return output;
  9290. }
  9291. async replaceLinkToCurrentFileInString(input) {
  9292. const currentFilePathLink = this.getCurrentFileLink();
  9293. let output = input;
  9294. while (LINK_TO_CURRENT_FILE_REGEX.test(output))
  9295. output = this.replacer(output, LINK_TO_CURRENT_FILE_REGEX, currentFilePathLink);
  9296. return output;
  9297. }
  9298. async replaceVariableInString(input) {
  9299. let output = input;
  9300. while (VARIABLE_REGEX.test(output)) {
  9301. const match = VARIABLE_REGEX.exec(output);
  9302. const variableName = match[1];
  9303. if (variableName) {
  9304. if (!this.getVariableValue(variableName)) {
  9305. const suggestedValues = variableName.split(",");
  9306. if (suggestedValues.length === 1)
  9307. this.variables.set(variableName, await this.promptForVariable(variableName));
  9308. else
  9309. this.variables.set(variableName, await this.suggestForValue(suggestedValues));
  9310. }
  9311. output = this.replacer(output, VARIABLE_REGEX, this.getVariableValue(variableName));
  9312. }
  9313. else {
  9314. break;
  9315. }
  9316. }
  9317. return output;
  9318. }
  9319. async replaceMathValueInString(input) {
  9320. let output = input;
  9321. while (MATH_VALUE_REGEX.test(output)) {
  9322. const mathstr = await this.promptForMathValue();
  9323. output = this.replacer(output, MATH_VALUE_REGEX, mathstr);
  9324. }
  9325. return output;
  9326. }
  9327. async replaceMacrosInString(input) {
  9328. let output = input;
  9329. while (MACRO_REGEX.test(output)) {
  9330. const macroName = MACRO_REGEX.exec(output)[1];
  9331. const macroOutput = await this.getMacroValue(macroName);
  9332. output = this.replacer(output, MACRO_REGEX, macroOutput ? macroOutput.toString() : "");
  9333. }
  9334. return output;
  9335. }
  9336. async replaceDateVariableInString(input) {
  9337. let output = input;
  9338. while (DATE_VARIABLE_REGEX.test(output)) {
  9339. const match = DATE_VARIABLE_REGEX.exec(output);
  9340. const variableName = match[1];
  9341. const dateFormat = match[2];
  9342. if (variableName && dateFormat) {
  9343. if (!this.variables[variableName]) {
  9344. this.variables[variableName] = await this.promptForVariable(variableName);
  9345. const parseAttempt = this.getNaturalLanguageDates().parseDate(this.variables[variableName]);
  9346. if (parseAttempt)
  9347. this.variables[variableName] = parseAttempt.moment.format(dateFormat);
  9348. else
  9349. throw new Error(`unable to parse date variable ${this.variables[variableName]}`);
  9350. }
  9351. output = this.replacer(output, DATE_VARIABLE_REGEX, this.variables[variableName]);
  9352. }
  9353. else {
  9354. break;
  9355. }
  9356. }
  9357. return output;
  9358. }
  9359. async replaceTemplateInString(input) {
  9360. let output = input;
  9361. while (TEMPLATE_REGEX.test(output)) {
  9362. const templatePath = TEMPLATE_REGEX.exec(output)[1];
  9363. const templateContent = await this.getTemplateContent(templatePath);
  9364. output = this.replacer(output, TEMPLATE_REGEX, templateContent);
  9365. }
  9366. return output;
  9367. }
  9368. replaceLinebreakInString(input) {
  9369. let output = input;
  9370. let match = LINEBREAK_REGEX.exec(output);
  9371. while (match && input[match.index - 1] !== "\\") {
  9372. output = this.replacer(output, LINEBREAK_REGEX, `\n`);
  9373. match = LINEBREAK_REGEX.exec(output);
  9374. }
  9375. const EscapedLinebreakRegex = /\\\\n/;
  9376. while (EscapedLinebreakRegex.test(output)) {
  9377. output = this.replacer(output, EscapedLinebreakRegex, `\\n`);
  9378. }
  9379. return output;
  9380. }
  9381. }
  9382. class FileNameDisplayFormatter extends Formatter {
  9383. constructor(app) {
  9384. super();
  9385. this.app = app;
  9386. }
  9387. async format(input) {
  9388. let output = input;
  9389. output = await this.replaceMacrosInString(output);
  9390. output = this.replaceDateInString(output);
  9391. output = await this.replaceValueInString(output);
  9392. output = await this.replaceDateVariableInString(output);
  9393. output = await this.replaceVariableInString(output);
  9394. return `File Name: ${output}`;
  9395. }
  9396. promptForValue(header) {
  9397. return `FileName`;
  9398. }
  9399. getVariableValue(variableName) {
  9400. return variableName;
  9401. }
  9402. getCurrentFileLink() {
  9403. var _a;
  9404. return (_a = this.app.workspace.getActiveFile().path) !== null && _a !== void 0 ? _a : "";
  9405. }
  9406. getNaturalLanguageDates() {
  9407. return getNaturalLanguageDates(this.app);
  9408. }
  9409. suggestForValue(suggestedValues) {
  9410. return "_suggest_";
  9411. }
  9412. promptForMathValue() {
  9413. return Promise.resolve("_math_");
  9414. }
  9415. getMacroValue(macroName) {
  9416. return `_macro: ${macroName}`;
  9417. }
  9418. async promptForVariable(variableName) {
  9419. return `_${variableName}_`;
  9420. }
  9421. async getTemplateContent(templatePath) {
  9422. return `/${templatePath}/`;
  9423. }
  9424. async getSelectedText() {
  9425. return "_selected_";
  9426. }
  9427. }
  9428. var FormatSyntaxToken;
  9429. (function (FormatSyntaxToken) {
  9430. FormatSyntaxToken[FormatSyntaxToken["Date"] = 0] = "Date";
  9431. FormatSyntaxToken[FormatSyntaxToken["DateFormat"] = 1] = "DateFormat";
  9432. FormatSyntaxToken[FormatSyntaxToken["VariableDate"] = 2] = "VariableDate";
  9433. FormatSyntaxToken[FormatSyntaxToken["Value"] = 3] = "Value";
  9434. FormatSyntaxToken[FormatSyntaxToken["Name"] = 4] = "Name";
  9435. FormatSyntaxToken[FormatSyntaxToken["Variable"] = 5] = "Variable";
  9436. FormatSyntaxToken[FormatSyntaxToken["LinkCurrent"] = 6] = "LinkCurrent";
  9437. FormatSyntaxToken[FormatSyntaxToken["Macro"] = 7] = "Macro";
  9438. FormatSyntaxToken[FormatSyntaxToken["Template"] = 8] = "Template";
  9439. FormatSyntaxToken[FormatSyntaxToken["MathValue"] = 9] = "MathValue";
  9440. })(FormatSyntaxToken || (FormatSyntaxToken = {}));
  9441. class FormatSyntaxSuggester extends TextInputSuggest {
  9442. constructor(app, inputEl, plugin, suggestForFileNames = false) {
  9443. super(app, inputEl);
  9444. this.app = app;
  9445. this.inputEl = inputEl;
  9446. this.plugin = plugin;
  9447. this.suggestForFileNames = suggestForFileNames;
  9448. this.lastInput = "";
  9449. this.macroNames = this.plugin.settings.macros.map(macro => macro.name);
  9450. this.templatePaths = getTemplatePaths(this.app);
  9451. }
  9452. getSuggestions(inputStr) {
  9453. const cursorPosition = this.inputEl.selectionStart;
  9454. const lookbehind = 15;
  9455. const inputBeforeCursor = inputStr.substr(cursorPosition - lookbehind, lookbehind);
  9456. let suggestions = [];
  9457. this.processToken(inputBeforeCursor, (match, type, suggestion) => {
  9458. this.lastInput = match[0];
  9459. this.lastInputType = type;
  9460. suggestions.push(suggestion);
  9461. if (this.lastInputType === FormatSyntaxToken.Template) {
  9462. suggestions.push(...this.templatePaths.map(templatePath => `{{TEMPLATE:${templatePath}}}`));
  9463. }
  9464. if (this.lastInputType === FormatSyntaxToken.Macro) {
  9465. suggestions.push(...this.macroNames.map(macroName => `{{MACRO:${macroName}}}`));
  9466. }
  9467. });
  9468. return suggestions;
  9469. }
  9470. selectSuggestion(item) {
  9471. const cursorPosition = this.inputEl.selectionStart;
  9472. const lastInputLength = this.lastInput.length;
  9473. const currentInputValue = this.inputEl.value;
  9474. let insertedEndPosition = 0;
  9475. const insert = (text, offset = 0) => {
  9476. return `${currentInputValue.substr(0, cursorPosition - lastInputLength + offset)}${text}${currentInputValue.substr(cursorPosition)}`;
  9477. };
  9478. this.processToken(item, ((match, type, suggestion) => {
  9479. if (item.contains(suggestion)) {
  9480. this.inputEl.value = insert(item);
  9481. this.lastInputType = type;
  9482. insertedEndPosition = cursorPosition - lastInputLength + item.length;
  9483. if (this.lastInputType === FormatSyntaxToken.VariableDate ||
  9484. this.lastInputType === FormatSyntaxToken.Variable ||
  9485. this.lastInputType === FormatSyntaxToken.DateFormat) {
  9486. insertedEndPosition -= 2;
  9487. }
  9488. }
  9489. }));
  9490. this.inputEl.trigger("input");
  9491. this.close();
  9492. this.inputEl.setSelectionRange(insertedEndPosition, insertedEndPosition);
  9493. }
  9494. renderSuggestion(value, el) {
  9495. if (value)
  9496. el.setText(value);
  9497. }
  9498. processToken(input, callback) {
  9499. const dateFormatMatch = DATE_FORMAT_SYNTAX_SUGGEST_REGEX.exec(input);
  9500. if (dateFormatMatch)
  9501. callback(dateFormatMatch, FormatSyntaxToken.DateFormat, "{{DATE:}}");
  9502. const dateMatch = DATE_SYNTAX_SUGGEST_REGEX.exec(input);
  9503. if (dateMatch)
  9504. callback(dateMatch, FormatSyntaxToken.Date, DATE_SYNTAX);
  9505. const nameMatch = NAME_SYNTAX_SUGGEST_REGEX.exec(input);
  9506. if (nameMatch)
  9507. callback(nameMatch, FormatSyntaxToken.Name, NAME_SYNTAX);
  9508. const valueMatch = VALUE_SYNTAX_SUGGEST_REGEX.exec(input);
  9509. if (valueMatch)
  9510. callback(valueMatch, FormatSyntaxToken.Value, VALUE_SYNTAX);
  9511. const mathValueMatch = MATH_VALUE_SYNTAX_SUGGEST_REGEX.exec(input);
  9512. if (mathValueMatch)
  9513. callback(mathValueMatch, FormatSyntaxToken.MathValue, MATH_VALUE_SYNTAX);
  9514. const variableMatch = VARIABLE_SYNTAX_SUGGEST_REGEX.exec(input);
  9515. if (variableMatch)
  9516. callback(variableMatch, FormatSyntaxToken.Variable, "{{VALUE:}}");
  9517. const variableDateMatch = VARIABLE_DATE_SYNTAX_SUGGEST_REGEX.exec(input);
  9518. if (variableDateMatch)
  9519. callback(variableDateMatch, FormatSyntaxToken.VariableDate, "{{VDATE:}}");
  9520. if (!this.suggestForFileNames) {
  9521. const linkCurrentMatch = LINKCURRENT_SYNTAX_SUGGEST_REGEX.exec(input);
  9522. if (linkCurrentMatch)
  9523. callback(linkCurrentMatch, FormatSyntaxToken.LinkCurrent, LINKCURRENT_SYNTAX);
  9524. const templateMatch = TEMPLATE_SYNTAX_SUGGEST_REGEX.exec(input);
  9525. if (templateMatch)
  9526. callback(templateMatch, FormatSyntaxToken.Template, "{{TEMPLATE:");
  9527. const macroMatch = MACRO_SYNTAX_SUGGEST_REGEX.exec(input);
  9528. if (macroMatch)
  9529. callback(macroMatch, FormatSyntaxToken.Macro, "{{MACRO:");
  9530. }
  9531. }
  9532. }
  9533. class ExclusiveSuggester extends TextInputSuggest {
  9534. constructor(app, inputEl, suggestItems, currentItems) {
  9535. super(app, inputEl);
  9536. this.app = app;
  9537. this.inputEl = inputEl;
  9538. this.suggestItems = suggestItems;
  9539. this.currentItems = currentItems;
  9540. }
  9541. updateCurrentItems(currentItems) {
  9542. this.currentItems = currentItems;
  9543. }
  9544. getSuggestions(inputStr) {
  9545. return this.suggestItems.filter(item => item.contains(inputStr));
  9546. }
  9547. selectSuggestion(item) {
  9548. this.inputEl.value = item;
  9549. this.inputEl.trigger("input");
  9550. this.close();
  9551. }
  9552. renderSuggestion(value, el) {
  9553. if (value)
  9554. el.setText(value);
  9555. }
  9556. }
  9557. class TemplateChoiceBuilder extends ChoiceBuilder {
  9558. constructor(app, choice, plugin) {
  9559. super(app);
  9560. this.plugin = plugin;
  9561. this.choice = choice;
  9562. this.display();
  9563. }
  9564. display() {
  9565. this.containerEl.addClass("templateChoiceBuilder");
  9566. this.addCenteredChoiceNameHeader(this.choice);
  9567. this.addTemplatePathSetting();
  9568. this.addFileNameFormatSetting();
  9569. this.addFolderSetting();
  9570. this.addAppendLinkSetting();
  9571. this.addIncrementFileNameSetting();
  9572. this.addOpenFileSetting();
  9573. if (this.choice.openFile)
  9574. this.addOpenFileInNewTabSetting();
  9575. }
  9576. addTemplatePathSetting() {
  9577. new obsidian.Setting(this.contentEl)
  9578. .setName('Template Path')
  9579. .setDesc('Path to the Template.')
  9580. .addSearch(search => {
  9581. const templates = getTemplatePaths(this.app);
  9582. search.setValue(this.choice.templatePath);
  9583. search.setPlaceholder("Template path");
  9584. new GenericTextSuggester(this.app, search.inputEl, templates);
  9585. search.onChange(value => {
  9586. this.choice.templatePath = value;
  9587. });
  9588. });
  9589. }
  9590. addFileNameFormatSetting() {
  9591. let textField;
  9592. const enableSetting = new obsidian.Setting(this.contentEl);
  9593. enableSetting.setName("File Name Format")
  9594. .setDesc("Set the file name format.")
  9595. .addToggle(toggleComponent => {
  9596. toggleComponent.setValue(this.choice.fileNameFormat.enabled)
  9597. .onChange(value => {
  9598. this.choice.fileNameFormat.enabled = value;
  9599. textField.setDisabled(!value);
  9600. });
  9601. });
  9602. const formatDisplay = this.contentEl.createEl('span');
  9603. const displayFormatter = new FileNameDisplayFormatter(this.app);
  9604. (async () => formatDisplay.textContent = await displayFormatter.format(this.choice.fileNameFormat.format))();
  9605. const formatInput = new obsidian.TextComponent(this.contentEl);
  9606. formatInput.setPlaceholder("File name format");
  9607. textField = formatInput;
  9608. formatInput.inputEl.style.width = "100%";
  9609. formatInput.inputEl.style.marginBottom = "8px";
  9610. formatInput.setValue(this.choice.fileNameFormat.format)
  9611. .setDisabled(!this.choice.fileNameFormat.enabled)
  9612. .onChange(async (value) => {
  9613. this.choice.fileNameFormat.format = value;
  9614. formatDisplay.textContent = await displayFormatter.format(value);
  9615. });
  9616. new FormatSyntaxSuggester(this.app, textField.inputEl, this.plugin, true);
  9617. }
  9618. addFolderSetting() {
  9619. var _a, _b, _c, _d;
  9620. const folderSetting = new obsidian.Setting(this.contentEl);
  9621. folderSetting.setName("Create in folder")
  9622. .setDesc("Create the file in the specified folder. If multiple folders are specified, you will be prompted for which folder to create the file in.")
  9623. .addToggle(toggle => {
  9624. toggle.setValue(this.choice.folder.enabled);
  9625. toggle.onChange(value => {
  9626. this.choice.folder.enabled = value;
  9627. this.reload();
  9628. });
  9629. });
  9630. if (this.choice.folder.enabled) {
  9631. if (!((_a = this.choice.folder) === null || _a === void 0 ? void 0 : _a.createInSameFolderAsActiveFile)) {
  9632. const chooseFolderWhenCreatingNoteContainer = this.contentEl.createDiv('chooseFolderWhenCreatingNoteContainer');
  9633. chooseFolderWhenCreatingNoteContainer.createEl('span', { text: "Choose folder when creating a new note" });
  9634. const chooseFolderWhenCreatingNote = new obsidian.ToggleComponent(chooseFolderWhenCreatingNoteContainer);
  9635. chooseFolderWhenCreatingNote.setValue((_b = this.choice.folder) === null || _b === void 0 ? void 0 : _b.chooseWhenCreatingNote)
  9636. .onChange(value => {
  9637. this.choice.folder.chooseWhenCreatingNote = value;
  9638. this.reload();
  9639. });
  9640. if (!((_c = this.choice.folder) === null || _c === void 0 ? void 0 : _c.chooseWhenCreatingNote)) {
  9641. this.addFolderSelector();
  9642. }
  9643. }
  9644. if (!((_d = this.choice.folder) === null || _d === void 0 ? void 0 : _d.chooseWhenCreatingNote)) {
  9645. const createInSameFolderAsActiveFileSetting = new obsidian.Setting(this.contentEl);
  9646. createInSameFolderAsActiveFileSetting.setName("Create in same folder as active file")
  9647. .setDesc("Creates the file in the same folder as the currently active file. Will not create the file if there is no active file.")
  9648. .addToggle(toggle => {
  9649. var _a;
  9650. return toggle
  9651. .setValue((_a = this.choice.folder) === null || _a === void 0 ? void 0 : _a.createInSameFolderAsActiveFile)
  9652. .onChange(value => {
  9653. this.choice.folder.createInSameFolderAsActiveFile = value;
  9654. this.reload();
  9655. });
  9656. });
  9657. }
  9658. }
  9659. }
  9660. addFolderSelector() {
  9661. const folderSelectionContainer = this.contentEl.createDiv('folderSelectionContainer');
  9662. const folderList = folderSelectionContainer.createDiv('folderList');
  9663. const folderListEl = new FolderList({
  9664. target: folderList,
  9665. props: {
  9666. folders: this.choice.folder.folders,
  9667. deleteFolder: (folder) => {
  9668. this.choice.folder.folders = this.choice.folder.folders.filter(f => f !== folder);
  9669. folderListEl.updateFolders(this.choice.folder.folders);
  9670. suggester.updateCurrentItems(this.choice.folder.folders);
  9671. }
  9672. }
  9673. });
  9674. this.svelteElements.push(folderListEl);
  9675. const inputContainer = folderSelectionContainer.createDiv('folderInputContainer');
  9676. const folderInput = new obsidian.TextComponent(inputContainer);
  9677. folderInput.inputEl.style.width = "100%";
  9678. folderInput.setPlaceholder("Folder path");
  9679. const allFolders = getAllFolderPathsInVault(this.app);
  9680. const suggester = new ExclusiveSuggester(this.app, folderInput.inputEl, allFolders, this.choice.folder.folders);
  9681. const addFolder = () => {
  9682. const input = folderInput.inputEl.value.trim();
  9683. if (this.choice.folder.folders.some(folder => folder === input)) {
  9684. log.logWarning("cannot add same folder twice.");
  9685. return;
  9686. }
  9687. this.choice.folder.folders.push(input);
  9688. folderListEl.updateFolders(this.choice.folder.folders);
  9689. folderInput.inputEl.value = "";
  9690. suggester.updateCurrentItems(this.choice.folder.folders);
  9691. };
  9692. folderInput.inputEl.addEventListener('keypress', (e) => {
  9693. if (e.key === 'Enter') {
  9694. addFolder();
  9695. }
  9696. });
  9697. const addButton = new obsidian.ButtonComponent(inputContainer);
  9698. addButton.setCta().setButtonText("Add").onClick(evt => {
  9699. addFolder();
  9700. });
  9701. }
  9702. addAppendLinkSetting() {
  9703. const appendLinkSetting = new obsidian.Setting(this.contentEl);
  9704. appendLinkSetting.setName("Append link")
  9705. .setDesc("Append link to created file to current file.")
  9706. .addToggle(toggle => {
  9707. toggle.setValue(this.choice.appendLink);
  9708. toggle.onChange(value => this.choice.appendLink = value);
  9709. });
  9710. }
  9711. addIncrementFileNameSetting() {
  9712. const incrementFileNameSetting = new obsidian.Setting(this.contentEl);
  9713. incrementFileNameSetting.setName("Increment file name")
  9714. .setDesc("If the file already exists, increment the file name.")
  9715. .addToggle(toggle => {
  9716. toggle.setValue(this.choice.incrementFileName);
  9717. toggle.onChange(value => this.choice.incrementFileName = value);
  9718. });
  9719. }
  9720. addOpenFileSetting() {
  9721. const noOpenSetting = new obsidian.Setting(this.contentEl);
  9722. noOpenSetting.setName("Open")
  9723. .setDesc("Open the created file.")
  9724. .addToggle(toggle => {
  9725. toggle.setValue(this.choice.openFile);
  9726. toggle.onChange(value => {
  9727. this.choice.openFile = value;
  9728. this.reload();
  9729. });
  9730. })
  9731. .addDropdown(dropdown => {
  9732. dropdown.selectEl.style.marginLeft = "10px";
  9733. if (!this.choice.openFileInMode)
  9734. this.choice.openFileInMode = 'default';
  9735. dropdown
  9736. .addOption('source', 'Source')
  9737. .addOption('preview', 'Preview')
  9738. .addOption('default', 'Default')
  9739. .setValue(this.choice.openFileInMode)
  9740. .onChange(value => this.choice.openFileInMode = value);
  9741. });
  9742. }
  9743. addOpenFileInNewTabSetting() {
  9744. const newTabSetting = new obsidian.Setting(this.contentEl);
  9745. newTabSetting.setName("New Tab")
  9746. .setDesc("Open created file in a new tab.")
  9747. .addToggle(toggle => {
  9748. toggle.setValue(this.choice.openFileInNewTab.enabled);
  9749. toggle.onChange(value => this.choice.openFileInNewTab.enabled = value);
  9750. })
  9751. .addDropdown(dropdown => {
  9752. dropdown.selectEl.style.marginLeft = "10px";
  9753. dropdown.addOption(NewTabDirection.vertical, "Vertical");
  9754. dropdown.addOption(NewTabDirection.horizontal, "Horizontal");
  9755. dropdown.setValue(this.choice.openFileInNewTab.direction);
  9756. dropdown.onChange(value => this.choice.openFileInNewTab.direction = value);
  9757. });
  9758. new obsidian.Setting(this.contentEl)
  9759. .setName("Focus new pane")
  9760. .setDesc("Focus the opened tab immediately")
  9761. .addToggle(toggle => toggle
  9762. .setValue(this.choice.openFileInNewTab.focus)
  9763. .onChange(value => this.choice.openFileInNewTab.focus = value));
  9764. }
  9765. }
  9766. class QuickAddEngine {
  9767. constructor(app) {
  9768. this.app = app;
  9769. }
  9770. async createFolder(folder) {
  9771. const folderExists = await this.app.vault.adapter.exists(folder);
  9772. if (!folderExists) {
  9773. await this.app.vault.createFolder(folder);
  9774. }
  9775. }
  9776. formatFilePath(folderPath, fileName) {
  9777. const actualFolderPath = folderPath ? `${folderPath}/` : "";
  9778. const formattedFileName = fileName.replace(MARKDOWN_FILE_EXTENSION_REGEX, '');
  9779. return `${actualFolderPath}${formattedFileName}.md`;
  9780. }
  9781. async fileExists(filePath) {
  9782. return await this.app.vault.adapter.exists(filePath);
  9783. }
  9784. async getFileByPath(filePath) {
  9785. const file = await this.app.vault.getAbstractFileByPath(filePath);
  9786. if (!file) {
  9787. log.logError(`${filePath} not found`);
  9788. return null;
  9789. }
  9790. if (file instanceof obsidian.TFolder) {
  9791. log.logError(`${filePath} found but it's a folder`);
  9792. return null;
  9793. }
  9794. if (file instanceof obsidian.TFile)
  9795. return file;
  9796. }
  9797. async createFileWithInput(filePath, fileContent) {
  9798. const dirMatch = filePath.match(/(.*)[\/\\]/);
  9799. let dirName = "";
  9800. if (dirMatch)
  9801. dirName = dirMatch[1];
  9802. if (await this.app.vault.adapter.exists(dirName)) {
  9803. return await this.app.vault.create(filePath, fileContent);
  9804. }
  9805. else {
  9806. await this.createFolder(dirName);
  9807. return await this.app.vault.create(filePath, fileContent);
  9808. }
  9809. }
  9810. }
  9811. class GenericSuggester extends obsidian.FuzzySuggestModal {
  9812. constructor(app, displayItems, items) {
  9813. super(app);
  9814. this.displayItems = displayItems;
  9815. this.items = items;
  9816. this.promise = new Promise((resolve, reject) => { (this.resolvePromise = resolve); (this.rejectPromise = reject); });
  9817. this.open();
  9818. }
  9819. static Suggest(app, displayItems, items) {
  9820. const newSuggester = new GenericSuggester(app, displayItems, items);
  9821. return newSuggester.promise;
  9822. }
  9823. getItemText(item) {
  9824. return this.displayItems[this.items.indexOf(item)];
  9825. }
  9826. getItems() {
  9827. return this.items;
  9828. }
  9829. selectSuggestion(value, evt) {
  9830. this.resolved = true;
  9831. super.selectSuggestion(value, evt);
  9832. }
  9833. onChooseItem(item, evt) {
  9834. this.resolved = true;
  9835. this.resolvePromise(item);
  9836. }
  9837. onClose() {
  9838. super.onClose();
  9839. if (!this.resolved)
  9840. this.rejectPromise("no input given.");
  9841. }
  9842. }
  9843. var CommandType;
  9844. (function (CommandType) {
  9845. CommandType["Obsidian"] = "Obsidian";
  9846. CommandType["UserScript"] = "UserScript";
  9847. CommandType["Choice"] = "Choice";
  9848. CommandType["Wait"] = "Wait";
  9849. CommandType["NestedChoice"] = "NestedChoice";
  9850. CommandType["EditorCommand"] = "EditorCommand";
  9851. })(CommandType || (CommandType = {}));
  9852. class GenericCheckboxPrompt extends obsidian.Modal {
  9853. constructor(app, items, selectedItems = []) {
  9854. super(app);
  9855. this.items = items;
  9856. this.selectedItems = selectedItems;
  9857. // This clones the item so that we don't get any unexpected modifications of the
  9858. // arguments
  9859. this._selectedItems = [...selectedItems];
  9860. this.promise = new Promise((resolve, reject) => { (this.resolvePromise = resolve); (this.rejectPromise = reject); });
  9861. this.display();
  9862. this.open();
  9863. }
  9864. static Open(app, items, selectedItems) {
  9865. const newSuggester = new GenericCheckboxPrompt(app, items, selectedItems);
  9866. return newSuggester.promise;
  9867. }
  9868. display() {
  9869. this.contentEl.empty();
  9870. this.containerEl.addClass('quickAddModal', 'checkboxPrompt');
  9871. this.addCheckboxRows();
  9872. this.addSubmitButton();
  9873. }
  9874. onClose() {
  9875. super.onClose();
  9876. if (!this.resolved)
  9877. this.rejectPromise("no input given.");
  9878. }
  9879. addCheckboxRows() {
  9880. const rowContainer = this.contentEl.createDiv('checkboxRowContainer');
  9881. this.items.forEach(item => this.addCheckboxRow(item, rowContainer));
  9882. }
  9883. addCheckboxRow(item, container) {
  9884. const checkboxRow = container.createDiv('checkboxRow');
  9885. checkboxRow.createEl('span', { text: item });
  9886. const checkbox = new obsidian.ToggleComponent(checkboxRow);
  9887. checkbox
  9888. .setTooltip(`Toggle ${item}`)
  9889. .setValue(this._selectedItems.contains(item))
  9890. .onChange(value => {
  9891. if (value)
  9892. this._selectedItems.push(item);
  9893. else {
  9894. const index = this._selectedItems.findIndex(value => item === value);
  9895. this._selectedItems.splice(index, 1);
  9896. }
  9897. });
  9898. }
  9899. addSubmitButton() {
  9900. const submitButtonContainer = this.contentEl.createDiv('submitButtonContainer');
  9901. const submitButton = new obsidian.ButtonComponent(submitButtonContainer);
  9902. submitButton.setButtonText("Submit").setCta().onClick(evt => {
  9903. this.resolved = true;
  9904. this.resolvePromise(this._selectedItems);
  9905. this.close();
  9906. });
  9907. }
  9908. }
  9909. class GenericWideInputPrompt extends obsidian.Modal {
  9910. constructor(app, header, placeholder, value) {
  9911. super(app);
  9912. this.header = header;
  9913. this.didSubmit = false;
  9914. this.submitClickCallback = (evt) => this.submit();
  9915. this.cancelClickCallback = (evt) => this.cancel();
  9916. this.submitEnterCallback = (evt) => {
  9917. if ((evt.ctrlKey || evt.metaKey) && evt.key === "Enter") {
  9918. evt.preventDefault();
  9919. this.submit();
  9920. }
  9921. };
  9922. this.placeholder = placeholder;
  9923. this.input = value;
  9924. this.waitForClose = new Promise((resolve, reject) => {
  9925. this.resolvePromise = resolve;
  9926. this.rejectPromise = reject;
  9927. });
  9928. this.display();
  9929. this.open();
  9930. this.fileSuggester = new SilentFileSuggester(app, this.inputComponent.inputEl);
  9931. this.tagSuggester = new SilentTagSuggester(app, this.inputComponent.inputEl);
  9932. }
  9933. static Prompt(app, header, placeholder, value) {
  9934. const newPromptModal = new GenericWideInputPrompt(app, header, placeholder, value);
  9935. return newPromptModal.waitForClose;
  9936. }
  9937. display() {
  9938. this.containerEl.addClass('quickAddModal', 'qaWideInputPrompt');
  9939. this.contentEl.empty();
  9940. this.titleEl.textContent = this.header;
  9941. const mainContentContainer = this.contentEl.createDiv();
  9942. this.inputComponent = this.createInputField(mainContentContainer, this.placeholder, this.input);
  9943. this.createButtonBar(mainContentContainer);
  9944. }
  9945. createInputField(container, placeholder, value) {
  9946. const textComponent = new obsidian.TextAreaComponent(container);
  9947. textComponent.inputEl.classList.add('wideInputPromptInputEl');
  9948. textComponent.setPlaceholder(placeholder !== null && placeholder !== void 0 ? placeholder : "")
  9949. .setValue(value !== null && value !== void 0 ? value : "")
  9950. .onChange(value => this.input = value)
  9951. .inputEl.addEventListener('keydown', this.submitEnterCallback);
  9952. return textComponent;
  9953. }
  9954. createButton(container, text, callback) {
  9955. const btn = new obsidian.ButtonComponent(container);
  9956. btn.setButtonText(text)
  9957. .onClick(callback);
  9958. return btn;
  9959. }
  9960. createButtonBar(mainContentContainer) {
  9961. const buttonBarContainer = mainContentContainer.createDiv();
  9962. this.createButton(buttonBarContainer, "Ok", this.submitClickCallback)
  9963. .setCta().buttonEl.style.marginRight = '0';
  9964. this.createButton(buttonBarContainer, "Cancel", this.cancelClickCallback);
  9965. buttonBarContainer.style.display = 'flex';
  9966. buttonBarContainer.style.flexDirection = 'row-reverse';
  9967. buttonBarContainer.style.justifyContent = 'flex-start';
  9968. buttonBarContainer.style.marginTop = '1rem';
  9969. }
  9970. submit() {
  9971. this.didSubmit = true;
  9972. this.close();
  9973. }
  9974. cancel() {
  9975. this.close();
  9976. }
  9977. resolveInput() {
  9978. if (!this.didSubmit)
  9979. this.rejectPromise("No input given.");
  9980. else
  9981. this.resolvePromise(this.input);
  9982. }
  9983. removeInputListener() {
  9984. this.inputComponent.inputEl.removeEventListener('keydown', this.submitEnterCallback);
  9985. }
  9986. onOpen() {
  9987. super.onOpen();
  9988. this.inputComponent.inputEl.focus();
  9989. this.inputComponent.inputEl.select();
  9990. }
  9991. onClose() {
  9992. super.onClose();
  9993. this.resolveInput();
  9994. this.removeInputListener();
  9995. }
  9996. }
  9997. class QuickAddApi {
  9998. static GetApi(app, plugin, choiceExecutor) {
  9999. return {
  10000. inputPrompt: (header, placeholder, value) => { return this.inputPrompt(app, header, placeholder, value); },
  10001. wideInputPrompt: (header, placeholder, value) => { return this.wideInputPrompt(app, header, placeholder, value); },
  10002. yesNoPrompt: (header, text) => { return this.yesNoPrompt(app, header, text); },
  10003. suggester: (displayItems, actualItems) => { return this.suggester(app, displayItems, actualItems); },
  10004. checkboxPrompt: (items, selectedItems) => { return this.checkboxPrompt(app, items, selectedItems); },
  10005. executeChoice: async (choiceName, variables) => {
  10006. const choice = plugin.getChoiceByName(choiceName);
  10007. if (!choice)
  10008. log.logError(`choice named '${choiceName}' not found`);
  10009. if (variables) {
  10010. Object.keys(variables).forEach(key => {
  10011. choiceExecutor.variables.set(key, variables[key]);
  10012. });
  10013. }
  10014. await choiceExecutor.execute(choice);
  10015. choiceExecutor.variables.clear();
  10016. },
  10017. format: async (input) => {
  10018. return new CompleteFormatter(app, plugin, choiceExecutor).formatFileContent(input);
  10019. },
  10020. utility: {
  10021. getClipboard: async () => { return await navigator.clipboard.readText(); },
  10022. setClipboard: async (text) => { return await navigator.clipboard.writeText(text); },
  10023. getSelectedText: () => {
  10024. const activeView = app.workspace.getActiveViewOfType(obsidian.MarkdownView);
  10025. if (!activeView) {
  10026. log.logError("no active view - could not get selected text.");
  10027. return;
  10028. }
  10029. if (!activeView.editor.somethingSelected()) {
  10030. log.logError("no text selected.");
  10031. return;
  10032. }
  10033. return activeView.editor.getSelection();
  10034. }
  10035. },
  10036. date: {
  10037. now: (format, offset) => {
  10038. return getDate({ format, offset });
  10039. },
  10040. tomorrow: (format) => {
  10041. return getDate({ format, offset: 1 });
  10042. },
  10043. yesterday: (format) => {
  10044. return getDate({ format, offset: -1 });
  10045. }
  10046. }
  10047. };
  10048. }
  10049. static async inputPrompt(app, header, placeholder, value) {
  10050. try {
  10051. return await GenericInputPrompt.Prompt(app, header, placeholder, value);
  10052. }
  10053. catch (_a) {
  10054. return undefined;
  10055. }
  10056. }
  10057. static async wideInputPrompt(app, header, placeholder, value) {
  10058. try {
  10059. return await GenericWideInputPrompt.Prompt(app, header, placeholder, value);
  10060. }
  10061. catch (_a) {
  10062. return undefined;
  10063. }
  10064. }
  10065. static async yesNoPrompt(app, header, text) {
  10066. try {
  10067. return await GenericYesNoPrompt.Prompt(app, header, text);
  10068. }
  10069. catch (_a) {
  10070. return undefined;
  10071. }
  10072. }
  10073. static async suggester(app, displayItems, actualItems) {
  10074. try {
  10075. let displayedItems;
  10076. if (typeof displayItems === "function") {
  10077. displayedItems = actualItems.map(displayItems);
  10078. }
  10079. else {
  10080. displayedItems = displayItems;
  10081. }
  10082. return await GenericSuggester.Suggest(app, displayedItems, actualItems);
  10083. }
  10084. catch (_a) {
  10085. return undefined;
  10086. }
  10087. }
  10088. static async checkboxPrompt(app, items, selectedItems) {
  10089. try {
  10090. return await GenericCheckboxPrompt.Open(app, items, selectedItems);
  10091. }
  10092. catch (_a) {
  10093. return undefined;
  10094. }
  10095. }
  10096. }
  10097. class QuickAddChoiceEngine extends QuickAddEngine {
  10098. }
  10099. var EditorCommandType;
  10100. (function (EditorCommandType) {
  10101. EditorCommandType["Cut"] = "Cut";
  10102. EditorCommandType["Copy"] = "Copy";
  10103. EditorCommandType["Paste"] = "Paste";
  10104. EditorCommandType["SelectActiveLine"] = "Select active line";
  10105. EditorCommandType["SelectLinkOnActiveLine"] = "Select link on active line";
  10106. })(EditorCommandType || (EditorCommandType = {}));
  10107. class Command {
  10108. constructor(name, type) {
  10109. this.name = name;
  10110. this.type = type;
  10111. this.id = v4();
  10112. }
  10113. }
  10114. class EditorCommand extends Command {
  10115. constructor(type) {
  10116. super(type, CommandType.EditorCommand);
  10117. this.editorCommandType = type;
  10118. }
  10119. static getSelectedText(app) {
  10120. return this.getActiveMarkdownView(app).editor.getSelection();
  10121. }
  10122. static getActiveMarkdownView(app) {
  10123. const activeView = app.workspace.getActiveViewOfType(obsidian.MarkdownView);
  10124. if (!activeView) {
  10125. log.logError("no active markdown view.");
  10126. return;
  10127. }
  10128. return activeView;
  10129. }
  10130. }
  10131. class CutCommand extends EditorCommand {
  10132. constructor() {
  10133. super(EditorCommandType.Cut);
  10134. }
  10135. static async run(app) {
  10136. const selectedText = EditorCommand.getSelectedText(app);
  10137. const activeView = EditorCommand.getActiveMarkdownView(app);
  10138. if (!selectedText) {
  10139. log.logError("nothing selected.");
  10140. return;
  10141. }
  10142. await navigator.clipboard.writeText(selectedText);
  10143. activeView.editor.replaceSelection("");
  10144. }
  10145. }
  10146. class CopyCommand extends EditorCommand {
  10147. constructor() {
  10148. super(EditorCommandType.Copy);
  10149. }
  10150. static async run(app) {
  10151. const selectedText = EditorCommand.getSelectedText(app);
  10152. await navigator.clipboard.writeText(selectedText);
  10153. }
  10154. }
  10155. class PasteCommand extends EditorCommand {
  10156. constructor() {
  10157. super(EditorCommandType.Paste);
  10158. }
  10159. static async run(app) {
  10160. const clipboard = await navigator.clipboard.readText();
  10161. const activeView = EditorCommand.getActiveMarkdownView(app);
  10162. if (!activeView) {
  10163. log.logError("no active markdown view.");
  10164. return;
  10165. }
  10166. activeView.editor.replaceSelection(clipboard);
  10167. }
  10168. }
  10169. class SelectActiveLineCommand extends EditorCommand {
  10170. constructor() {
  10171. super(EditorCommandType.SelectActiveLine);
  10172. }
  10173. static run(app) {
  10174. const activeView = EditorCommand.getActiveMarkdownView(app);
  10175. const { line: lineNumber } = activeView.editor.getCursor();
  10176. const line = activeView.editor.getLine(lineNumber);
  10177. const lineLength = line.length;
  10178. activeView.editor.setSelection({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: lineLength });
  10179. }
  10180. }
  10181. class SelectLinkOnActiveLineCommand extends EditorCommand {
  10182. constructor() {
  10183. super(EditorCommandType.SelectLinkOnActiveLine);
  10184. }
  10185. static async run(app) {
  10186. const activeView = EditorCommand.getActiveMarkdownView(app);
  10187. const { line: lineNumber } = activeView.editor.getCursor();
  10188. const line = activeView.editor.getLine(lineNumber);
  10189. const match = WIKI_LINK_REGEX.exec(line);
  10190. if (!match) {
  10191. log.logError(`no internal link found on line ${lineNumber}.`);
  10192. return;
  10193. }
  10194. const matchStart = match.index;
  10195. const matchEnd = match[0].length + matchStart;
  10196. activeView.editor.setSelection({ line: lineNumber, ch: matchStart }, { line: lineNumber, ch: matchEnd });
  10197. }
  10198. }
  10199. class MacroChoiceEngine extends QuickAddChoiceEngine {
  10200. constructor(app, plugin, choice, macros, choiceExecutor, variables) {
  10201. super(app);
  10202. this.choice = choice;
  10203. this.plugin = plugin;
  10204. this.macros = macros;
  10205. this.choiceExecutor = choiceExecutor;
  10206. this.params = { app: this.app, quickAddApi: QuickAddApi.GetApi(app, plugin, choiceExecutor), variables: {}, obsidian: obsidian__namespace };
  10207. variables === null || variables === void 0 ? void 0 : variables.forEach(((value, key) => {
  10208. this.params.variables[key] = value;
  10209. }));
  10210. }
  10211. async run() {
  10212. var _a, _b, _c;
  10213. const macroId = (_a = this.choice.macroId) !== null && _a !== void 0 ? _a : (_c = (_b = this.choice) === null || _b === void 0 ? void 0 : _b.macro) === null || _c === void 0 ? void 0 : _c.id;
  10214. const macro = this.macros.find(m => m.id === macroId);
  10215. if (!macro || !(macro === null || macro === void 0 ? void 0 : macro.commands)) {
  10216. log.logError(`No commands in the selected macro. Did you select a macro for '${this.choice.name}'?`);
  10217. }
  10218. await this.executeCommands(macro.commands);
  10219. }
  10220. async executeCommands(commands) {
  10221. for (const command of commands) {
  10222. if ((command === null || command === void 0 ? void 0 : command.type) === CommandType.Obsidian)
  10223. await this.executeObsidianCommand(command);
  10224. if ((command === null || command === void 0 ? void 0 : command.type) === CommandType.UserScript)
  10225. await this.executeUserScript(command);
  10226. if ((command === null || command === void 0 ? void 0 : command.type) === CommandType.Choice)
  10227. await this.executeChoice(command);
  10228. if ((command === null || command === void 0 ? void 0 : command.type) === CommandType.Wait) {
  10229. const waitCommand = command;
  10230. await waitFor(waitCommand.time);
  10231. }
  10232. if ((command === null || command === void 0 ? void 0 : command.type) === CommandType.NestedChoice) {
  10233. await this.executeNestedChoice(command);
  10234. }
  10235. if ((command === null || command === void 0 ? void 0 : command.type) === CommandType.EditorCommand) {
  10236. await this.executeEditorCommand(command);
  10237. }
  10238. Object.keys(this.params.variables).forEach(key => {
  10239. this.choiceExecutor.variables.set(key, this.params.variables[key]);
  10240. });
  10241. }
  10242. }
  10243. // Slightly modified from Templater's user script engine:
  10244. // https://github.com/SilentVoid13/Templater/blob/master/src/UserTemplates/UserTemplateParser.ts
  10245. async executeUserScript(command) {
  10246. const userScript = await getUserScript(command, this.app);
  10247. if (!userScript) {
  10248. log.logError(`failed to load user script ${command.path}.`);
  10249. return;
  10250. }
  10251. // @ts-ignore
  10252. if (userScript.settings) {
  10253. this.userScriptCommand = command;
  10254. }
  10255. await this.userScriptDelegator(userScript);
  10256. if (this.userScriptCommand)
  10257. this.userScriptCommand = null;
  10258. }
  10259. async runScriptWithSettings(userScript, command) {
  10260. if (userScript.entry) {
  10261. await this.onExportIsFunction(userScript.entry, command.settings);
  10262. }
  10263. else {
  10264. await this.onExportIsFunction(userScript, command.settings);
  10265. }
  10266. }
  10267. async userScriptDelegator(userScript) {
  10268. switch (typeof userScript) {
  10269. case "function":
  10270. if (this.userScriptCommand) {
  10271. await this.runScriptWithSettings(userScript, this.userScriptCommand);
  10272. }
  10273. else {
  10274. await this.onExportIsFunction(userScript);
  10275. }
  10276. break;
  10277. case "object":
  10278. await this.onExportIsObject(userScript);
  10279. break;
  10280. case "bigint":
  10281. case "boolean":
  10282. case "number":
  10283. case "string":
  10284. this.output = userScript.toString();
  10285. break;
  10286. default:
  10287. log.logError(`user script in macro for '${this.choice.name}' is invalid`);
  10288. }
  10289. }
  10290. async onExportIsFunction(userScript, settings) {
  10291. this.output = await userScript(this.params, settings);
  10292. }
  10293. async onExportIsObject(obj) {
  10294. if (this.userScriptCommand && obj.entry !== null) {
  10295. await this.runScriptWithSettings(obj, this.userScriptCommand);
  10296. return;
  10297. }
  10298. try {
  10299. const keys = Object.keys(obj);
  10300. const selected = await GenericSuggester.Suggest(this.app, keys, keys);
  10301. await this.userScriptDelegator(obj[selected]);
  10302. }
  10303. catch (e) {
  10304. log.logMessage(e);
  10305. }
  10306. }
  10307. executeObsidianCommand(command) {
  10308. // @ts-ignore
  10309. this.app.commands.executeCommandById(command.commandId);
  10310. }
  10311. async executeChoice(command) {
  10312. const targetChoice = this.plugin.getChoiceById(command.choiceId);
  10313. if (!targetChoice) {
  10314. log.logError("choice could not be found.");
  10315. return;
  10316. }
  10317. await this.choiceExecutor.execute(targetChoice);
  10318. }
  10319. async executeNestedChoice(command) {
  10320. const choice = command.choice;
  10321. if (!choice) {
  10322. log.logError(`choice in ${command.name} is invalid`);
  10323. return;
  10324. }
  10325. await this.choiceExecutor.execute(choice);
  10326. }
  10327. async executeEditorCommand(command) {
  10328. switch (command.editorCommandType) {
  10329. case EditorCommandType.Cut:
  10330. await CutCommand.run(this.app);
  10331. break;
  10332. case EditorCommandType.Copy:
  10333. await CopyCommand.run(this.app);
  10334. break;
  10335. case EditorCommandType.Paste:
  10336. await PasteCommand.run(this.app);
  10337. break;
  10338. case EditorCommandType.SelectActiveLine:
  10339. await SelectActiveLineCommand.run(this.app);
  10340. break;
  10341. case EditorCommandType.SelectLinkOnActiveLine:
  10342. await SelectLinkOnActiveLineCommand.run(this.app);
  10343. break;
  10344. }
  10345. }
  10346. }
  10347. class SingleMacroEngine extends MacroChoiceEngine {
  10348. constructor(app, plugin, macros, choiceExecutor, variables) {
  10349. super(app, plugin, null, macros, choiceExecutor, variables);
  10350. }
  10351. async runAndGetOutput(macroName) {
  10352. const { basename, memberAccess } = getUserScriptMemberAccess(macroName);
  10353. const macro = this.macros.find(macro => macro.name === basename);
  10354. if (!macro) {
  10355. log.logError(`macro '${macroName}' does not exist.`);
  10356. return;
  10357. }
  10358. if (memberAccess && memberAccess.length > 0) {
  10359. this.memberAccess = memberAccess;
  10360. }
  10361. await this.executeCommands(macro.commands);
  10362. return this.output;
  10363. }
  10364. async onExportIsObject(obj) {
  10365. if (!this.memberAccess)
  10366. return await super.onExportIsObject(obj);
  10367. let newObj = obj;
  10368. this.memberAccess.forEach(key => {
  10369. newObj = newObj[key];
  10370. });
  10371. await this.userScriptDelegator(newObj);
  10372. }
  10373. }
  10374. class SingleInlineScriptEngine extends MacroChoiceEngine {
  10375. constructor(app, plugin, choiceExecutor, variables) {
  10376. super(app, plugin, null, null, choiceExecutor, variables);
  10377. }
  10378. async runAndGetOutput(code) {
  10379. const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
  10380. const userCode = new AsyncFunction(code);
  10381. return await userCode.bind(this.params, this).call();
  10382. }
  10383. }
  10384. const LATEX_CURSOR_MOVE_HERE = "\u261A";
  10385. // Modified from https://github.com/echaos/BetterLatexForObsidian (MIT License).
  10386. const commands = [
  10387. "\\!",
  10388. "\\,",
  10389. "\\:",
  10390. "\\>",
  10391. "\\;",
  10392. "\\#",
  10393. "\\$",
  10394. "\\%",
  10395. "\\&",
  10396. "\\",
  10397. "\_",
  10398. "\{ \}",
  10399. "\|",
  10400. `\^{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  10401. `\[${LATEX_CURSOR_MOVE_HERE}]${LATEX_CURSOR_MOVE_HERE}`,
  10402. "\\above",
  10403. "\\abovewithdelims",
  10404. "\\acute",
  10405. "\\aleph",
  10406. "\\alpha",
  10407. "\\amalg",
  10408. "\\And",
  10409. "\\angle",
  10410. "\\approx",
  10411. "\\approxeq",
  10412. "\\arccos",
  10413. "\\arcsin",
  10414. "\\arctan",
  10415. "\\arg",
  10416. "\\array",
  10417. "\\arrowvert",
  10418. "\\Arrowvert",
  10419. "\\ast",
  10420. "\\asymp",
  10421. "\\atop",
  10422. "\\atopwithdelims",
  10423. "\\backepsilon",
  10424. "\\backprime",
  10425. "\\backsim",
  10426. "\\backsimeq",
  10427. "\\backslash",
  10428. "\\bar",
  10429. "\\barwedge",
  10430. "\\Bbb",
  10431. "\\Bbbk",
  10432. "\\because",
  10433. "\\begin",
  10434. "\\beta",
  10435. "\\beth",
  10436. "\\between",
  10437. "\\bf",
  10438. "\\Bigg",
  10439. "\\bigg",
  10440. "\\Big",
  10441. "\\big",
  10442. "\\Biggl", "\\Biggm", "\\Biggr",
  10443. "\\biggl", "\\biggm", "\\biggr",
  10444. "\\Bigl", "\\Bigm", "\\Bigl",
  10445. "\\bigl", "\\bigm", "\\bigr",
  10446. "\\bigcap",
  10447. "\\bigcirc",
  10448. "\\bigcup",
  10449. "\\bigodot",
  10450. "\\bigoplus",
  10451. "\\bigotimes",
  10452. "\\bigsqcup",
  10453. "\\bigstar",
  10454. "\\bigtriangledown",
  10455. "\\bigtriangleup",
  10456. "\\biguplus",
  10457. "\\bigvee",
  10458. "\\bigwedge",
  10459. "\\binom",
  10460. "\\blacklozenge",
  10461. "\\blacksquare",
  10462. "\\blacktriangle",
  10463. "\\blacktriangledown",
  10464. "\\blacktriangleleft",
  10465. "\\blacktriangleright",
  10466. "\\bmod",
  10467. "\\boldsymbol",
  10468. "\\bot",
  10469. "\\bowtie",
  10470. "\\Box",
  10471. "\\boxdot",
  10472. "\\boxed",
  10473. "\\boxminus",
  10474. "\\boxplus",
  10475. "\\boxtimes",
  10476. "\\brace",
  10477. "\\bracevert",
  10478. "\\brack",
  10479. "\\breve",
  10480. "\\bullet",
  10481. "\\Bumpeq",
  10482. "\\bumpeq",
  10483. "\\cal",
  10484. "\\cancel",
  10485. "\\Cap",
  10486. "\\cap",
  10487. "\\cases",
  10488. "\\cdot",
  10489. "\\cdotp",
  10490. "\\cdots",
  10491. "\\centerdot",
  10492. `\\cfrac{${LATEX_CURSOR_MOVE_HERE}}{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  10493. "\\check",
  10494. "\\checkmark",
  10495. "\\chi",
  10496. "\\choose",
  10497. "\\circ",
  10498. "\\circeq",
  10499. "\\circlearrowleft",
  10500. "\\circlearrowright",
  10501. "\\circledast",
  10502. "\\circledcirc",
  10503. "\\circleddash",
  10504. "\\circledR",
  10505. "\\circledS",
  10506. "\\class",
  10507. "\\clubsuit",
  10508. "\\colon",
  10509. "\\color",
  10510. "\\complement",
  10511. "\\cong",
  10512. "\\coprod",
  10513. "\\cos",
  10514. "\\cosh",
  10515. "\\cot",
  10516. "\\coth",
  10517. "\\cr",
  10518. "\\csc",
  10519. "\\cssId",
  10520. "\\Cup",
  10521. "\\cup",
  10522. "\\curlyeqprec",
  10523. "\\curlyeqsucc",
  10524. "\\curlyvee",
  10525. "\\curlywedge",
  10526. "\\curvearrowleft",
  10527. "\\curvearrowright",
  10528. "\\dagger",
  10529. "\\ddagger",
  10530. "\\daleth",
  10531. "\\dashleftarrow",
  10532. "\\dashrightarrow",
  10533. "\\dashv",
  10534. "\\dbinom",
  10535. "\\dot",
  10536. "\\ddot",
  10537. "\\dddot",
  10538. "\\ddddot",
  10539. "\\ddots",
  10540. "\\DeclareMathOperator",
  10541. "\\def",
  10542. "\\deg",
  10543. "\\Delta",
  10544. "\\delta",
  10545. "\\det",
  10546. `\\dfrac{${LATEX_CURSOR_MOVE_HERE}}{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  10547. "\\diagdown",
  10548. "\\diagup",
  10549. "\\Diamond",
  10550. "\\diamond",
  10551. "\\diamondsuit",
  10552. "\\digamma",
  10553. "\\dim",
  10554. "\\displaylines",
  10555. "\\displaystyle",
  10556. "\\div",
  10557. "\\divideontimes",
  10558. "\\Doteq",
  10559. "\\doteq",
  10560. "\\dotplus",
  10561. "\\dots",
  10562. "\\dotsb",
  10563. "\\dotsc",
  10564. "\\dotsi",
  10565. "\\dotsm",
  10566. "\\dotso",
  10567. "\\doublebarwedge",
  10568. "\\doublecap",
  10569. "\\doublecup",
  10570. "\\downarrow",
  10571. "\\Downarrow",
  10572. "\\downdownarrows",
  10573. "\\downharpoonleft",
  10574. "\\downharpoonright",
  10575. "\\ell",
  10576. "\\emptyset",
  10577. "\\end",
  10578. "\\enspace",
  10579. "\\epsilon",
  10580. "\\eqalign",
  10581. "\\eqalignno",
  10582. "\\eqcirc",
  10583. "\\eqsim",
  10584. "\\eqslantgtr",
  10585. "\\eqslantless",
  10586. "\\equiv",
  10587. "\\eta",
  10588. "\\eth",
  10589. "\\exists",
  10590. "\\exp",
  10591. "\\fallingdotseq",
  10592. "\\fbox",
  10593. "\\Finv",
  10594. "\\flat",
  10595. "\\forall",
  10596. `\\frac{${LATEX_CURSOR_MOVE_HERE}}{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  10597. "\\frak",
  10598. "\\frown",
  10599. "\\Game",
  10600. "\\Gamma",
  10601. "\\gamma",
  10602. "\\gcd",
  10603. "\\ge",
  10604. "\\geq",
  10605. "\\geqq",
  10606. "\\geqslant",
  10607. "\\genfrac",
  10608. "\\gets",
  10609. "\\gg",
  10610. "\\ggg",
  10611. "\\gggtr",
  10612. "\\gimel",
  10613. "\\gtrapprox",
  10614. "\\gnapprox",
  10615. "\\gneq",
  10616. "\\gneqq",
  10617. "\\gvertneqq",
  10618. "\\gtrsim",
  10619. "\\gnsim",
  10620. "\\grave",
  10621. "\\gt",
  10622. "\\gtrdot",
  10623. "\\gtreqless",
  10624. "\\gtreqqless",
  10625. "\\gtrless",
  10626. "\\hat",
  10627. "\\hbar",
  10628. "\\hbox",
  10629. "\\hdashline",
  10630. "\\hline",
  10631. "\\heartsuit",
  10632. "\\hfil",
  10633. "\\hfill",
  10634. "\\hom",
  10635. "\\hookleftarrow",
  10636. "\\hookrightarrow",
  10637. "\\hphantom",
  10638. "\\href",
  10639. "\\hskip",
  10640. "\\hslash",
  10641. "\\hspace",
  10642. "\\Huge",
  10643. "\\huge",
  10644. "\\iddots",
  10645. "\\idotsint",
  10646. "\\iff",
  10647. "\\iiiint",
  10648. "\\iiint",
  10649. "\\iint",
  10650. "\\int",
  10651. "\\intop",
  10652. "\\Im",
  10653. "\\imath",
  10654. "\\impliedby",
  10655. "\\implies",
  10656. "\\in",
  10657. "\\inf",
  10658. "\\infty",
  10659. "\\injlim",
  10660. "\\intercal",
  10661. "\\iota",
  10662. "\\it",
  10663. "\\jmath",
  10664. "\\Join",
  10665. "\\kappa",
  10666. "\\ker",
  10667. "\\kern",
  10668. "\\Lambda",
  10669. "\\lambda",
  10670. "\\land",
  10671. "\\langle",
  10672. "\\LARGE",
  10673. "\\Large",
  10674. "\\large",
  10675. "\\LaTeX",
  10676. "\\lbrace",
  10677. "\\lbrack",
  10678. "\\lceil",
  10679. "\\ldotp",
  10680. "\\ldots",
  10681. "\\le",
  10682. "\\leq",
  10683. "\\leqq",
  10684. "\\leqslant",
  10685. "\\leadsto",
  10686. "\\left",
  10687. "\\leftarrow",
  10688. "\\Leftarrow",
  10689. "\\leftarrowtail",
  10690. "\\leftharpoondown",
  10691. "\\leftharpoonup",
  10692. "\\leftleftarrows",
  10693. "\\leftrightarrow",
  10694. "\\Leftrightarrow",
  10695. "\\leftrightarrows",
  10696. "\\leftrightharpoons",
  10697. "\\leftrightsquigarrow",
  10698. "\\leftroot",
  10699. "\\leftthreetimes",
  10700. "\\leqalignno",
  10701. "\\lessapprox",
  10702. "\\lessdot",
  10703. "\\lesseqgtr",
  10704. "\\lesseqqgtr",
  10705. "\\lessgtr",
  10706. "\\lesssim",
  10707. "\\lfloor",
  10708. "\\lg",
  10709. "\\lgroup",
  10710. "\\lhd",
  10711. "\\lim",
  10712. "\\liminf",
  10713. "\\limits",
  10714. "\\limsup",
  10715. "\\ll",
  10716. "\\llap",
  10717. "\\llcorner",
  10718. "\\lrcorner",
  10719. "\\Lleftarrow",
  10720. "\\lll",
  10721. "\\llless",
  10722. "\\lmoustache",
  10723. "\\ln",
  10724. "\\lnapprox",
  10725. "\\lneq",
  10726. "\\lneqq",
  10727. "\\lnot",
  10728. "\\lnsim",
  10729. "\\log",
  10730. "\\longleftarrow",
  10731. "\\Longleftarrow",
  10732. "\\longrightarrow",
  10733. "\\Longrightarrow",
  10734. "\\longleftrightarrow",
  10735. "\\Longleftrightarrow",
  10736. "\\longmapsto",
  10737. "\\looparrowleft",
  10738. "\\looparrowright",
  10739. "\\lor",
  10740. "\\lower",
  10741. "\\lozenge",
  10742. "\\Lsh",
  10743. "\\lt",
  10744. "\\ltimes",
  10745. "\\lvert",
  10746. "\\lVert",
  10747. "\\lvertneqq",
  10748. "\\maltese",
  10749. "\\mapsto",
  10750. "\\mathbb",
  10751. "\\mathbf",
  10752. "\\mathbin",
  10753. "\\mathcal",
  10754. "\\mathchoice",
  10755. "\\mathclose",
  10756. "\\mathfrak",
  10757. "\\mathinner",
  10758. "\\mathit",
  10759. "\\mathop",
  10760. "\\mathopen",
  10761. "\\mathord",
  10762. "\\mathpunct",
  10763. "\\mathrel",
  10764. "\\mathring",
  10765. "\\mathrm",
  10766. "\\mathscr",
  10767. "\\mathsf",
  10768. "\\mathstrut",
  10769. "\\mathtt",
  10770. "\\matrix",
  10771. "\\max",
  10772. "\\mbox",
  10773. "\\measuredangle",
  10774. "\\mho",
  10775. "\\mid",
  10776. "\\min",
  10777. "\\mit",
  10778. "\\mod",
  10779. "\\models",
  10780. "\\moveleft",
  10781. "\\moveright",
  10782. "\\mp",
  10783. "\\mskip",
  10784. "\\mspace",
  10785. "\\mu",
  10786. "\\multimap",
  10787. "\\nabla",
  10788. "\\natural",
  10789. "\\ncong",
  10790. "\\ne",
  10791. "\\nearrow",
  10792. "\\neg",
  10793. "\\negthinspace",
  10794. "\\negmedspace",
  10795. "\\negthickspace",
  10796. "\\neq",
  10797. "\\newcommand",
  10798. "\\newenvironment",
  10799. "\\newline",
  10800. "\\nexists",
  10801. "\\ngeq",
  10802. "\\ngeqq",
  10803. "\\ngeqslant",
  10804. "\\ngtr",
  10805. "\\ni",
  10806. "\\nleftarrow",
  10807. "\\nLeftarrow",
  10808. "\\nleftrightarrow",
  10809. "\\nLeftrightarrow",
  10810. "\\nleq",
  10811. "\\nleqq",
  10812. "\\nleqslant",
  10813. "\\nless",
  10814. "\\nmid",
  10815. "\\nobreakspace",
  10816. "\\nolimits",
  10817. "\\normalsize",
  10818. "\\not",
  10819. "\\notag",
  10820. "\\notin",
  10821. "\\nparallel",
  10822. "\\nprec",
  10823. "\\npreceq",
  10824. "\\nrightarrow",
  10825. "\\nRightarrow",
  10826. "\\nshortmid",
  10827. "\\nshortparallel",
  10828. "\\nsim",
  10829. "\\nsubseteq",
  10830. "\\nsubseteqq",
  10831. "\\nsucc",
  10832. "\\nsucceq",
  10833. "\\nsupseteq",
  10834. "\\nsupseteqq",
  10835. "\\ntriangleleft",
  10836. "\\ntrianglelefteq",
  10837. "\\ntriangleright",
  10838. "\\ntrianglerighteq",
  10839. "\\nu",
  10840. "\\nVDash",
  10841. "\\nVdash",
  10842. "\\nvDash",
  10843. "\\nvdash",
  10844. "\\nwarrow",
  10845. "\\odot",
  10846. "\\ominus",
  10847. "\\oplus",
  10848. "\\oslash",
  10849. "\\otimes",
  10850. "\\oint",
  10851. "\\oldstyle",
  10852. "\\omega",
  10853. "\\Omega",
  10854. "\\omicron",
  10855. "\\operatorname",
  10856. "\\over",
  10857. "\\overbrace",
  10858. "\\overleftarrow",
  10859. "\\overrightarrow",
  10860. "\\overleftrightarrow",
  10861. "\\overline",
  10862. "\\overparen",
  10863. "\\overset",
  10864. "\\overwithdelims",
  10865. "\\owns",
  10866. "\\parallel",
  10867. "\\partial",
  10868. "\\perp",
  10869. "\\phantom",
  10870. "\\phi",
  10871. "\\Phi",
  10872. "\\pi",
  10873. "\\Pi",
  10874. "\\pitchfork",
  10875. "\\pm",
  10876. "\\pmatrix",
  10877. "\\pmb",
  10878. "\\pmod",
  10879. "\\pod",
  10880. "\\Pr",
  10881. "\\prec",
  10882. "\\precapprox",
  10883. "\\precnapprox",
  10884. "\\preccurlyeq",
  10885. "\\preceq",
  10886. "\\precneqq",
  10887. "\\precsim",
  10888. "\\precnsim",
  10889. "\\prime",
  10890. "\\prod",
  10891. "\\projlim",
  10892. "\\propto",
  10893. "\\psi",
  10894. "\\Psi",
  10895. "\\quad",
  10896. "\\qquad",
  10897. "\\raise",
  10898. "\\rangle",
  10899. "\\rbrace",
  10900. "\\rbrack",
  10901. "\\rceil",
  10902. "\\Re",
  10903. "\\renewcommand",
  10904. "\\require (non-standard)",
  10905. "\\restriction",
  10906. "\\rfloor",
  10907. "\\rgroup",
  10908. "\\rhd",
  10909. "\\rho",
  10910. "\\right",
  10911. "\\rightarrow",
  10912. "\\Rightarrow",
  10913. "\\rightarrowtail",
  10914. "\\rightharpoondown",
  10915. "\\rightharpoonup",
  10916. "\\rightleftarrows",
  10917. "\\rightleftharpoons",
  10918. "\\rightrightarrows",
  10919. "\\rightsquigarrow",
  10920. "\\rightthreetimes",
  10921. "\\risingdotseq",
  10922. "\\rlap",
  10923. "\\rm",
  10924. "\\rmoustache",
  10925. "\\Rrightarrow",
  10926. "\\Rsh",
  10927. "\\rtimes",
  10928. "\\Rule (non-standard)",
  10929. "\\rvert",
  10930. "\\rVert",
  10931. "\\S",
  10932. "\\scr",
  10933. "\\scriptscriptstyle",
  10934. "\\scriptsize",
  10935. "\\scriptstyle",
  10936. "\\searrow",
  10937. "\\sec",
  10938. "\\setminus",
  10939. "\\sf",
  10940. "\\sharp",
  10941. "\\shortmid",
  10942. "\\shortparallel",
  10943. "\\shoveleft",
  10944. "\\shoveright",
  10945. "\\sideset",
  10946. "\\sigma",
  10947. "\\Sigma",
  10948. "\\sim",
  10949. "\\simeq",
  10950. "\\sin",
  10951. "\\sinh",
  10952. "\\skew",
  10953. "\\small",
  10954. "\\smallfrown",
  10955. "\\smallint",
  10956. "\\smallsetminus",
  10957. "\\smallsmile",
  10958. "\\smash",
  10959. "\\smile",
  10960. "\\space",
  10961. "\\Space (non-standard)",
  10962. "\\spadesuit",
  10963. "\\sphericalangle",
  10964. "\\sqcap",
  10965. "\\sqcup",
  10966. "\\sqrt",
  10967. "\\sqsubset",
  10968. "\\sqsupset",
  10969. "\\sqsubseteq",
  10970. "\\sqsupseteq",
  10971. "\\square",
  10972. "\\stackrel",
  10973. "\\star",
  10974. "\\strut",
  10975. "\\style",
  10976. "\\subset",
  10977. "\\Subset",
  10978. "\\subseteq",
  10979. "\\subsetneq",
  10980. "\\subseteqq",
  10981. "\\subsetneqq",
  10982. "\\substack",
  10983. "\\succ",
  10984. "\\succapprox",
  10985. "\\succnapprox",
  10986. "\\succcurlyeq",
  10987. "\\succeq",
  10988. "\\succneqq",
  10989. "\\succsim",
  10990. "\\succnsim",
  10991. "\\sum",
  10992. "\\sup",
  10993. "\\supset",
  10994. "\\Supset",
  10995. "\\supseteq",
  10996. "\\supsetneq",
  10997. "\\supseteqq",
  10998. "\\supsetneqq",
  10999. "\\surd",
  11000. "\\swarrow",
  11001. "\\tag",
  11002. "\\tan",
  11003. "\\tanh",
  11004. "\\tau",
  11005. "\\tbinom",
  11006. "\\TeX",
  11007. `\\text{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11008. `\\textbf{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11009. `\\textit{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11010. `\\textrm{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11011. `\\textsf{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11012. `\\texttt{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11013. "\\textstyle",
  11014. `\\tfrac{${LATEX_CURSOR_MOVE_HERE}}{${LATEX_CURSOR_MOVE_HERE}}${LATEX_CURSOR_MOVE_HERE}`,
  11015. "\\therefore",
  11016. "\\theta",
  11017. "\\Theta",
  11018. "\\thickapprox",
  11019. "\\thicksim",
  11020. "\\thinspace",
  11021. "\\tilde",
  11022. "\\times",
  11023. "\\tiny",
  11024. "\\Tiny",
  11025. "\\to",
  11026. "\\top",
  11027. "\\triangle",
  11028. "\\triangledown",
  11029. "\\triangleleft",
  11030. "\\triangleright",
  11031. "\\trianglelefteq",
  11032. "\\trianglerighteq",
  11033. "\\triangleq",
  11034. "\\tt",
  11035. "\\twoheadleftarrow",
  11036. "\\twoheadrightarrow",
  11037. "\\ulcorner",
  11038. "\\urcorner",
  11039. "\\underbrace",
  11040. "\\underleftarrow",
  11041. "\\underrightarrow",
  11042. "\\underleftrightarrow",
  11043. "\\underline",
  11044. "\\underparen",
  11045. "\\underset",
  11046. "\\unicode",
  11047. "\\unlhd",
  11048. "\\unrhd",
  11049. "\\uparrow",
  11050. "\\Uparrow",
  11051. "\\updownarrow",
  11052. "\\Updownarrow",
  11053. "\\upharpoonleft",
  11054. "\\upharpoonright",
  11055. "\\uplus",
  11056. "\\uproot",
  11057. "\\upsilon",
  11058. "\\Upsilon",
  11059. "\\upuparrows",
  11060. "\\varDelta",
  11061. "\\varepsilon",
  11062. "\\varGamma",
  11063. "\\varinjlim",
  11064. "\\varkappa",
  11065. "\\varLambda",
  11066. "\\varlimsup",
  11067. "\\varliminf",
  11068. "\\varnothing",
  11069. "\\varOmega",
  11070. "\\varphi",
  11071. "\\varPhi",
  11072. "\\varpi",
  11073. "\\varPi",
  11074. "\\varprojlim",
  11075. "\\varpropto",
  11076. "\\varPsi",
  11077. "\\varrho",
  11078. "\\varsigma",
  11079. "\\varSigma",
  11080. "\\varsubsetneq",
  11081. "\\varsubsetneqq",
  11082. "\\varsupsetneq",
  11083. "\\varsupsetneqq",
  11084. "\\vartheta",
  11085. "\\varTheta",
  11086. "\\vartriangle",
  11087. "\\vartriangleleft",
  11088. "\\vartriangleright",
  11089. "\\varUpsilon",
  11090. "\\varXi",
  11091. "\\vcenter",
  11092. "\\vdash",
  11093. "\\Vdash",
  11094. "\\vDash",
  11095. "\\vdots",
  11096. "\\vec",
  11097. "\\vee",
  11098. "\\veebar",
  11099. "\\verb",
  11100. "\\vert",
  11101. "\\Vert",
  11102. "\\vphantom",
  11103. "\\Vvdash",
  11104. "\\wedge",
  11105. "\\widehat",
  11106. "\\widetilde",
  11107. "\\wp",
  11108. "\\wr",
  11109. "\\Xi",
  11110. "\\xi",
  11111. "\\xleftarrow",
  11112. "\\xrightarrow",
  11113. "\\yen",
  11114. "\\zeta",
  11115. "\\{%C\\}%C",
  11116. "\\langle %C \\rangle%C"
  11117. ];
  11118. const environments = [
  11119. "align",
  11120. "align*",
  11121. "alignat",
  11122. "alignat*",
  11123. "array",
  11124. "Bmatrix",
  11125. "bmatrix",
  11126. "cases",
  11127. "eqnarray",
  11128. "eqnarray*",
  11129. "equation",
  11130. "equation*",
  11131. "gather",
  11132. "gather*",
  11133. "matrix",
  11134. "pmatrix",
  11135. "smallmatrix",
  11136. "subarray",
  11137. "Vmatrix",
  11138. "vmatrix",
  11139. ];
  11140. function beginEndGen(symbol) {
  11141. return `\\begin{${symbol}}\n${LATEX_CURSOR_MOVE_HERE}\n\\end{${symbol}}${LATEX_CURSOR_MOVE_HERE}`;
  11142. }
  11143. const LaTeXSymbols = [...commands, ...environments.map(beginEndGen)];
  11144. const LATEX_REGEX = new RegExp(/\\([a-z{}A-Z0-9]*)$/);
  11145. class LaTeXSuggester extends TextInputSuggest {
  11146. constructor(inputEl) {
  11147. super(QuickAdd.instance.app, inputEl);
  11148. this.inputEl = inputEl;
  11149. this.lastInput = "";
  11150. this.symbols = Object.assign([], LaTeXSymbols);
  11151. this.elementsRendered = this.symbols.reduce((elements, symbol) => {
  11152. try {
  11153. elements[symbol.toString()] = obsidian.renderMath(symbol, true);
  11154. }
  11155. catch (_a) { } // Ignoring symbols that we can't use
  11156. return elements;
  11157. }, {});
  11158. }
  11159. getSuggestions(inputStr) {
  11160. const cursorPosition = this.inputEl.selectionStart;
  11161. const inputBeforeCursor = inputStr.substr(0, cursorPosition);
  11162. const lastBackslashPos = inputBeforeCursor.lastIndexOf("\\");
  11163. const commandText = inputBeforeCursor.substr(lastBackslashPos);
  11164. const match = LATEX_REGEX.exec(commandText);
  11165. let suggestions = [];
  11166. if (match) {
  11167. this.lastInput = match[1];
  11168. suggestions = this.symbols.filter(val => val.toLowerCase().contains(this.lastInput));
  11169. }
  11170. const fuse = new Fuse(suggestions, { findAllMatches: true, threshold: 0.8 });
  11171. const searchResults = fuse.search(this.lastInput);
  11172. return searchResults.map(value => value.item);
  11173. }
  11174. renderSuggestion(item, el) {
  11175. if (item) {
  11176. el.setText(item);
  11177. el.append(this.elementsRendered[item]);
  11178. }
  11179. }
  11180. selectSuggestion(item) {
  11181. const cursorPosition = this.inputEl.selectionStart;
  11182. const lastInputLength = this.lastInput.length;
  11183. const currentInputValue = this.inputEl.value;
  11184. let insertedEndPosition = 0;
  11185. const textToInsert = item.replace(/\\\\/g, "\\");
  11186. this.inputEl.value = `${currentInputValue.substr(0, cursorPosition - lastInputLength - 1)}${textToInsert}${currentInputValue.substr(cursorPosition)}`;
  11187. insertedEndPosition = cursorPosition - lastInputLength + item.length - 1;
  11188. this.inputEl.trigger("input");
  11189. this.close();
  11190. if (item.contains(LATEX_CURSOR_MOVE_HERE)) {
  11191. const cursorPos = this.inputEl.value.indexOf(LATEX_CURSOR_MOVE_HERE);
  11192. this.inputEl.value = this.inputEl.value.replace(LATEX_CURSOR_MOVE_HERE, "");
  11193. this.inputEl.setSelectionRange(cursorPos, cursorPos);
  11194. }
  11195. else {
  11196. this.inputEl.setSelectionRange(insertedEndPosition, insertedEndPosition);
  11197. }
  11198. }
  11199. }
  11200. class MathModal extends obsidian.Modal {
  11201. constructor() {
  11202. super(QuickAdd.instance.app);
  11203. this.didSubmit = false;
  11204. this.keybindListener = (evt) => {
  11205. if (evt.ctrlKey && evt.key === "Enter") {
  11206. this.submit();
  11207. }
  11208. if (evt.key === "Tab") {
  11209. evt.preventDefault();
  11210. this.cursorToGoTo();
  11211. }
  11212. };
  11213. this.submitClickCallback = (evt) => this.submit();
  11214. this.cancelClickCallback = (evt) => this.cancel();
  11215. this.open();
  11216. this.display();
  11217. this.waitForClose = new Promise((resolve, reject) => {
  11218. this.resolvePromise = resolve;
  11219. this.rejectPromise = reject;
  11220. });
  11221. new LaTeXSuggester(this.inputEl);
  11222. this.inputEl.focus();
  11223. this.inputEl.select();
  11224. }
  11225. static Prompt() {
  11226. return new MathModal().waitForClose;
  11227. }
  11228. display() {
  11229. this.containerEl.addClass('quickAddModal', 'qaMathModal');
  11230. this.contentEl.empty();
  11231. const mathDiv = this.contentEl.createDiv();
  11232. mathDiv.className = "math math-block is-loaded";
  11233. const tc = new obsidian.TextAreaComponent(this.contentEl);
  11234. tc.inputEl.style.width = "100%";
  11235. tc.inputEl.style.height = "10rem";
  11236. this.inputEl = tc.inputEl;
  11237. tc.onChange(obsidian.debounce(async (value) => await this.mathjaxLoop(mathDiv, value), 50));
  11238. tc.inputEl.addEventListener('keydown', this.keybindListener);
  11239. this.createButtonBar(this.contentEl.createDiv());
  11240. }
  11241. async onOpen() {
  11242. super.onOpen();
  11243. await obsidian.loadMathJax();
  11244. }
  11245. async mathjaxLoop(container, value) {
  11246. const html = obsidian.renderMath(value, true);
  11247. await obsidian.finishRenderMath();
  11248. container.empty();
  11249. container.append(html);
  11250. }
  11251. cursorToGoTo() {
  11252. if (this.inputEl.value.contains(LATEX_CURSOR_MOVE_HERE)) {
  11253. const cursorPos = this.inputEl.value.indexOf(LATEX_CURSOR_MOVE_HERE);
  11254. this.inputEl.value = this.inputEl.value.replace(LATEX_CURSOR_MOVE_HERE, "");
  11255. this.inputEl.setSelectionRange(cursorPos, cursorPos);
  11256. }
  11257. }
  11258. createButton(container, text, callback) {
  11259. const btn = new obsidian.ButtonComponent(container);
  11260. btn.setButtonText(text)
  11261. .onClick(callback);
  11262. return btn;
  11263. }
  11264. createButtonBar(mainContentContainer) {
  11265. const buttonBarContainer = mainContentContainer.createDiv();
  11266. this.createButton(buttonBarContainer, "Ok", this.submitClickCallback)
  11267. .setCta().buttonEl.style.marginRight = '0';
  11268. this.createButton(buttonBarContainer, "Cancel", this.cancelClickCallback);
  11269. buttonBarContainer.style.display = 'flex';
  11270. buttonBarContainer.style.flexDirection = 'row-reverse';
  11271. buttonBarContainer.style.justifyContent = 'flex-start';
  11272. buttonBarContainer.style.marginTop = '1rem';
  11273. }
  11274. removeInputListeners() {
  11275. this.inputEl.removeEventListener('keydown', this.keybindListener);
  11276. }
  11277. resolveInput() {
  11278. const output = this.inputEl.value.replace("\\n", `\\\\n`).replace(new RegExp(LATEX_CURSOR_MOVE_HERE, "g"), '');
  11279. if (!this.didSubmit)
  11280. this.rejectPromise("No input given.");
  11281. else
  11282. this.resolvePromise(output);
  11283. }
  11284. submit() {
  11285. this.didSubmit = true;
  11286. this.close();
  11287. }
  11288. cancel() {
  11289. this.close();
  11290. }
  11291. onClose() {
  11292. super.onClose();
  11293. this.resolveInput();
  11294. this.removeInputListeners();
  11295. }
  11296. }
  11297. class InputPrompt {
  11298. factory() {
  11299. if (QuickAdd.instance.settings.inputPrompt === "multi-line") {
  11300. return GenericWideInputPrompt;
  11301. }
  11302. else {
  11303. return GenericInputPrompt;
  11304. }
  11305. }
  11306. }
  11307. class CompleteFormatter extends Formatter {
  11308. constructor(app, plugin, choiceExecutor) {
  11309. super();
  11310. this.app = app;
  11311. this.plugin = plugin;
  11312. this.choiceExecutor = choiceExecutor;
  11313. this.variables = choiceExecutor === null || choiceExecutor === void 0 ? void 0 : choiceExecutor.variables;
  11314. }
  11315. async format(input) {
  11316. let output = input;
  11317. output = await this.replaceInlineJavascriptInString(output);
  11318. output = await this.replaceMacrosInString(output);
  11319. output = await this.replaceTemplateInString(output);
  11320. output = this.replaceDateInString(output);
  11321. output = await this.replaceValueInString(output);
  11322. output = await this.replaceDateVariableInString(output);
  11323. output = await this.replaceVariableInString(output);
  11324. output = await this.replaceMathValueInString(output);
  11325. return output;
  11326. }
  11327. async formatFileName(input, valueHeader) {
  11328. this.valueHeader = valueHeader;
  11329. return await this.format(input);
  11330. }
  11331. async formatFileContent(input) {
  11332. let output = input;
  11333. output = await this.format(output);
  11334. output = await this.replaceLinkToCurrentFileInString(output);
  11335. return output;
  11336. }
  11337. async formatFolderPath(folderName) {
  11338. return await this.format(folderName);
  11339. }
  11340. getCurrentFileLink() {
  11341. const currentFile = this.app.workspace.getActiveFile();
  11342. if (!currentFile)
  11343. return null;
  11344. return this.app.fileManager.generateMarkdownLink(currentFile, '');
  11345. }
  11346. getNaturalLanguageDates() {
  11347. return getNaturalLanguageDates(this.app);
  11348. }
  11349. getVariableValue(variableName) {
  11350. return this.variables.get(variableName);
  11351. }
  11352. async promptForValue(header) {
  11353. var _a;
  11354. if (!this.value) {
  11355. const selectedText = await this.getSelectedText();
  11356. this.value = selectedText ? selectedText :
  11357. await new InputPrompt().factory().Prompt(this.app, (_a = this.valueHeader) !== null && _a !== void 0 ? _a : `Enter value`);
  11358. }
  11359. return this.value;
  11360. }
  11361. async promptForVariable(header) {
  11362. return await new InputPrompt().factory().Prompt(this.app, header);
  11363. }
  11364. async promptForMathValue() {
  11365. return await MathModal.Prompt();
  11366. }
  11367. async suggestForValue(suggestedValues) {
  11368. return await GenericSuggester.Suggest(this.app, suggestedValues, suggestedValues);
  11369. }
  11370. async getMacroValue(macroName) {
  11371. var _a;
  11372. const macroEngine = new SingleMacroEngine(this.app, this.plugin, this.plugin.settings.macros, this.choiceExecutor, this.variables);
  11373. const macroOutput = (_a = await macroEngine.runAndGetOutput(macroName)) !== null && _a !== void 0 ? _a : "";
  11374. Object.keys(macroEngine.params.variables).forEach(key => {
  11375. this.variables.set(key, macroEngine.params.variables[key]);
  11376. });
  11377. return macroOutput;
  11378. }
  11379. async getTemplateContent(templatePath) {
  11380. return await new SingleTemplateEngine(this.app, this.plugin, templatePath, this.choiceExecutor).run();
  11381. }
  11382. async getSelectedText() {
  11383. const activeView = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView);
  11384. if (!activeView)
  11385. return;
  11386. return activeView.editor.getSelection();
  11387. }
  11388. async replaceInlineJavascriptInString(input) {
  11389. var _a;
  11390. let output = input;
  11391. while (INLINE_JAVASCRIPT_REGEX.test(output)) {
  11392. const match = INLINE_JAVASCRIPT_REGEX.exec(output);
  11393. const code = (_a = match[1]) === null || _a === void 0 ? void 0 : _a.trim();
  11394. if (code) {
  11395. const executor = new SingleInlineScriptEngine(this.app, this.plugin, this.choiceExecutor, this.variables);
  11396. const outVal = await executor.runAndGetOutput(code);
  11397. for (let key in executor.params.variables) {
  11398. this.variables.set(key, executor.params.variables[key]);
  11399. }
  11400. output = typeof outVal === "string" ?
  11401. this.replacer(output, INLINE_JAVASCRIPT_REGEX, outVal) :
  11402. this.replacer(output, INLINE_JAVASCRIPT_REGEX, "");
  11403. }
  11404. }
  11405. return output;
  11406. }
  11407. }
  11408. class TemplateEngine extends QuickAddEngine {
  11409. constructor(app, plugin, choiceFormatter) {
  11410. super(app);
  11411. this.plugin = plugin;
  11412. this.templater = getTemplater(app);
  11413. this.formatter = new CompleteFormatter(app, plugin, choiceFormatter);
  11414. }
  11415. async getOrCreateFolder(folders) {
  11416. let folderPath;
  11417. if (folders.length > 1) {
  11418. folderPath = await GenericSuggester.Suggest(this.app, folders, folders);
  11419. if (!folderPath)
  11420. return null;
  11421. }
  11422. else {
  11423. folderPath = folders[0];
  11424. }
  11425. if (folderPath)
  11426. await this.createFolder(folderPath);
  11427. else
  11428. folderPath = "";
  11429. return folderPath;
  11430. }
  11431. async getFormattedFilePath(folderPath, format, promptHeader) {
  11432. const formattedName = await this.formatter.formatFileName(format, promptHeader);
  11433. return this.formatFilePath(folderPath, formattedName);
  11434. }
  11435. async incrementFileName(fileName) {
  11436. const numStr = FILE_NUMBER_REGEX.exec(fileName)[1];
  11437. const fileExists = await this.app.vault.adapter.exists(fileName);
  11438. let newFileName = fileName;
  11439. if (fileExists && numStr) {
  11440. const number = parseInt(numStr);
  11441. if (!number)
  11442. throw new Error("detected numbers but couldn't get them.");
  11443. newFileName = newFileName.replace(FILE_NUMBER_REGEX, `${number + 1}.md`);
  11444. }
  11445. else if (fileExists) {
  11446. newFileName = newFileName.replace(FILE_NUMBER_REGEX, `${1}.md`);
  11447. }
  11448. const newFileExists = await this.app.vault.adapter.exists(newFileName);
  11449. if (newFileExists)
  11450. newFileName = await this.incrementFileName(newFileName);
  11451. return newFileName;
  11452. }
  11453. async createFileWithTemplate(filePath, templatePath) {
  11454. try {
  11455. const templateContent = await this.getTemplateContent(templatePath);
  11456. const formattedTemplateContent = await this.formatter.formatFileContent(templateContent);
  11457. const createdFile = await this.createFileWithInput(filePath, formattedTemplateContent);
  11458. await replaceTemplaterTemplatesInCreatedFile(this.app, createdFile);
  11459. return createdFile;
  11460. }
  11461. catch (e) {
  11462. log.logError(`Could not create file with template. Maybe '${templatePath}' is an invalid template path?`);
  11463. return null;
  11464. }
  11465. }
  11466. async overwriteFileWithTemplate(file, templatePath) {
  11467. try {
  11468. const templateContent = await this.getTemplateContent(templatePath);
  11469. const formattedTemplateContent = await this.formatter.formatFileContent(templateContent);
  11470. await this.app.vault.modify(file, formattedTemplateContent);
  11471. await replaceTemplaterTemplatesInCreatedFile(this.app, file, true);
  11472. return file;
  11473. }
  11474. catch (e) {
  11475. log.logError(e);
  11476. return null;
  11477. }
  11478. }
  11479. async appendToFileWithTemplate(file, templatePath, section) {
  11480. try {
  11481. const templateContent = await this.getTemplateContent(templatePath);
  11482. const formattedTemplateContent = await this.formatter.formatFileContent(templateContent);
  11483. const fileContent = await this.app.vault.cachedRead(file);
  11484. const newFileContent = section === "top" ?
  11485. `${formattedTemplateContent}\n${fileContent}` :
  11486. `${fileContent}\n${formattedTemplateContent}`;
  11487. await this.app.vault.modify(file, newFileContent);
  11488. await replaceTemplaterTemplatesInCreatedFile(this.app, file, true);
  11489. return file;
  11490. }
  11491. catch (e) {
  11492. log.logError(e);
  11493. return null;
  11494. }
  11495. }
  11496. async getTemplateContent(templatePath) {
  11497. let correctTemplatePath = templatePath;
  11498. if (!MARKDOWN_FILE_EXTENSION_REGEX.test(templatePath))
  11499. correctTemplatePath += ".md";
  11500. const templateFile = this.app.vault.getAbstractFileByPath(correctTemplatePath);
  11501. if (!(templateFile instanceof obsidian.TFile))
  11502. return;
  11503. return await this.app.vault.cachedRead(templateFile);
  11504. }
  11505. }
  11506. class SingleTemplateEngine extends TemplateEngine {
  11507. constructor(app, plugin, templatePath, choiceExecutor) {
  11508. super(app, plugin, choiceExecutor);
  11509. this.templatePath = templatePath;
  11510. }
  11511. async run() {
  11512. let templateContent = await this.getTemplateContent(this.templatePath);
  11513. if (!templateContent) {
  11514. log.logError(`Template ${this.templatePath} not found.`);
  11515. }
  11516. templateContent = await this.formatter.formatFileContent(templateContent);
  11517. return templateContent;
  11518. }
  11519. }
  11520. class FormatDisplayFormatter extends Formatter {
  11521. constructor(app, plugin) {
  11522. super();
  11523. this.app = app;
  11524. this.plugin = plugin;
  11525. }
  11526. async format(input) {
  11527. let output = input;
  11528. output = this.replaceDateInString(output);
  11529. output = await this.replaceValueInString(output);
  11530. output = await this.replaceDateVariableInString(output);
  11531. output = await this.replaceVariableInString(output);
  11532. output = await this.replaceLinkToCurrentFileInString(output);
  11533. output = await this.replaceMacrosInString(output);
  11534. output = await this.replaceTemplateInString(output);
  11535. output = this.replaceLinebreakInString(output);
  11536. return output;
  11537. }
  11538. promptForValue(header) {
  11539. return "_value_";
  11540. }
  11541. getVariableValue(variableName) {
  11542. return variableName;
  11543. }
  11544. getCurrentFileLink() {
  11545. var _a, _b;
  11546. return (_b = (_a = this.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : "_noPageOpen_";
  11547. }
  11548. getNaturalLanguageDates() {
  11549. return getNaturalLanguageDates(this.app);
  11550. }
  11551. suggestForValue(suggestedValues) {
  11552. return "_suggest_";
  11553. }
  11554. getMacroValue(macroName) {
  11555. return `_macro: ${macroName}_`;
  11556. }
  11557. promptForMathValue() {
  11558. return Promise.resolve("_math_");
  11559. }
  11560. promptForVariable(variableName) {
  11561. return Promise.resolve(`${variableName}_`);
  11562. }
  11563. async getTemplateContent(templatePath) {
  11564. try {
  11565. return await new SingleTemplateEngine(this.app, this.plugin, templatePath, null).run();
  11566. }
  11567. catch (e) {
  11568. return `Template (not found): ${templatePath}`;
  11569. }
  11570. }
  11571. async getSelectedText() {
  11572. return "_selected_";
  11573. }
  11574. }
  11575. class CaptureChoiceBuilder extends ChoiceBuilder {
  11576. constructor(app, choice, plugin) {
  11577. super(app);
  11578. this.plugin = plugin;
  11579. this.choice = choice;
  11580. this.display();
  11581. }
  11582. display() {
  11583. var _a, _b, _c;
  11584. this.containerEl.addClass("captureChoiceBuilder");
  11585. this.contentEl.empty();
  11586. this.addCenteredChoiceNameHeader(this.choice);
  11587. this.addCapturedToSetting();
  11588. if (!((_a = this.choice) === null || _a === void 0 ? void 0 : _a.captureToActiveFile)) {
  11589. this.addCreateIfNotExistsSetting();
  11590. if ((_c = (_b = this.choice) === null || _b === void 0 ? void 0 : _b.createFileIfItDoesntExist) === null || _c === void 0 ? void 0 : _c.enabled)
  11591. this.addCreateWithTemplateSetting();
  11592. }
  11593. this.addTaskSetting();
  11594. this.addPrependSetting();
  11595. if (!this.choice.captureToActiveFile) {
  11596. this.addAppendLinkSetting();
  11597. this.addInsertAfterSetting();
  11598. this.addOpenFileSetting();
  11599. if (this.choice.openFile)
  11600. this.addOpenFileInNewTabSetting();
  11601. }
  11602. this.addFormatSetting();
  11603. }
  11604. addCapturedToSetting() {
  11605. var _a, _b, _c;
  11606. let textField;
  11607. new obsidian.Setting(this.contentEl)
  11608. .setName('Capture To')
  11609. .setDesc('File to capture to. Supports some format syntax.');
  11610. const captureToContainer = this.contentEl.createDiv('captureToContainer');
  11611. const captureToActiveFileContainer = captureToContainer.createDiv('captureToActiveFileContainer');
  11612. const captureToActiveFileText = captureToActiveFileContainer.createEl('span');
  11613. captureToActiveFileText.textContent = "Capture to active file";
  11614. const captureToActiveFileToggle = new obsidian.ToggleComponent(captureToActiveFileContainer);
  11615. captureToActiveFileToggle.setValue((_a = this.choice) === null || _a === void 0 ? void 0 : _a.captureToActiveFile);
  11616. captureToActiveFileToggle.onChange(value => {
  11617. this.choice.captureToActiveFile = value;
  11618. this.reload();
  11619. });
  11620. if (!((_b = this.choice) === null || _b === void 0 ? void 0 : _b.captureToActiveFile)) {
  11621. const captureToFileContainer = captureToContainer.createDiv('captureToFileContainer');
  11622. const formatDisplay = captureToFileContainer.createEl('span');
  11623. const displayFormatter = new FileNameDisplayFormatter(this.app);
  11624. (async () => formatDisplay.textContent = await displayFormatter.format(this.choice.captureTo))();
  11625. const formatInput = new obsidian.TextComponent(captureToFileContainer);
  11626. formatInput.setPlaceholder("File name format");
  11627. textField = formatInput;
  11628. formatInput.inputEl.style.width = "100%";
  11629. formatInput.inputEl.style.marginBottom = "8px";
  11630. formatInput.setValue(this.choice.captureTo)
  11631. .setDisabled((_c = this.choice) === null || _c === void 0 ? void 0 : _c.captureToActiveFile)
  11632. .onChange(async (value) => {
  11633. this.choice.captureTo = value;
  11634. formatDisplay.textContent = await displayFormatter.format(value);
  11635. });
  11636. const markdownFilesAndFormatSyntax = [...this.app.vault.getMarkdownFiles().map(f => f.path), ...FILE_NAME_FORMAT_SYNTAX];
  11637. new GenericTextSuggester(this.app, textField.inputEl, markdownFilesAndFormatSyntax);
  11638. }
  11639. }
  11640. addPrependSetting() {
  11641. var _a;
  11642. const prependSetting = new obsidian.Setting(this.contentEl);
  11643. prependSetting.setName("Write to bottom of file")
  11644. .setDesc(`Put value at the bottom of the file - otherwise at the ${((_a = this.choice) === null || _a === void 0 ? void 0 : _a.captureToActiveFile) ? "active cursor location" : "top"}.`)
  11645. .addToggle(toggle => {
  11646. toggle.setValue(this.choice.prepend);
  11647. toggle.onChange(value => this.choice.prepend = value);
  11648. });
  11649. }
  11650. addTaskSetting() {
  11651. const taskSetting = new obsidian.Setting(this.contentEl);
  11652. taskSetting.setName("Task")
  11653. .setDesc("Formats the value as a task.")
  11654. .addToggle(toggle => {
  11655. toggle.setValue(this.choice.task);
  11656. toggle.onChange(value => this.choice.task = value);
  11657. });
  11658. }
  11659. addAppendLinkSetting() {
  11660. const appendLinkSetting = new obsidian.Setting(this.contentEl);
  11661. appendLinkSetting.setName("Append link")
  11662. .setDesc("Add a link on your current cursor position, linking to the file you're capturing to.")
  11663. .addToggle(toggle => {
  11664. toggle.setValue(this.choice.appendLink);
  11665. toggle.onChange(value => this.choice.appendLink = value);
  11666. });
  11667. }
  11668. addInsertAfterSetting() {
  11669. let insertAfterInput;
  11670. const insertAfterSetting = new obsidian.Setting(this.contentEl);
  11671. insertAfterSetting.setName("Insert after")
  11672. .setDesc("Insert capture after specified line. Accepts format syntax.")
  11673. .addToggle(toggle => {
  11674. toggle.setValue(this.choice.insertAfter.enabled);
  11675. toggle.onChange(value => {
  11676. this.choice.insertAfter.enabled = value;
  11677. insertAfterInput.setDisabled(!value);
  11678. this.reload();
  11679. });
  11680. });
  11681. const insertAfterFormatDisplay = this.contentEl.createEl('span');
  11682. const displayFormatter = new FormatDisplayFormatter(this.app, this.plugin);
  11683. (async () => insertAfterFormatDisplay.innerText = await displayFormatter.format(this.choice.insertAfter.after))();
  11684. insertAfterInput = new obsidian.TextComponent(this.contentEl);
  11685. insertAfterInput.setPlaceholder("Insert after");
  11686. insertAfterInput.inputEl.style.width = "100%";
  11687. insertAfterInput.inputEl.style.marginBottom = "8px";
  11688. insertAfterInput.setValue(this.choice.insertAfter.after)
  11689. .setDisabled(!this.choice.insertAfter.enabled)
  11690. .onChange(async (value) => {
  11691. this.choice.insertAfter.after = value;
  11692. insertAfterFormatDisplay.innerText = await displayFormatter.format(value);
  11693. });
  11694. new FormatSyntaxSuggester(this.app, insertAfterInput.inputEl, this.plugin);
  11695. if (this.choice.insertAfter.enabled) {
  11696. const insertAtEndSetting = new obsidian.Setting(this.contentEl);
  11697. insertAtEndSetting.setName("Insert at end of section")
  11698. .setDesc("Insert the text at the end of the section, rather than at the top.")
  11699. .addToggle(toggle => {
  11700. var _a;
  11701. return toggle
  11702. .setValue((_a = this.choice.insertAfter) === null || _a === void 0 ? void 0 : _a.insertAtEnd)
  11703. .onChange(value => this.choice.insertAfter.insertAtEnd = value);
  11704. });
  11705. const createLineIfNotFound = new obsidian.Setting(this.contentEl);
  11706. createLineIfNotFound.setName("Create line if not found")
  11707. .setDesc("Creates the 'insert after' line if it is not found.")
  11708. .addToggle(toggle => {
  11709. var _a, _b;
  11710. if (!((_a = this.choice.insertAfter) === null || _a === void 0 ? void 0 : _a.createIfNotFound))
  11711. this.choice.insertAfter.createIfNotFound = false; // Set to default
  11712. toggle
  11713. .setValue((_b = this.choice.insertAfter) === null || _b === void 0 ? void 0 : _b.createIfNotFound)
  11714. .onChange(value => this.choice.insertAfter.createIfNotFound = value)
  11715. .toggleEl.style.marginRight = "1em";
  11716. })
  11717. .addDropdown(dropdown => {
  11718. var _a, _b;
  11719. if (!((_a = this.choice.insertAfter) === null || _a === void 0 ? void 0 : _a.createIfNotFoundLocation))
  11720. this.choice.insertAfter.createIfNotFoundLocation = CREATE_IF_NOT_FOUND_TOP; // Set to default
  11721. dropdown
  11722. .addOption(CREATE_IF_NOT_FOUND_TOP, "Top")
  11723. .addOption(CREATE_IF_NOT_FOUND_BOTTOM, "Bottom")
  11724. .setValue((_b = this.choice.insertAfter) === null || _b === void 0 ? void 0 : _b.createIfNotFoundLocation)
  11725. .onChange(value => this.choice.insertAfter.createIfNotFoundLocation = value);
  11726. });
  11727. }
  11728. }
  11729. addFormatSetting() {
  11730. let textField;
  11731. const enableSetting = new obsidian.Setting(this.contentEl);
  11732. enableSetting.setName("Capture format")
  11733. .setDesc("Set the format of the capture.")
  11734. .addToggle(toggleComponent => {
  11735. toggleComponent.setValue(this.choice.format.enabled)
  11736. .onChange(value => {
  11737. this.choice.format.enabled = value;
  11738. textField.setDisabled(!value);
  11739. });
  11740. });
  11741. const formatInput = new obsidian.TextAreaComponent(this.contentEl);
  11742. formatInput.setPlaceholder("Format");
  11743. textField = formatInput;
  11744. formatInput.inputEl.style.width = "100%";
  11745. formatInput.inputEl.style.marginBottom = "8px";
  11746. formatInput.inputEl.style.height = "10rem";
  11747. formatInput.setValue(this.choice.format.format)
  11748. .setDisabled(!this.choice.format.enabled)
  11749. .onChange(async (value) => {
  11750. this.choice.format.format = value;
  11751. formatDisplay.innerText = await displayFormatter.format(value);
  11752. });
  11753. new FormatSyntaxSuggester(this.app, textField.inputEl, this.plugin);
  11754. const formatDisplay = this.contentEl.createEl('span');
  11755. const displayFormatter = new FormatDisplayFormatter(this.app, this.plugin);
  11756. (async () => formatDisplay.innerText = await displayFormatter.format(this.choice.format.format))();
  11757. }
  11758. addCreateIfNotExistsSetting() {
  11759. if (!this.choice.createFileIfItDoesntExist)
  11760. this.choice.createFileIfItDoesntExist = { enabled: false, createWithTemplate: false, template: "" };
  11761. const createFileIfItDoesntExist = new obsidian.Setting(this.contentEl);
  11762. createFileIfItDoesntExist
  11763. .setName("Create file if it doesn't exist")
  11764. .addToggle(toggle => {
  11765. var _a, _b;
  11766. return toggle
  11767. .setValue((_b = (_a = this.choice) === null || _a === void 0 ? void 0 : _a.createFileIfItDoesntExist) === null || _b === void 0 ? void 0 : _b.enabled)
  11768. .setTooltip("Create file if it doesn't exist")
  11769. .onChange(value => {
  11770. this.choice.createFileIfItDoesntExist.enabled = value;
  11771. this.reload();
  11772. });
  11773. });
  11774. }
  11775. addCreateWithTemplateSetting() {
  11776. var _a, _b, _c, _d, _e;
  11777. let templateSelector;
  11778. const createWithTemplateSetting = new obsidian.Setting(this.contentEl);
  11779. createWithTemplateSetting.setName("Create file with given template.")
  11780. .addToggle(toggle => {
  11781. var _a;
  11782. return toggle.setValue((_a = this.choice.createFileIfItDoesntExist) === null || _a === void 0 ? void 0 : _a.createWithTemplate)
  11783. .onChange(value => {
  11784. this.choice.createFileIfItDoesntExist.createWithTemplate = value;
  11785. templateSelector.setDisabled(!value);
  11786. });
  11787. });
  11788. templateSelector = new obsidian.TextComponent(this.contentEl);
  11789. templateSelector.setValue((_c = (_b = (_a = this.choice) === null || _a === void 0 ? void 0 : _a.createFileIfItDoesntExist) === null || _b === void 0 ? void 0 : _b.template) !== null && _c !== void 0 ? _c : "")
  11790. .setPlaceholder("Template path")
  11791. .setDisabled(!((_e = (_d = this.choice) === null || _d === void 0 ? void 0 : _d.createFileIfItDoesntExist) === null || _e === void 0 ? void 0 : _e.createWithTemplate));
  11792. templateSelector.inputEl.style.width = "100%";
  11793. templateSelector.inputEl.style.marginBottom = "8px";
  11794. const markdownFiles = getTemplatePaths(this.app);
  11795. new GenericTextSuggester(this.app, templateSelector.inputEl, markdownFiles);
  11796. templateSelector.onChange(value => {
  11797. this.choice.createFileIfItDoesntExist.template = value;
  11798. });
  11799. }
  11800. addOpenFileSetting() {
  11801. const noOpenSetting = new obsidian.Setting(this.contentEl);
  11802. noOpenSetting.setName("Open")
  11803. .setDesc("Open the file that is captured to.")
  11804. .addToggle(toggle => {
  11805. toggle.setValue(this.choice.openFile);
  11806. toggle.onChange(value => {
  11807. this.choice.openFile = value;
  11808. this.reload();
  11809. });
  11810. })
  11811. .addDropdown(dropdown => {
  11812. dropdown.selectEl.style.marginLeft = "10px";
  11813. if (!this.choice.openFileInMode)
  11814. this.choice.openFileInMode = 'default';
  11815. dropdown
  11816. .addOption('source', 'Source')
  11817. .addOption('preview', 'Preview')
  11818. .addOption('default', 'Default')
  11819. .setValue(this.choice.openFileInMode)
  11820. .onChange(value => this.choice.openFileInMode = value);
  11821. });
  11822. }
  11823. addOpenFileInNewTabSetting() {
  11824. const newTabSetting = new obsidian.Setting(this.contentEl);
  11825. newTabSetting.setName("New Tab")
  11826. .setDesc("Open the file that is captured to in a new tab.")
  11827. .addToggle(toggle => {
  11828. var _a, _b;
  11829. toggle.setValue((_b = (_a = this.choice) === null || _a === void 0 ? void 0 : _a.openFileInNewTab) === null || _b === void 0 ? void 0 : _b.enabled);
  11830. toggle.onChange(value => this.choice.openFileInNewTab.enabled = value);
  11831. })
  11832. .addDropdown(dropdown => {
  11833. var _a, _b, _c;
  11834. if (!((_a = this.choice) === null || _a === void 0 ? void 0 : _a.openFileInNewTab)) {
  11835. this.choice.openFileInNewTab = { enabled: false, direction: NewTabDirection.vertical, focus: true };
  11836. }
  11837. dropdown.selectEl.style.marginLeft = "10px";
  11838. dropdown.addOption(NewTabDirection.vertical, "Vertical");
  11839. dropdown.addOption(NewTabDirection.horizontal, "Horizontal");
  11840. dropdown.setValue((_c = (_b = this.choice) === null || _b === void 0 ? void 0 : _b.openFileInNewTab) === null || _c === void 0 ? void 0 : _c.direction);
  11841. dropdown.onChange(value => this.choice.openFileInNewTab.direction = value);
  11842. });
  11843. new obsidian.Setting(this.contentEl)
  11844. .setName("Focus new pane")
  11845. .setDesc("Focus the opened tab immediately")
  11846. .addToggle(toggle => toggle
  11847. .setValue(this.choice.openFileInNewTab.focus)
  11848. .onChange(value => this.choice.openFileInNewTab.focus = value));
  11849. }
  11850. }
  11851. class MacroChoiceBuilder extends ChoiceBuilder {
  11852. constructor(app, choice, macros) {
  11853. super(app);
  11854. this.macros = macros;
  11855. this.choice = choice;
  11856. this.display();
  11857. }
  11858. display() {
  11859. this.containerEl.addClass("macroChoiceBuilder");
  11860. this.addCenteredChoiceNameHeader(this.choice);
  11861. this.addSelectMacroSearch();
  11862. }
  11863. addSelectMacroSearch() {
  11864. const selectMacroDropdownContainer = this.contentEl.createDiv('selectMacroDropdownContainer');
  11865. const dropdown = new obsidian.DropdownComponent(selectMacroDropdownContainer);
  11866. let macroOptions = {};
  11867. this.macros.forEach(macro => {
  11868. macroOptions[macro.name] = macro.name;
  11869. });
  11870. dropdown.addOptions(macroOptions);
  11871. dropdown.onChange(value => {
  11872. this.selectMacro(value);
  11873. });
  11874. const selectedMacro = this.macros.find(m => m.id === this.choice.macroId);
  11875. if (selectedMacro) {
  11876. dropdown.setValue(selectedMacro.name);
  11877. }
  11878. else {
  11879. const value = dropdown.getValue();
  11880. if (value) {
  11881. this.selectMacro(value);
  11882. }
  11883. }
  11884. }
  11885. selectMacro(value) {
  11886. const targetMacro = this.macros.find(m => m.name === value);
  11887. if (!targetMacro)
  11888. return;
  11889. this.choice.macroId = targetMacro.id;
  11890. }
  11891. }
  11892. class UserScript extends Command {
  11893. constructor(name, path) {
  11894. super(name, CommandType.UserScript);
  11895. this.path = path;
  11896. this.settings = {};
  11897. }
  11898. }
  11899. class ObsidianCommand extends Command {
  11900. constructor(name, commandId) {
  11901. super(name, CommandType.Obsidian);
  11902. this.generateId = () => this.id = v4();
  11903. this.commandId = commandId;
  11904. }
  11905. }
  11906. /* src/gui/MacroGUIs/Components/StandardCommand.svelte generated by Svelte v3.47.0 */
  11907. function create_fragment$5(ctx) {
  11908. let div1;
  11909. let li;
  11910. let t0_value = /*command*/ ctx[0].name + "";
  11911. let t0;
  11912. let t1;
  11913. let div0;
  11914. let span0;
  11915. let icon0;
  11916. let t2;
  11917. let span1;
  11918. let icon1;
  11919. let span1_style_value;
  11920. let span1_tabindex_value;
  11921. let current;
  11922. let mounted;
  11923. let dispose;
  11924. icon0 = new Icon({ props: { data: faTrash } });
  11925. icon1 = new Icon({ props: { data: faBars } });
  11926. return {
  11927. c() {
  11928. div1 = element("div");
  11929. li = element("li");
  11930. t0 = text(t0_value);
  11931. t1 = space();
  11932. div0 = element("div");
  11933. span0 = element("span");
  11934. create_component(icon0.$$.fragment);
  11935. t2 = space();
  11936. span1 = element("span");
  11937. create_component(icon1.$$.fragment);
  11938. attr(span0, "class", "clickable");
  11939. attr(span1, "aria-label", "Drag-handle");
  11940. attr(span1, "style", span1_style_value = "" + ((/*dragDisabled*/ ctx[2]
  11941. ? 'cursor: grab'
  11942. : 'cursor: grabbing') + ";"));
  11943. attr(span1, "tabindex", span1_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1);
  11944. attr(div1, "class", "quickAddCommandListItem");
  11945. },
  11946. m(target, anchor) {
  11947. insert(target, div1, anchor);
  11948. append(div1, li);
  11949. append(li, t0);
  11950. append(div1, t1);
  11951. append(div1, div0);
  11952. append(div0, span0);
  11953. mount_component(icon0, span0, null);
  11954. append(div0, t2);
  11955. append(div0, span1);
  11956. mount_component(icon1, span1, null);
  11957. current = true;
  11958. if (!mounted) {
  11959. dispose = [
  11960. listen(span0, "click", /*click_handler*/ ctx[4]),
  11961. listen(span1, "mousedown", function () {
  11962. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  11963. }),
  11964. listen(span1, "touchstart", function () {
  11965. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  11966. })
  11967. ];
  11968. mounted = true;
  11969. }
  11970. },
  11971. p(new_ctx, [dirty]) {
  11972. ctx = new_ctx;
  11973. if ((!current || dirty & /*command*/ 1) && t0_value !== (t0_value = /*command*/ ctx[0].name + "")) set_data(t0, t0_value);
  11974. if (!current || dirty & /*dragDisabled*/ 4 && span1_style_value !== (span1_style_value = "" + ((/*dragDisabled*/ ctx[2]
  11975. ? 'cursor: grab'
  11976. : 'cursor: grabbing') + ";"))) {
  11977. attr(span1, "style", span1_style_value);
  11978. }
  11979. if (!current || dirty & /*dragDisabled*/ 4 && span1_tabindex_value !== (span1_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1)) {
  11980. attr(span1, "tabindex", span1_tabindex_value);
  11981. }
  11982. },
  11983. i(local) {
  11984. if (current) return;
  11985. transition_in(icon0.$$.fragment, local);
  11986. transition_in(icon1.$$.fragment, local);
  11987. current = true;
  11988. },
  11989. o(local) {
  11990. transition_out(icon0.$$.fragment, local);
  11991. transition_out(icon1.$$.fragment, local);
  11992. current = false;
  11993. },
  11994. d(detaching) {
  11995. if (detaching) detach(div1);
  11996. destroy_component(icon0);
  11997. destroy_component(icon1);
  11998. mounted = false;
  11999. run_all(dispose);
  12000. }
  12001. };
  12002. }
  12003. function instance$5($$self, $$props, $$invalidate) {
  12004. let { command } = $$props;
  12005. let { startDrag } = $$props;
  12006. let { dragDisabled } = $$props;
  12007. const dispatch = createEventDispatcher();
  12008. function deleteCommand(commandId) {
  12009. dispatch('deleteCommand', commandId);
  12010. }
  12011. const click_handler = () => deleteCommand(command.id);
  12012. $$self.$$set = $$props => {
  12013. if ('command' in $$props) $$invalidate(0, command = $$props.command);
  12014. if ('startDrag' in $$props) $$invalidate(1, startDrag = $$props.startDrag);
  12015. if ('dragDisabled' in $$props) $$invalidate(2, dragDisabled = $$props.dragDisabled);
  12016. };
  12017. return [command, startDrag, dragDisabled, deleteCommand, click_handler];
  12018. }
  12019. class StandardCommand extends SvelteComponent {
  12020. constructor(options) {
  12021. super();
  12022. init(this, options, instance$5, create_fragment$5, safe_not_equal, {
  12023. command: 0,
  12024. startDrag: 1,
  12025. dragDisabled: 2
  12026. });
  12027. }
  12028. }
  12029. /* src/gui/MacroGUIs/Components/WaitCommand.svelte generated by Svelte v3.47.0 */
  12030. function add_css$2(target) {
  12031. append_styles(target, "svelte-1196d9p", ".dotInput.svelte-1196d9p{border:none;display:inline;font-family:inherit;font-size:inherit;padding:0;width:0;text-decoration:underline dotted;background-color:transparent}.dotInput.svelte-1196d9p:hover{background-color:transparent}");
  12032. }
  12033. function create_fragment$4(ctx) {
  12034. let div1;
  12035. let li;
  12036. let t0_value = /*command*/ ctx[0].name + "";
  12037. let t0;
  12038. let t1;
  12039. let input;
  12040. let t2;
  12041. let t3;
  12042. let div0;
  12043. let span0;
  12044. let icon0;
  12045. let t4;
  12046. let span1;
  12047. let icon1;
  12048. let span1_style_value;
  12049. let span1_tabindex_value;
  12050. let current;
  12051. let mounted;
  12052. let dispose;
  12053. icon0 = new Icon({ props: { data: faTrash } });
  12054. icon1 = new Icon({ props: { data: faBars } });
  12055. return {
  12056. c() {
  12057. div1 = element("div");
  12058. li = element("li");
  12059. t0 = text(t0_value);
  12060. t1 = text(" for ");
  12061. input = element("input");
  12062. t2 = text("ms");
  12063. t3 = space();
  12064. div0 = element("div");
  12065. span0 = element("span");
  12066. create_component(icon0.$$.fragment);
  12067. t4 = space();
  12068. span1 = element("span");
  12069. create_component(icon1.$$.fragment);
  12070. attr(input, "type", "number");
  12071. attr(input, "placeholder", " ");
  12072. attr(input, "class", "dotInput svelte-1196d9p");
  12073. attr(span0, "class", "clickable");
  12074. attr(span1, "aria-label", "Drag-handle");
  12075. attr(span1, "style", span1_style_value = "" + ((/*dragDisabled*/ ctx[2]
  12076. ? 'cursor: grab'
  12077. : 'cursor: grabbing') + ";"));
  12078. attr(span1, "tabindex", span1_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1);
  12079. attr(div1, "class", "quickAddCommandListItem");
  12080. },
  12081. m(target, anchor) {
  12082. insert(target, div1, anchor);
  12083. append(div1, li);
  12084. append(li, t0);
  12085. append(li, t1);
  12086. append(li, input);
  12087. /*input_binding*/ ctx[6](input);
  12088. set_input_value(input, /*command*/ ctx[0].time);
  12089. append(li, t2);
  12090. append(div1, t3);
  12091. append(div1, div0);
  12092. append(div0, span0);
  12093. mount_component(icon0, span0, null);
  12094. append(div0, t4);
  12095. append(div0, span1);
  12096. mount_component(icon1, span1, null);
  12097. current = true;
  12098. if (!mounted) {
  12099. dispose = [
  12100. listen(input, "keyup", /*resizeInput*/ ctx[5]),
  12101. listen(input, "input", /*input_input_handler*/ ctx[7]),
  12102. listen(span0, "click", /*click_handler*/ ctx[8]),
  12103. listen(span1, "mousedown", function () {
  12104. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  12105. }),
  12106. listen(span1, "touchstart", function () {
  12107. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  12108. })
  12109. ];
  12110. mounted = true;
  12111. }
  12112. },
  12113. p(new_ctx, [dirty]) {
  12114. ctx = new_ctx;
  12115. if ((!current || dirty & /*command*/ 1) && t0_value !== (t0_value = /*command*/ ctx[0].name + "")) set_data(t0, t0_value);
  12116. if (dirty & /*command*/ 1 && to_number(input.value) !== /*command*/ ctx[0].time) {
  12117. set_input_value(input, /*command*/ ctx[0].time);
  12118. }
  12119. if (!current || dirty & /*dragDisabled*/ 4 && span1_style_value !== (span1_style_value = "" + ((/*dragDisabled*/ ctx[2]
  12120. ? 'cursor: grab'
  12121. : 'cursor: grabbing') + ";"))) {
  12122. attr(span1, "style", span1_style_value);
  12123. }
  12124. if (!current || dirty & /*dragDisabled*/ 4 && span1_tabindex_value !== (span1_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1)) {
  12125. attr(span1, "tabindex", span1_tabindex_value);
  12126. }
  12127. },
  12128. i(local) {
  12129. if (current) return;
  12130. transition_in(icon0.$$.fragment, local);
  12131. transition_in(icon1.$$.fragment, local);
  12132. current = true;
  12133. },
  12134. o(local) {
  12135. transition_out(icon0.$$.fragment, local);
  12136. transition_out(icon1.$$.fragment, local);
  12137. current = false;
  12138. },
  12139. d(detaching) {
  12140. if (detaching) detach(div1);
  12141. /*input_binding*/ ctx[6](null);
  12142. destroy_component(icon0);
  12143. destroy_component(icon1);
  12144. mounted = false;
  12145. run_all(dispose);
  12146. }
  12147. };
  12148. }
  12149. function instance$4($$self, $$props, $$invalidate) {
  12150. let { command } = $$props;
  12151. let { startDrag } = $$props;
  12152. let { dragDisabled } = $$props;
  12153. const dispatch = createEventDispatcher();
  12154. let inputEl;
  12155. function deleteCommand(commandId) {
  12156. dispatch('deleteCommand', commandId);
  12157. }
  12158. function resizeInput() {
  12159. const length = inputEl.value.length;
  12160. $$invalidate(3, inputEl.style.width = (length === 0 ? 2 : length) + 'ch', inputEl);
  12161. }
  12162. onMount(resizeInput);
  12163. function input_binding($$value) {
  12164. binding_callbacks[$$value ? 'unshift' : 'push'](() => {
  12165. inputEl = $$value;
  12166. $$invalidate(3, inputEl);
  12167. });
  12168. }
  12169. function input_input_handler() {
  12170. command.time = to_number(this.value);
  12171. $$invalidate(0, command);
  12172. }
  12173. const click_handler = () => deleteCommand(command.id);
  12174. $$self.$$set = $$props => {
  12175. if ('command' in $$props) $$invalidate(0, command = $$props.command);
  12176. if ('startDrag' in $$props) $$invalidate(1, startDrag = $$props.startDrag);
  12177. if ('dragDisabled' in $$props) $$invalidate(2, dragDisabled = $$props.dragDisabled);
  12178. };
  12179. return [
  12180. command,
  12181. startDrag,
  12182. dragDisabled,
  12183. inputEl,
  12184. deleteCommand,
  12185. resizeInput,
  12186. input_binding,
  12187. input_input_handler,
  12188. click_handler
  12189. ];
  12190. }
  12191. class WaitCommand$1 extends SvelteComponent {
  12192. constructor(options) {
  12193. super();
  12194. init(
  12195. this,
  12196. options,
  12197. instance$4,
  12198. create_fragment$4,
  12199. safe_not_equal,
  12200. {
  12201. command: 0,
  12202. startDrag: 1,
  12203. dragDisabled: 2
  12204. },
  12205. add_css$2
  12206. );
  12207. }
  12208. }
  12209. /* src/gui/MacroGUIs/Components/NestedChoiceCommand.svelte generated by Svelte v3.47.0 */
  12210. function create_fragment$3(ctx) {
  12211. let div1;
  12212. let li;
  12213. let t0_value = /*command*/ ctx[0].name + "";
  12214. let t0;
  12215. let t1;
  12216. let div0;
  12217. let span0;
  12218. let icon0;
  12219. let t2;
  12220. let span1;
  12221. let icon1;
  12222. let t3;
  12223. let span2;
  12224. let icon2;
  12225. let span2_style_value;
  12226. let span2_tabindex_value;
  12227. let current;
  12228. let mounted;
  12229. let dispose;
  12230. icon0 = new Icon({ props: { data: faCog } });
  12231. icon1 = new Icon({ props: { data: faTrash } });
  12232. icon2 = new Icon({ props: { data: faBars } });
  12233. return {
  12234. c() {
  12235. div1 = element("div");
  12236. li = element("li");
  12237. t0 = text(t0_value);
  12238. t1 = space();
  12239. div0 = element("div");
  12240. span0 = element("span");
  12241. create_component(icon0.$$.fragment);
  12242. t2 = space();
  12243. span1 = element("span");
  12244. create_component(icon1.$$.fragment);
  12245. t3 = space();
  12246. span2 = element("span");
  12247. create_component(icon2.$$.fragment);
  12248. attr(span0, "class", "clickable");
  12249. attr(span1, "class", "clickable");
  12250. attr(span2, "aria-label", "Drag-handle");
  12251. attr(span2, "style", span2_style_value = "" + ((/*dragDisabled*/ ctx[2]
  12252. ? 'cursor: grab'
  12253. : 'cursor: grabbing') + ";"));
  12254. attr(span2, "tabindex", span2_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1);
  12255. attr(div1, "class", "quickAddCommandListItem");
  12256. },
  12257. m(target, anchor) {
  12258. insert(target, div1, anchor);
  12259. append(div1, li);
  12260. append(li, t0);
  12261. append(div1, t1);
  12262. append(div1, div0);
  12263. append(div0, span0);
  12264. mount_component(icon0, span0, null);
  12265. append(div0, t2);
  12266. append(div0, span1);
  12267. mount_component(icon1, span1, null);
  12268. append(div0, t3);
  12269. append(div0, span2);
  12270. mount_component(icon2, span2, null);
  12271. current = true;
  12272. if (!mounted) {
  12273. dispose = [
  12274. listen(span0, "click", /*click_handler*/ ctx[5]),
  12275. listen(span1, "click", /*click_handler_1*/ ctx[6]),
  12276. listen(span2, "mousedown", function () {
  12277. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  12278. }),
  12279. listen(span2, "touchstart", function () {
  12280. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  12281. })
  12282. ];
  12283. mounted = true;
  12284. }
  12285. },
  12286. p(new_ctx, [dirty]) {
  12287. ctx = new_ctx;
  12288. if ((!current || dirty & /*command*/ 1) && t0_value !== (t0_value = /*command*/ ctx[0].name + "")) set_data(t0, t0_value);
  12289. if (!current || dirty & /*dragDisabled*/ 4 && span2_style_value !== (span2_style_value = "" + ((/*dragDisabled*/ ctx[2]
  12290. ? 'cursor: grab'
  12291. : 'cursor: grabbing') + ";"))) {
  12292. attr(span2, "style", span2_style_value);
  12293. }
  12294. if (!current || dirty & /*dragDisabled*/ 4 && span2_tabindex_value !== (span2_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1)) {
  12295. attr(span2, "tabindex", span2_tabindex_value);
  12296. }
  12297. },
  12298. i(local) {
  12299. if (current) return;
  12300. transition_in(icon0.$$.fragment, local);
  12301. transition_in(icon1.$$.fragment, local);
  12302. transition_in(icon2.$$.fragment, local);
  12303. current = true;
  12304. },
  12305. o(local) {
  12306. transition_out(icon0.$$.fragment, local);
  12307. transition_out(icon1.$$.fragment, local);
  12308. transition_out(icon2.$$.fragment, local);
  12309. current = false;
  12310. },
  12311. d(detaching) {
  12312. if (detaching) detach(div1);
  12313. destroy_component(icon0);
  12314. destroy_component(icon1);
  12315. destroy_component(icon2);
  12316. mounted = false;
  12317. run_all(dispose);
  12318. }
  12319. };
  12320. }
  12321. function instance$3($$self, $$props, $$invalidate) {
  12322. let { command } = $$props;
  12323. let { startDrag } = $$props;
  12324. let { dragDisabled } = $$props;
  12325. const dispatch = createEventDispatcher();
  12326. function deleteCommand() {
  12327. dispatch('deleteCommand', command.id);
  12328. }
  12329. function configureChoice() {
  12330. dispatch('configureChoice', command);
  12331. }
  12332. const click_handler = () => configureChoice();
  12333. const click_handler_1 = () => deleteCommand();
  12334. $$self.$$set = $$props => {
  12335. if ('command' in $$props) $$invalidate(0, command = $$props.command);
  12336. if ('startDrag' in $$props) $$invalidate(1, startDrag = $$props.startDrag);
  12337. if ('dragDisabled' in $$props) $$invalidate(2, dragDisabled = $$props.dragDisabled);
  12338. };
  12339. return [
  12340. command,
  12341. startDrag,
  12342. dragDisabled,
  12343. deleteCommand,
  12344. configureChoice,
  12345. click_handler,
  12346. click_handler_1
  12347. ];
  12348. }
  12349. class NestedChoiceCommand$1 extends SvelteComponent {
  12350. constructor(options) {
  12351. super();
  12352. init(this, options, instance$3, create_fragment$3, safe_not_equal, {
  12353. command: 0,
  12354. startDrag: 1,
  12355. dragDisabled: 2
  12356. });
  12357. }
  12358. }
  12359. /* src/gui/MacroGUIs/Components/UserScriptCommand.svelte generated by Svelte v3.47.0 */
  12360. function create_fragment$2(ctx) {
  12361. let div1;
  12362. let li;
  12363. let t0_value = /*command*/ ctx[0].name + "";
  12364. let t0;
  12365. let t1;
  12366. let div0;
  12367. let span0;
  12368. let icon0;
  12369. let t2;
  12370. let span1;
  12371. let icon1;
  12372. let t3;
  12373. let span2;
  12374. let icon2;
  12375. let span2_style_value;
  12376. let span2_tabindex_value;
  12377. let current;
  12378. let mounted;
  12379. let dispose;
  12380. icon0 = new Icon({ props: { data: faCog } });
  12381. icon1 = new Icon({ props: { data: faTrash } });
  12382. icon2 = new Icon({ props: { data: faBars } });
  12383. return {
  12384. c() {
  12385. div1 = element("div");
  12386. li = element("li");
  12387. t0 = text(t0_value);
  12388. t1 = space();
  12389. div0 = element("div");
  12390. span0 = element("span");
  12391. create_component(icon0.$$.fragment);
  12392. t2 = space();
  12393. span1 = element("span");
  12394. create_component(icon1.$$.fragment);
  12395. t3 = space();
  12396. span2 = element("span");
  12397. create_component(icon2.$$.fragment);
  12398. attr(span0, "class", "clickable");
  12399. attr(span1, "class", "clickable");
  12400. attr(span2, "aria-label", "Drag-handle");
  12401. attr(span2, "style", span2_style_value = "" + ((/*dragDisabled*/ ctx[2]
  12402. ? 'cursor: grab'
  12403. : 'cursor: grabbing') + ";"));
  12404. attr(span2, "tabindex", span2_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1);
  12405. attr(div1, "class", "quickAddCommandListItem");
  12406. },
  12407. m(target, anchor) {
  12408. insert(target, div1, anchor);
  12409. append(div1, li);
  12410. append(li, t0);
  12411. append(div1, t1);
  12412. append(div1, div0);
  12413. append(div0, span0);
  12414. mount_component(icon0, span0, null);
  12415. append(div0, t2);
  12416. append(div0, span1);
  12417. mount_component(icon1, span1, null);
  12418. append(div0, t3);
  12419. append(div0, span2);
  12420. mount_component(icon2, span2, null);
  12421. current = true;
  12422. if (!mounted) {
  12423. dispose = [
  12424. listen(span0, "click", /*click_handler*/ ctx[5]),
  12425. listen(span1, "click", /*click_handler_1*/ ctx[6]),
  12426. listen(span2, "mousedown", function () {
  12427. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  12428. }),
  12429. listen(span2, "touchstart", function () {
  12430. if (is_function(/*startDrag*/ ctx[1])) /*startDrag*/ ctx[1].apply(this, arguments);
  12431. })
  12432. ];
  12433. mounted = true;
  12434. }
  12435. },
  12436. p(new_ctx, [dirty]) {
  12437. ctx = new_ctx;
  12438. if ((!current || dirty & /*command*/ 1) && t0_value !== (t0_value = /*command*/ ctx[0].name + "")) set_data(t0, t0_value);
  12439. if (!current || dirty & /*dragDisabled*/ 4 && span2_style_value !== (span2_style_value = "" + ((/*dragDisabled*/ ctx[2]
  12440. ? 'cursor: grab'
  12441. : 'cursor: grabbing') + ";"))) {
  12442. attr(span2, "style", span2_style_value);
  12443. }
  12444. if (!current || dirty & /*dragDisabled*/ 4 && span2_tabindex_value !== (span2_tabindex_value = /*dragDisabled*/ ctx[2] ? 0 : -1)) {
  12445. attr(span2, "tabindex", span2_tabindex_value);
  12446. }
  12447. },
  12448. i(local) {
  12449. if (current) return;
  12450. transition_in(icon0.$$.fragment, local);
  12451. transition_in(icon1.$$.fragment, local);
  12452. transition_in(icon2.$$.fragment, local);
  12453. current = true;
  12454. },
  12455. o(local) {
  12456. transition_out(icon0.$$.fragment, local);
  12457. transition_out(icon1.$$.fragment, local);
  12458. transition_out(icon2.$$.fragment, local);
  12459. current = false;
  12460. },
  12461. d(detaching) {
  12462. if (detaching) detach(div1);
  12463. destroy_component(icon0);
  12464. destroy_component(icon1);
  12465. destroy_component(icon2);
  12466. mounted = false;
  12467. run_all(dispose);
  12468. }
  12469. };
  12470. }
  12471. function instance$2($$self, $$props, $$invalidate) {
  12472. let { command } = $$props;
  12473. let { startDrag } = $$props;
  12474. let { dragDisabled } = $$props;
  12475. const dispatch = createEventDispatcher();
  12476. function deleteCommand() {
  12477. dispatch('deleteCommand', command.id);
  12478. }
  12479. function configureChoice() {
  12480. dispatch('configureScript', command);
  12481. }
  12482. const click_handler = () => configureChoice();
  12483. const click_handler_1 = () => deleteCommand();
  12484. $$self.$$set = $$props => {
  12485. if ('command' in $$props) $$invalidate(0, command = $$props.command);
  12486. if ('startDrag' in $$props) $$invalidate(1, startDrag = $$props.startDrag);
  12487. if ('dragDisabled' in $$props) $$invalidate(2, dragDisabled = $$props.dragDisabled);
  12488. };
  12489. return [
  12490. command,
  12491. startDrag,
  12492. dragDisabled,
  12493. deleteCommand,
  12494. configureChoice,
  12495. click_handler,
  12496. click_handler_1
  12497. ];
  12498. }
  12499. class UserScriptCommand extends SvelteComponent {
  12500. constructor(options) {
  12501. super();
  12502. init(this, options, instance$2, create_fragment$2, safe_not_equal, {
  12503. command: 0,
  12504. startDrag: 1,
  12505. dragDisabled: 2
  12506. });
  12507. }
  12508. }
  12509. class UserScriptSettingsModal extends obsidian.Modal {
  12510. constructor(app, command, settings) {
  12511. super(app);
  12512. this.command = command;
  12513. this.settings = settings;
  12514. this.display();
  12515. if (!this.command.settings)
  12516. this.command.settings = {};
  12517. Object.keys(this.settings.options).forEach(setting => {
  12518. var _a;
  12519. if (this.command.settings[setting] === undefined) {
  12520. this.command.settings[setting] = (_a = this.settings.options[setting]) === null || _a === void 0 ? void 0 : _a.defaultValue;
  12521. }
  12522. });
  12523. }
  12524. display() {
  12525. var _a, _b, _c;
  12526. this.containerEl.addClass('quickAddModal', 'userScriptSettingsModal');
  12527. this.contentEl.empty();
  12528. this.titleEl.innerText = `${(_a = this.settings) === null || _a === void 0 ? void 0 : _a.name}${((_b = this.settings) === null || _b === void 0 ? void 0 : _b.author) ? " by " + ((_c = this.settings) === null || _c === void 0 ? void 0 : _c.author) : ""}`;
  12529. const options = this.settings.options;
  12530. Object.keys(options).forEach(option => {
  12531. var _a, _b;
  12532. const entry = options[option];
  12533. let value = entry.defaultValue;
  12534. if (this.command.settings[option] !== undefined) {
  12535. value = this.command.settings[option];
  12536. }
  12537. switch ((_b = (_a = options[option]) === null || _a === void 0 ? void 0 : _a.type) === null || _b === void 0 ? void 0 : _b.toLowerCase()) {
  12538. case "text":
  12539. case "input":
  12540. this.addInputBox(option, value, entry === null || entry === void 0 ? void 0 : entry.placeholder, entry === null || entry === void 0 ? void 0 : entry.secret);
  12541. break;
  12542. case "checkbox":
  12543. case "toggle":
  12544. this.addToggle(option, value);
  12545. break;
  12546. case "dropdown":
  12547. case "select":
  12548. this.addDropdown(option, entry.options, value);
  12549. break;
  12550. case "format":
  12551. this.addFormatInput(option, value, entry === null || entry === void 0 ? void 0 : entry.placeholder);
  12552. break;
  12553. }
  12554. });
  12555. }
  12556. setPasswordOnBlur(el) {
  12557. el.addEventListener('focus', () => {
  12558. el.type = "text";
  12559. });
  12560. el.addEventListener('blur', () => {
  12561. el.type = "password";
  12562. });
  12563. el.type = "password";
  12564. }
  12565. addInputBox(name, value, placeholder, passwordOnBlur) {
  12566. new obsidian.Setting(this.contentEl)
  12567. .setName(name)
  12568. .addText(input => {
  12569. input.setValue(value)
  12570. .onChange(value => this.command.settings[name] = value)
  12571. .setPlaceholder(placeholder !== null && placeholder !== void 0 ? placeholder : "");
  12572. if (passwordOnBlur) {
  12573. this.setPasswordOnBlur(input.inputEl);
  12574. }
  12575. });
  12576. }
  12577. addToggle(name, value) {
  12578. new obsidian.Setting(this.contentEl)
  12579. .setName(name)
  12580. .addToggle(toggle => toggle.setValue(value)
  12581. .onChange(value => this.command.settings[name] = value));
  12582. }
  12583. addDropdown(name, options, value) {
  12584. new obsidian.Setting(this.contentEl)
  12585. .setName(name)
  12586. .addDropdown(dropdown => {
  12587. options.forEach(item => dropdown.addOption(item, item));
  12588. dropdown.setValue(value);
  12589. dropdown.onChange(value => this.command.settings[name] = value);
  12590. });
  12591. }
  12592. addFormatInput(name, value, placeholder) {
  12593. new obsidian.Setting(this.contentEl).setName(name);
  12594. const formatDisplay = this.contentEl.createEl("span");
  12595. const input = new obsidian.TextComponent(this.contentEl);
  12596. new FormatSyntaxSuggester(this.app, input.inputEl, QuickAdd.instance);
  12597. const displayFormatter = new FormatDisplayFormatter(this.app, QuickAdd.instance);
  12598. input.setValue(value)
  12599. .onChange(async (value) => {
  12600. this.command.settings[name] = value;
  12601. formatDisplay.innerText = await displayFormatter.format(value);
  12602. })
  12603. .setPlaceholder(placeholder !== null && placeholder !== void 0 ? placeholder : "");
  12604. input.inputEl.style.width = "100%";
  12605. input.inputEl.style.marginBottom = "1em";
  12606. (async () => formatDisplay.innerText = await displayFormatter.format(value))();
  12607. }
  12608. }
  12609. /* src/gui/MacroGUIs/CommandList.svelte generated by Svelte v3.47.0 */
  12610. function add_css$1(target) {
  12611. append_styles(target, "svelte-1ukgrgp", ".quickAddCommandList.svelte-1ukgrgp{display:grid;grid-template-columns:auto;width:auto;border:0 solid black;overflow-y:auto;height:auto;margin-bottom:8px;padding:20px}");
  12612. }
  12613. function get_each_context(ctx, list, i) {
  12614. const child_ctx = ctx.slice();
  12615. child_ctx[33] = list[i];
  12616. child_ctx[34] = list;
  12617. child_ctx[35] = i;
  12618. return child_ctx;
  12619. }
  12620. // (93:8) {:else}
  12621. function create_else_block(ctx) {
  12622. let standardcommand;
  12623. let updating_command;
  12624. let updating_dragDisabled;
  12625. let updating_startDrag;
  12626. let current;
  12627. function standardcommand_command_binding(value) {
  12628. /*standardcommand_command_binding*/ ctx[27](value, /*command*/ ctx[33], /*each_value*/ ctx[34], /*command_index*/ ctx[35]);
  12629. }
  12630. function standardcommand_dragDisabled_binding(value) {
  12631. /*standardcommand_dragDisabled_binding*/ ctx[28](value);
  12632. }
  12633. function standardcommand_startDrag_binding(value) {
  12634. /*standardcommand_startDrag_binding*/ ctx[29](value);
  12635. }
  12636. let standardcommand_props = {};
  12637. if (/*command*/ ctx[33] !== void 0) {
  12638. standardcommand_props.command = /*command*/ ctx[33];
  12639. }
  12640. if (/*dragDisabled*/ ctx[3] !== void 0) {
  12641. standardcommand_props.dragDisabled = /*dragDisabled*/ ctx[3];
  12642. }
  12643. if (/*startDrag*/ ctx[4] !== void 0) {
  12644. standardcommand_props.startDrag = /*startDrag*/ ctx[4];
  12645. }
  12646. standardcommand = new StandardCommand({ props: standardcommand_props });
  12647. binding_callbacks.push(() => bind(standardcommand, 'command', standardcommand_command_binding));
  12648. binding_callbacks.push(() => bind(standardcommand, 'dragDisabled', standardcommand_dragDisabled_binding));
  12649. binding_callbacks.push(() => bind(standardcommand, 'startDrag', standardcommand_startDrag_binding));
  12650. standardcommand.$on("deleteCommand", /*deleteCommand_handler_3*/ ctx[30]);
  12651. standardcommand.$on("updateCommand", /*updateCommandFromEvent*/ ctx[7]);
  12652. return {
  12653. c() {
  12654. create_component(standardcommand.$$.fragment);
  12655. },
  12656. m(target, anchor) {
  12657. mount_component(standardcommand, target, anchor);
  12658. current = true;
  12659. },
  12660. p(new_ctx, dirty) {
  12661. ctx = new_ctx;
  12662. const standardcommand_changes = {};
  12663. if (!updating_command && dirty[0] & /*commands, SHADOW_PLACEHOLDER_ITEM_ID*/ 5) {
  12664. updating_command = true;
  12665. standardcommand_changes.command = /*command*/ ctx[33];
  12666. add_flush_callback(() => updating_command = false);
  12667. }
  12668. if (!updating_dragDisabled && dirty[0] & /*dragDisabled*/ 8) {
  12669. updating_dragDisabled = true;
  12670. standardcommand_changes.dragDisabled = /*dragDisabled*/ ctx[3];
  12671. add_flush_callback(() => updating_dragDisabled = false);
  12672. }
  12673. if (!updating_startDrag && dirty[0] & /*startDrag*/ 16) {
  12674. updating_startDrag = true;
  12675. standardcommand_changes.startDrag = /*startDrag*/ ctx[4];
  12676. add_flush_callback(() => updating_startDrag = false);
  12677. }
  12678. standardcommand.$set(standardcommand_changes);
  12679. },
  12680. i(local) {
  12681. if (current) return;
  12682. transition_in(standardcommand.$$.fragment, local);
  12683. current = true;
  12684. },
  12685. o(local) {
  12686. transition_out(standardcommand.$$.fragment, local);
  12687. current = false;
  12688. },
  12689. d(detaching) {
  12690. destroy_component(standardcommand, detaching);
  12691. }
  12692. };
  12693. }
  12694. // (91:58)
  12695. function create_if_block_2(ctx) {
  12696. let userscriptcommand;
  12697. let updating_command;
  12698. let updating_dragDisabled;
  12699. let updating_startDrag;
  12700. let current;
  12701. function userscriptcommand_command_binding(value) {
  12702. /*userscriptcommand_command_binding*/ ctx[23](value, /*command*/ ctx[33], /*each_value*/ ctx[34], /*command_index*/ ctx[35]);
  12703. }
  12704. function userscriptcommand_dragDisabled_binding(value) {
  12705. /*userscriptcommand_dragDisabled_binding*/ ctx[24](value);
  12706. }
  12707. function userscriptcommand_startDrag_binding(value) {
  12708. /*userscriptcommand_startDrag_binding*/ ctx[25](value);
  12709. }
  12710. let userscriptcommand_props = {};
  12711. if (/*command*/ ctx[33] !== void 0) {
  12712. userscriptcommand_props.command = /*command*/ ctx[33];
  12713. }
  12714. if (/*dragDisabled*/ ctx[3] !== void 0) {
  12715. userscriptcommand_props.dragDisabled = /*dragDisabled*/ ctx[3];
  12716. }
  12717. if (/*startDrag*/ ctx[4] !== void 0) {
  12718. userscriptcommand_props.startDrag = /*startDrag*/ ctx[4];
  12719. }
  12720. userscriptcommand = new UserScriptCommand({ props: userscriptcommand_props });
  12721. binding_callbacks.push(() => bind(userscriptcommand, 'command', userscriptcommand_command_binding));
  12722. binding_callbacks.push(() => bind(userscriptcommand, 'dragDisabled', userscriptcommand_dragDisabled_binding));
  12723. binding_callbacks.push(() => bind(userscriptcommand, 'startDrag', userscriptcommand_startDrag_binding));
  12724. userscriptcommand.$on("deleteCommand", /*deleteCommand_handler_2*/ ctx[26]);
  12725. userscriptcommand.$on("updateCommand", /*updateCommandFromEvent*/ ctx[7]);
  12726. userscriptcommand.$on("configureScript", /*configureScript*/ ctx[9]);
  12727. return {
  12728. c() {
  12729. create_component(userscriptcommand.$$.fragment);
  12730. },
  12731. m(target, anchor) {
  12732. mount_component(userscriptcommand, target, anchor);
  12733. current = true;
  12734. },
  12735. p(new_ctx, dirty) {
  12736. ctx = new_ctx;
  12737. const userscriptcommand_changes = {};
  12738. if (!updating_command && dirty[0] & /*commands, SHADOW_PLACEHOLDER_ITEM_ID*/ 5) {
  12739. updating_command = true;
  12740. userscriptcommand_changes.command = /*command*/ ctx[33];
  12741. add_flush_callback(() => updating_command = false);
  12742. }
  12743. if (!updating_dragDisabled && dirty[0] & /*dragDisabled*/ 8) {
  12744. updating_dragDisabled = true;
  12745. userscriptcommand_changes.dragDisabled = /*dragDisabled*/ ctx[3];
  12746. add_flush_callback(() => updating_dragDisabled = false);
  12747. }
  12748. if (!updating_startDrag && dirty[0] & /*startDrag*/ 16) {
  12749. updating_startDrag = true;
  12750. userscriptcommand_changes.startDrag = /*startDrag*/ ctx[4];
  12751. add_flush_callback(() => updating_startDrag = false);
  12752. }
  12753. userscriptcommand.$set(userscriptcommand_changes);
  12754. },
  12755. i(local) {
  12756. if (current) return;
  12757. transition_in(userscriptcommand.$$.fragment, local);
  12758. current = true;
  12759. },
  12760. o(local) {
  12761. transition_out(userscriptcommand.$$.fragment, local);
  12762. current = false;
  12763. },
  12764. d(detaching) {
  12765. destroy_component(userscriptcommand, detaching);
  12766. }
  12767. };
  12768. }
  12769. // (89:60)
  12770. function create_if_block_1(ctx) {
  12771. let nestedchoicecommand;
  12772. let updating_command;
  12773. let updating_dragDisabled;
  12774. let updating_startDrag;
  12775. let current;
  12776. function nestedchoicecommand_command_binding(value) {
  12777. /*nestedchoicecommand_command_binding*/ ctx[19](value, /*command*/ ctx[33], /*each_value*/ ctx[34], /*command_index*/ ctx[35]);
  12778. }
  12779. function nestedchoicecommand_dragDisabled_binding(value) {
  12780. /*nestedchoicecommand_dragDisabled_binding*/ ctx[20](value);
  12781. }
  12782. function nestedchoicecommand_startDrag_binding(value) {
  12783. /*nestedchoicecommand_startDrag_binding*/ ctx[21](value);
  12784. }
  12785. let nestedchoicecommand_props = {};
  12786. if (/*command*/ ctx[33] !== void 0) {
  12787. nestedchoicecommand_props.command = /*command*/ ctx[33];
  12788. }
  12789. if (/*dragDisabled*/ ctx[3] !== void 0) {
  12790. nestedchoicecommand_props.dragDisabled = /*dragDisabled*/ ctx[3];
  12791. }
  12792. if (/*startDrag*/ ctx[4] !== void 0) {
  12793. nestedchoicecommand_props.startDrag = /*startDrag*/ ctx[4];
  12794. }
  12795. nestedchoicecommand = new NestedChoiceCommand$1({ props: nestedchoicecommand_props });
  12796. binding_callbacks.push(() => bind(nestedchoicecommand, 'command', nestedchoicecommand_command_binding));
  12797. binding_callbacks.push(() => bind(nestedchoicecommand, 'dragDisabled', nestedchoicecommand_dragDisabled_binding));
  12798. binding_callbacks.push(() => bind(nestedchoicecommand, 'startDrag', nestedchoicecommand_startDrag_binding));
  12799. nestedchoicecommand.$on("deleteCommand", /*deleteCommand_handler_1*/ ctx[22]);
  12800. nestedchoicecommand.$on("updateCommand", /*updateCommandFromEvent*/ ctx[7]);
  12801. nestedchoicecommand.$on("configureChoice", /*configureChoice*/ ctx[8]);
  12802. return {
  12803. c() {
  12804. create_component(nestedchoicecommand.$$.fragment);
  12805. },
  12806. m(target, anchor) {
  12807. mount_component(nestedchoicecommand, target, anchor);
  12808. current = true;
  12809. },
  12810. p(new_ctx, dirty) {
  12811. ctx = new_ctx;
  12812. const nestedchoicecommand_changes = {};
  12813. if (!updating_command && dirty[0] & /*commands, SHADOW_PLACEHOLDER_ITEM_ID*/ 5) {
  12814. updating_command = true;
  12815. nestedchoicecommand_changes.command = /*command*/ ctx[33];
  12816. add_flush_callback(() => updating_command = false);
  12817. }
  12818. if (!updating_dragDisabled && dirty[0] & /*dragDisabled*/ 8) {
  12819. updating_dragDisabled = true;
  12820. nestedchoicecommand_changes.dragDisabled = /*dragDisabled*/ ctx[3];
  12821. add_flush_callback(() => updating_dragDisabled = false);
  12822. }
  12823. if (!updating_startDrag && dirty[0] & /*startDrag*/ 16) {
  12824. updating_startDrag = true;
  12825. nestedchoicecommand_changes.startDrag = /*startDrag*/ ctx[4];
  12826. add_flush_callback(() => updating_startDrag = false);
  12827. }
  12828. nestedchoicecommand.$set(nestedchoicecommand_changes);
  12829. },
  12830. i(local) {
  12831. if (current) return;
  12832. transition_in(nestedchoicecommand.$$.fragment, local);
  12833. current = true;
  12834. },
  12835. o(local) {
  12836. transition_out(nestedchoicecommand.$$.fragment, local);
  12837. current = false;
  12838. },
  12839. d(detaching) {
  12840. destroy_component(nestedchoicecommand, detaching);
  12841. }
  12842. };
  12843. }
  12844. // (87:8) {#if command.type === CommandType.Wait}
  12845. function create_if_block(ctx) {
  12846. let waitcommand;
  12847. let updating_command;
  12848. let updating_dragDisabled;
  12849. let updating_startDrag;
  12850. let current;
  12851. function waitcommand_command_binding(value) {
  12852. /*waitcommand_command_binding*/ ctx[15](value, /*command*/ ctx[33], /*each_value*/ ctx[34], /*command_index*/ ctx[35]);
  12853. }
  12854. function waitcommand_dragDisabled_binding(value) {
  12855. /*waitcommand_dragDisabled_binding*/ ctx[16](value);
  12856. }
  12857. function waitcommand_startDrag_binding(value) {
  12858. /*waitcommand_startDrag_binding*/ ctx[17](value);
  12859. }
  12860. let waitcommand_props = {};
  12861. if (/*command*/ ctx[33] !== void 0) {
  12862. waitcommand_props.command = /*command*/ ctx[33];
  12863. }
  12864. if (/*dragDisabled*/ ctx[3] !== void 0) {
  12865. waitcommand_props.dragDisabled = /*dragDisabled*/ ctx[3];
  12866. }
  12867. if (/*startDrag*/ ctx[4] !== void 0) {
  12868. waitcommand_props.startDrag = /*startDrag*/ ctx[4];
  12869. }
  12870. waitcommand = new WaitCommand$1({ props: waitcommand_props });
  12871. binding_callbacks.push(() => bind(waitcommand, 'command', waitcommand_command_binding));
  12872. binding_callbacks.push(() => bind(waitcommand, 'dragDisabled', waitcommand_dragDisabled_binding));
  12873. binding_callbacks.push(() => bind(waitcommand, 'startDrag', waitcommand_startDrag_binding));
  12874. waitcommand.$on("deleteCommand", /*deleteCommand_handler*/ ctx[18]);
  12875. waitcommand.$on("updateCommand", /*updateCommandFromEvent*/ ctx[7]);
  12876. return {
  12877. c() {
  12878. create_component(waitcommand.$$.fragment);
  12879. },
  12880. m(target, anchor) {
  12881. mount_component(waitcommand, target, anchor);
  12882. current = true;
  12883. },
  12884. p(new_ctx, dirty) {
  12885. ctx = new_ctx;
  12886. const waitcommand_changes = {};
  12887. if (!updating_command && dirty[0] & /*commands, SHADOW_PLACEHOLDER_ITEM_ID*/ 5) {
  12888. updating_command = true;
  12889. waitcommand_changes.command = /*command*/ ctx[33];
  12890. add_flush_callback(() => updating_command = false);
  12891. }
  12892. if (!updating_dragDisabled && dirty[0] & /*dragDisabled*/ 8) {
  12893. updating_dragDisabled = true;
  12894. waitcommand_changes.dragDisabled = /*dragDisabled*/ ctx[3];
  12895. add_flush_callback(() => updating_dragDisabled = false);
  12896. }
  12897. if (!updating_startDrag && dirty[0] & /*startDrag*/ 16) {
  12898. updating_startDrag = true;
  12899. waitcommand_changes.startDrag = /*startDrag*/ ctx[4];
  12900. add_flush_callback(() => updating_startDrag = false);
  12901. }
  12902. waitcommand.$set(waitcommand_changes);
  12903. },
  12904. i(local) {
  12905. if (current) return;
  12906. transition_in(waitcommand.$$.fragment, local);
  12907. current = true;
  12908. },
  12909. o(local) {
  12910. transition_out(waitcommand.$$.fragment, local);
  12911. current = false;
  12912. },
  12913. d(detaching) {
  12914. destroy_component(waitcommand, detaching);
  12915. }
  12916. };
  12917. }
  12918. // (86:4) {#each commands.filter(c => c.id !== SHADOW_PLACEHOLDER_ITEM_ID) as command(command.id)}
  12919. function create_each_block(key_1, ctx) {
  12920. let first;
  12921. let current_block_type_index;
  12922. let if_block;
  12923. let if_block_anchor;
  12924. let current;
  12925. const if_block_creators = [create_if_block, create_if_block_1, create_if_block_2, create_else_block];
  12926. const if_blocks = [];
  12927. function select_block_type(ctx, dirty) {
  12928. if (/*command*/ ctx[33].type === CommandType.Wait) return 0;
  12929. if (/*command*/ ctx[33].type === CommandType.NestedChoice) return 1;
  12930. if (/*command*/ ctx[33].type === CommandType.UserScript) return 2;
  12931. return 3;
  12932. }
  12933. current_block_type_index = select_block_type(ctx);
  12934. if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  12935. return {
  12936. key: key_1,
  12937. first: null,
  12938. c() {
  12939. first = empty();
  12940. if_block.c();
  12941. if_block_anchor = empty();
  12942. this.first = first;
  12943. },
  12944. m(target, anchor) {
  12945. insert(target, first, anchor);
  12946. if_blocks[current_block_type_index].m(target, anchor);
  12947. insert(target, if_block_anchor, anchor);
  12948. current = true;
  12949. },
  12950. p(new_ctx, dirty) {
  12951. ctx = new_ctx;
  12952. let previous_block_index = current_block_type_index;
  12953. current_block_type_index = select_block_type(ctx);
  12954. if (current_block_type_index === previous_block_index) {
  12955. if_blocks[current_block_type_index].p(ctx, dirty);
  12956. } else {
  12957. group_outros();
  12958. transition_out(if_blocks[previous_block_index], 1, 1, () => {
  12959. if_blocks[previous_block_index] = null;
  12960. });
  12961. check_outros();
  12962. if_block = if_blocks[current_block_type_index];
  12963. if (!if_block) {
  12964. if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  12965. if_block.c();
  12966. } else {
  12967. if_block.p(ctx, dirty);
  12968. }
  12969. transition_in(if_block, 1);
  12970. if_block.m(if_block_anchor.parentNode, if_block_anchor);
  12971. }
  12972. },
  12973. i(local) {
  12974. if (current) return;
  12975. transition_in(if_block);
  12976. current = true;
  12977. },
  12978. o(local) {
  12979. transition_out(if_block);
  12980. current = false;
  12981. },
  12982. d(detaching) {
  12983. if (detaching) detach(first);
  12984. if_blocks[current_block_type_index].d(detaching);
  12985. if (detaching) detach(if_block_anchor);
  12986. }
  12987. };
  12988. }
  12989. function create_fragment$1(ctx) {
  12990. let ol;
  12991. let each_blocks = [];
  12992. let each_1_lookup = new Map();
  12993. let dndzone_action;
  12994. let current;
  12995. let mounted;
  12996. let dispose;
  12997. let each_value = /*commands*/ ctx[0].filter(/*func*/ ctx[14]);
  12998. const get_key = ctx => /*command*/ ctx[33].id;
  12999. for (let i = 0; i < each_value.length; i += 1) {
  13000. let child_ctx = get_each_context(ctx, each_value, i);
  13001. let key = get_key(child_ctx);
  13002. each_1_lookup.set(key, each_blocks[i] = create_each_block(key, child_ctx));
  13003. }
  13004. return {
  13005. c() {
  13006. ol = element("ol");
  13007. for (let i = 0; i < each_blocks.length; i += 1) {
  13008. each_blocks[i].c();
  13009. }
  13010. attr(ol, "class", "quickAddCommandList svelte-1ukgrgp");
  13011. },
  13012. m(target, anchor) {
  13013. insert(target, ol, anchor);
  13014. for (let i = 0; i < each_blocks.length; i += 1) {
  13015. each_blocks[i].m(ol, null);
  13016. }
  13017. current = true;
  13018. if (!mounted) {
  13019. dispose = [
  13020. action_destroyer(dndzone_action = dndzone$2.call(null, ol, {
  13021. items: /*commands*/ ctx[0],
  13022. dragDisabled: /*dragDisabled*/ ctx[3],
  13023. dropTargetStyle: {},
  13024. type: "command"
  13025. })),
  13026. listen(ol, "consider", /*handleConsider*/ ctx[5]),
  13027. listen(ol, "finalize", /*handleSort*/ ctx[6])
  13028. ];
  13029. mounted = true;
  13030. }
  13031. },
  13032. p(ctx, dirty) {
  13033. if (dirty[0] & /*commands, SHADOW_PLACEHOLDER_ITEM_ID, dragDisabled, startDrag, deleteCommand, updateCommandFromEvent, configureChoice, configureScript*/ 927) {
  13034. each_value = /*commands*/ ctx[0].filter(/*func*/ ctx[14]);
  13035. group_outros();
  13036. each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value, each_1_lookup, ol, outro_and_destroy_block, create_each_block, null, get_each_context);
  13037. check_outros();
  13038. }
  13039. if (dndzone_action && is_function(dndzone_action.update) && dirty[0] & /*commands, dragDisabled*/ 9) dndzone_action.update.call(null, {
  13040. items: /*commands*/ ctx[0],
  13041. dragDisabled: /*dragDisabled*/ ctx[3],
  13042. dropTargetStyle: {},
  13043. type: "command"
  13044. });
  13045. },
  13046. i(local) {
  13047. if (current) return;
  13048. for (let i = 0; i < each_value.length; i += 1) {
  13049. transition_in(each_blocks[i]);
  13050. }
  13051. current = true;
  13052. },
  13053. o(local) {
  13054. for (let i = 0; i < each_blocks.length; i += 1) {
  13055. transition_out(each_blocks[i]);
  13056. }
  13057. current = false;
  13058. },
  13059. d(detaching) {
  13060. if (detaching) detach(ol);
  13061. for (let i = 0; i < each_blocks.length; i += 1) {
  13062. each_blocks[i].d();
  13063. }
  13064. mounted = false;
  13065. run_all(dispose);
  13066. }
  13067. };
  13068. }
  13069. function instance$1($$self, $$props, $$invalidate) {
  13070. let { commands } = $$props;
  13071. let { deleteCommand } = $$props;
  13072. let { saveCommands } = $$props;
  13073. let { app } = $$props;
  13074. let { plugin } = $$props;
  13075. let dragDisabled = true;
  13076. const updateCommandList = newCommands => {
  13077. $$invalidate(0, commands = newCommands);
  13078. };
  13079. function handleConsider(e) {
  13080. let { items: newItems } = e.detail;
  13081. $$invalidate(0, commands = newItems);
  13082. }
  13083. function handleSort(e) {
  13084. let { items: newItems, info: { source } } = e.detail;
  13085. $$invalidate(0, commands = newItems);
  13086. if (source === SOURCES.POINTER) {
  13087. $$invalidate(3, dragDisabled = true);
  13088. }
  13089. saveCommands(commands);
  13090. }
  13091. let startDrag = e => {
  13092. e.preventDefault();
  13093. $$invalidate(3, dragDisabled = false);
  13094. };
  13095. function updateCommandFromEvent(e) {
  13096. const command = e.detail;
  13097. updateCommand(command);
  13098. }
  13099. function updateCommand(command) {
  13100. const index = commands.findIndex(c => c.id === command.id);
  13101. $$invalidate(0, commands[index] = command, commands);
  13102. saveCommands(commands);
  13103. }
  13104. async function configureChoice(e) {
  13105. const command = e.detail;
  13106. const newChoice = await getChoiceBuilder(command.choice).waitForClose;
  13107. if (!newChoice) return;
  13108. command.choice = newChoice;
  13109. command.name = newChoice.name;
  13110. updateCommand(command);
  13111. }
  13112. function getChoiceBuilder(choice) {
  13113. switch (choice.type) {
  13114. case ChoiceType.Template:
  13115. return new TemplateChoiceBuilder(app, choice, plugin);
  13116. case ChoiceType.Capture:
  13117. return new CaptureChoiceBuilder(app, choice, plugin);
  13118. case ChoiceType.Macro:
  13119. case ChoiceType.Multi:
  13120. }
  13121. }
  13122. async function configureScript(e) {
  13123. const command = e.detail;
  13124. const userScript = await getUserScript(command, app);
  13125. if (!userScript.settings) {
  13126. log.logWarning(`${command.name} has no settings.`);
  13127. return;
  13128. }
  13129. new UserScriptSettingsModal(app, command, userScript.settings).open();
  13130. }
  13131. const func = c => c.id !== SHADOW_PLACEHOLDER_ITEM_ID;
  13132. function waitcommand_command_binding(value, command, each_value, command_index) {
  13133. each_value[command_index] = value;
  13134. $$invalidate(0, commands);
  13135. }
  13136. function waitcommand_dragDisabled_binding(value) {
  13137. dragDisabled = value;
  13138. $$invalidate(3, dragDisabled);
  13139. }
  13140. function waitcommand_startDrag_binding(value) {
  13141. startDrag = value;
  13142. $$invalidate(4, startDrag);
  13143. }
  13144. const deleteCommand_handler = async e => await deleteCommand(e.detail);
  13145. function nestedchoicecommand_command_binding(value, command, each_value, command_index) {
  13146. each_value[command_index] = value;
  13147. $$invalidate(0, commands);
  13148. }
  13149. function nestedchoicecommand_dragDisabled_binding(value) {
  13150. dragDisabled = value;
  13151. $$invalidate(3, dragDisabled);
  13152. }
  13153. function nestedchoicecommand_startDrag_binding(value) {
  13154. startDrag = value;
  13155. $$invalidate(4, startDrag);
  13156. }
  13157. const deleteCommand_handler_1 = async e => await deleteCommand(e.detail);
  13158. function userscriptcommand_command_binding(value, command, each_value, command_index) {
  13159. each_value[command_index] = value;
  13160. $$invalidate(0, commands);
  13161. }
  13162. function userscriptcommand_dragDisabled_binding(value) {
  13163. dragDisabled = value;
  13164. $$invalidate(3, dragDisabled);
  13165. }
  13166. function userscriptcommand_startDrag_binding(value) {
  13167. startDrag = value;
  13168. $$invalidate(4, startDrag);
  13169. }
  13170. const deleteCommand_handler_2 = async e => await deleteCommand(e.detail);
  13171. function standardcommand_command_binding(value, command, each_value, command_index) {
  13172. each_value[command_index] = value;
  13173. $$invalidate(0, commands);
  13174. }
  13175. function standardcommand_dragDisabled_binding(value) {
  13176. dragDisabled = value;
  13177. $$invalidate(3, dragDisabled);
  13178. }
  13179. function standardcommand_startDrag_binding(value) {
  13180. startDrag = value;
  13181. $$invalidate(4, startDrag);
  13182. }
  13183. const deleteCommand_handler_3 = async e => await deleteCommand(e.detail);
  13184. $$self.$$set = $$props => {
  13185. if ('commands' in $$props) $$invalidate(0, commands = $$props.commands);
  13186. if ('deleteCommand' in $$props) $$invalidate(1, deleteCommand = $$props.deleteCommand);
  13187. if ('saveCommands' in $$props) $$invalidate(10, saveCommands = $$props.saveCommands);
  13188. if ('app' in $$props) $$invalidate(11, app = $$props.app);
  13189. if ('plugin' in $$props) $$invalidate(12, plugin = $$props.plugin);
  13190. };
  13191. return [
  13192. commands,
  13193. deleteCommand,
  13194. SHADOW_PLACEHOLDER_ITEM_ID,
  13195. dragDisabled,
  13196. startDrag,
  13197. handleConsider,
  13198. handleSort,
  13199. updateCommandFromEvent,
  13200. configureChoice,
  13201. configureScript,
  13202. saveCommands,
  13203. app,
  13204. plugin,
  13205. updateCommandList,
  13206. func,
  13207. waitcommand_command_binding,
  13208. waitcommand_dragDisabled_binding,
  13209. waitcommand_startDrag_binding,
  13210. deleteCommand_handler,
  13211. nestedchoicecommand_command_binding,
  13212. nestedchoicecommand_dragDisabled_binding,
  13213. nestedchoicecommand_startDrag_binding,
  13214. deleteCommand_handler_1,
  13215. userscriptcommand_command_binding,
  13216. userscriptcommand_dragDisabled_binding,
  13217. userscriptcommand_startDrag_binding,
  13218. deleteCommand_handler_2,
  13219. standardcommand_command_binding,
  13220. standardcommand_dragDisabled_binding,
  13221. standardcommand_startDrag_binding,
  13222. deleteCommand_handler_3
  13223. ];
  13224. }
  13225. class CommandList extends SvelteComponent {
  13226. constructor(options) {
  13227. super();
  13228. init(
  13229. this,
  13230. options,
  13231. instance$1,
  13232. create_fragment$1,
  13233. safe_not_equal,
  13234. {
  13235. commands: 0,
  13236. deleteCommand: 1,
  13237. saveCommands: 10,
  13238. app: 11,
  13239. plugin: 12,
  13240. updateCommandList: 13
  13241. },
  13242. add_css$1,
  13243. [-1, -1]
  13244. );
  13245. }
  13246. get updateCommandList() {
  13247. return this.$$.ctx[13];
  13248. }
  13249. }
  13250. class ChoiceCommand extends Command {
  13251. constructor(name, choiceId) {
  13252. super(name, CommandType.Choice);
  13253. this.choiceId = choiceId;
  13254. }
  13255. }
  13256. class WaitCommand extends Command {
  13257. constructor(time) {
  13258. super("Wait", CommandType.Wait);
  13259. this.time = time;
  13260. }
  13261. }
  13262. class NestedChoiceCommand extends Command {
  13263. constructor(choice) {
  13264. super(choice.name, CommandType.NestedChoice);
  13265. this.choice = choice;
  13266. }
  13267. }
  13268. class MacroBuilder extends obsidian.Modal {
  13269. constructor(app, plugin, macro, choices) {
  13270. super(app);
  13271. this.commands = [];
  13272. this.javascriptFiles = [];
  13273. this.choices = [];
  13274. this.macro = macro;
  13275. this.svelteElements = [];
  13276. this.choices = choices;
  13277. this.plugin = plugin;
  13278. this.waitForClose = new Promise(resolve => (this.resolvePromise = resolve));
  13279. this.getObsidianCommands();
  13280. this.getJavascriptFiles();
  13281. this.display();
  13282. this.open();
  13283. }
  13284. onClose() {
  13285. super.onClose();
  13286. this.resolvePromise(this.macro);
  13287. this.svelteElements.forEach(el => {
  13288. if (el && el.$destroy)
  13289. el.$destroy();
  13290. });
  13291. }
  13292. display() {
  13293. this.containerEl.addClass('quickAddModal', 'macroBuilder');
  13294. this.contentEl.empty();
  13295. this.addCenteredHeader(this.macro.name);
  13296. this.addCommandList();
  13297. this.addCommandBar();
  13298. this.addAddObsidianCommandSetting();
  13299. this.addAddEditorCommandsSetting();
  13300. this.addAddUserScriptSetting();
  13301. this.addAddChoiceSetting();
  13302. }
  13303. addCenteredHeader(header) {
  13304. const headerEl = this.contentEl.createEl('h2');
  13305. headerEl.style.textAlign = "center";
  13306. headerEl.setText(header);
  13307. headerEl.addClass('clickable');
  13308. headerEl.addEventListener('click', async () => {
  13309. const newMacroName = await GenericInputPrompt.Prompt(this.app, `Update name for ${this.macro.name}`, this.macro.name);
  13310. if (!newMacroName)
  13311. return;
  13312. this.macro.name = newMacroName;
  13313. this.reload();
  13314. });
  13315. }
  13316. reload() {
  13317. this.display();
  13318. }
  13319. addAddObsidianCommandSetting() {
  13320. let input;
  13321. const addObsidianCommandFromInput = () => {
  13322. const value = input.getValue();
  13323. const obsidianCommand = this.commands.find(v => v.name === value);
  13324. const command = new ObsidianCommand(obsidianCommand.name, obsidianCommand.commandId);
  13325. command.generateId();
  13326. this.addCommandToMacro(command);
  13327. input.setValue("");
  13328. };
  13329. new obsidian.Setting(this.contentEl)
  13330. .setName("Obsidian command")
  13331. .setDesc("Add an Obsidian command")
  13332. .addText(textComponent => {
  13333. input = textComponent;
  13334. textComponent.inputEl.style.marginRight = "1em";
  13335. textComponent.setPlaceholder("Obsidian command");
  13336. new GenericTextSuggester(this.app, textComponent.inputEl, this.commands.map(c => c.name));
  13337. textComponent.inputEl.addEventListener('keypress', (e) => {
  13338. if (e.key === 'Enter') {
  13339. addObsidianCommandFromInput();
  13340. }
  13341. });
  13342. })
  13343. .addButton(button => button.setCta().setButtonText("Add").onClick(addObsidianCommandFromInput));
  13344. }
  13345. addAddEditorCommandsSetting() {
  13346. let dropdownComponent;
  13347. const addEditorCommandFromDropdown = () => {
  13348. const type = dropdownComponent.getValue();
  13349. let command;
  13350. switch (type) {
  13351. case EditorCommandType.Copy:
  13352. command = new CopyCommand();
  13353. break;
  13354. case EditorCommandType.Cut:
  13355. command = new CutCommand();
  13356. break;
  13357. case EditorCommandType.Paste:
  13358. command = new PasteCommand();
  13359. break;
  13360. case EditorCommandType.SelectActiveLine:
  13361. command = new SelectActiveLineCommand();
  13362. break;
  13363. case EditorCommandType.SelectLinkOnActiveLine:
  13364. command = new SelectLinkOnActiveLineCommand();
  13365. break;
  13366. default:
  13367. log.logError("invalid editor command type");
  13368. }
  13369. this.addCommandToMacro(command);
  13370. };
  13371. new obsidian.Setting(this.contentEl)
  13372. .setName("Editor commands")
  13373. .setDesc("Add editor command")
  13374. .addDropdown(dropdown => {
  13375. dropdownComponent = dropdown;
  13376. dropdown.selectEl.style.marginRight = "1em";
  13377. dropdown.addOption(EditorCommandType.Copy, EditorCommandType.Copy)
  13378. .addOption(EditorCommandType.Cut, EditorCommandType.Cut)
  13379. .addOption(EditorCommandType.Paste, EditorCommandType.Paste)
  13380. .addOption(EditorCommandType.SelectActiveLine, EditorCommandType.SelectActiveLine)
  13381. .addOption(EditorCommandType.SelectLinkOnActiveLine, EditorCommandType.SelectLinkOnActiveLine);
  13382. })
  13383. .addButton(button => button.setCta().setButtonText("Add").onClick(addEditorCommandFromDropdown));
  13384. }
  13385. addAddUserScriptSetting() {
  13386. let input;
  13387. const addUserScriptFromInput = () => {
  13388. const value = input.getValue();
  13389. const scriptBasename = getUserScriptMemberAccess(value).basename;
  13390. const file = this.javascriptFiles.find(f => f.basename === scriptBasename);
  13391. if (!file)
  13392. return;
  13393. this.addCommandToMacro(new UserScript(value, file.path));
  13394. input.setValue("");
  13395. };
  13396. new obsidian.Setting(this.contentEl)
  13397. .setName("User Scripts")
  13398. .setDesc("Add user script")
  13399. .addText(textComponent => {
  13400. input = textComponent;
  13401. textComponent.inputEl.style.marginRight = "1em";
  13402. textComponent.setPlaceholder("User script");
  13403. new GenericTextSuggester(this.app, textComponent.inputEl, this.javascriptFiles.map(f => f.basename));
  13404. textComponent.inputEl.addEventListener('keypress', (e) => {
  13405. if (e.key === 'Enter') {
  13406. addUserScriptFromInput();
  13407. }
  13408. });
  13409. })
  13410. .addButton(button => button
  13411. .setButtonText("Add")
  13412. .setCta()
  13413. .onClick(addUserScriptFromInput));
  13414. }
  13415. addAddChoiceSetting() {
  13416. let input;
  13417. const addChoiceFromInput = () => {
  13418. const value = input.getValue();
  13419. const choice = this.choices.find(c => c.name === value);
  13420. if (!choice)
  13421. return;
  13422. this.addCommandToMacro(new ChoiceCommand(choice.name, choice.id));
  13423. input.setValue("");
  13424. };
  13425. new obsidian.Setting(this.contentEl)
  13426. .setName("Choices")
  13427. .setDesc("Add existing choice")
  13428. .addText(textComponent => {
  13429. input = textComponent;
  13430. textComponent.inputEl.style.marginRight = "1em";
  13431. textComponent.setPlaceholder("Choice");
  13432. new GenericTextSuggester(this.app, textComponent.inputEl, this.choices.map(c => c.name));
  13433. textComponent.inputEl.addEventListener('keypress', (e) => {
  13434. if (e.key === 'Enter') {
  13435. addChoiceFromInput();
  13436. }
  13437. });
  13438. })
  13439. .addButton(button => button.setCta()
  13440. .setButtonText("Add")
  13441. .onClick(addChoiceFromInput));
  13442. }
  13443. getObsidianCommands() {
  13444. // @ts-ignore
  13445. Object.keys(this.app.commands.commands).forEach(key => {
  13446. // @ts-ignore
  13447. const command = this.app.commands.commands[key];
  13448. this.commands.push(new ObsidianCommand(command.name, command.id));
  13449. });
  13450. }
  13451. getJavascriptFiles() {
  13452. this.javascriptFiles = this.app.vault.getFiles()
  13453. .filter(file => JAVASCRIPT_FILE_EXTENSION_REGEX.test(file.path));
  13454. }
  13455. addCommandList() {
  13456. const commandList = this.contentEl.createDiv('commandList');
  13457. console.log(this.macro.commands);
  13458. this.commandListEl = new CommandList({
  13459. target: commandList,
  13460. props: {
  13461. app: this.app,
  13462. plugin: this.plugin,
  13463. commands: this.macro.commands,
  13464. deleteCommand: async (commandId) => {
  13465. const command = this.macro.commands.find(c => c.id === commandId);
  13466. const promptAnswer = await GenericYesNoPrompt.Prompt(this.app, "Are you sure you wish to delete this command?", `If you click yes, you will delete '${command.name}'.`);
  13467. if (!promptAnswer)
  13468. return;
  13469. this.macro.commands = this.macro.commands.filter(c => c.id !== commandId);
  13470. this.commandListEl.updateCommandList(this.macro.commands);
  13471. },
  13472. saveCommands: (commands) => {
  13473. this.macro.commands = commands;
  13474. },
  13475. }
  13476. });
  13477. this.svelteElements.push(this.commandListEl);
  13478. }
  13479. addCommandBar() {
  13480. const quickCommandContainer = this.contentEl.createDiv('quickCommandContainer');
  13481. this.newChoiceButton(quickCommandContainer, "Capture", CaptureChoice);
  13482. this.newChoiceButton(quickCommandContainer, "Template", TemplateChoice);
  13483. this.addAddWaitCommandButton(quickCommandContainer);
  13484. }
  13485. addAddWaitCommandButton(quickCommandContainer) {
  13486. const button = new obsidian.ButtonComponent(quickCommandContainer);
  13487. button.setIcon('clock').setTooltip("Add wait command").onClick(() => {
  13488. this.addCommandToMacro(new WaitCommand(100));
  13489. });
  13490. }
  13491. newChoiceButton(container, typeName, type) {
  13492. const button = new obsidian.ButtonComponent(container);
  13493. button.setButtonText(typeName).setTooltip(`Add ${typeName} Choice`).onClick(() => {
  13494. const captureChoice = new type(`Untitled ${typeName} Choice`);
  13495. this.addCommandToMacro(new NestedChoiceCommand(captureChoice));
  13496. });
  13497. }
  13498. addCommandToMacro(command) {
  13499. this.macro.commands.push(command);
  13500. this.commandListEl.updateCommandList(this.macro.commands);
  13501. }
  13502. }
  13503. class QuickAddMacro {
  13504. constructor(name) {
  13505. this.name = name;
  13506. this.id = v4();
  13507. this.commands = [];
  13508. this.runOnStartup = false;
  13509. }
  13510. }
  13511. class MacrosManager extends obsidian.Modal {
  13512. constructor(app, plugin, macros, choices) {
  13513. super(app);
  13514. this.app = app;
  13515. this.macros = macros;
  13516. this.choices = choices;
  13517. this.plugin = plugin;
  13518. this.waitForClose = new Promise(((resolve, reject) => {
  13519. this.rejectPromise = reject;
  13520. this.resolvePromise = resolve;
  13521. }));
  13522. this.open();
  13523. this.display();
  13524. }
  13525. display() {
  13526. this.contentEl.createEl('h2', { text: 'Macro Manager' }).style.textAlign = "center";
  13527. this.addMacroSettings();
  13528. this.addAddMacroBar();
  13529. }
  13530. addMacroSettings() {
  13531. this.macroContainer = this.contentEl.createDiv();
  13532. this.updateMacroContainer = () => {
  13533. if (this.macros.length <= 1)
  13534. this.macroContainer.className = "macroContainer macroContainer1";
  13535. if (this.macros.length === 2)
  13536. this.macroContainer.className = "macroContainer macroContainer2";
  13537. if (this.macros.length > 2)
  13538. this.macroContainer.className = "macroContainer macroContainer3";
  13539. };
  13540. this.macros.forEach(macro => this.addMacroSetting(macro, this.macroContainer));
  13541. this.updateMacroContainer();
  13542. }
  13543. addMacroSetting(macro, container) {
  13544. const configureMacroContainer = container.createDiv();
  13545. const macroSetting = new obsidian.Setting(configureMacroContainer);
  13546. macroSetting.setName(macro.name);
  13547. macroSetting.infoEl.style.fontWeight = "bold";
  13548. this.addMacroConfigurationItem(configureMacroContainer, itemContainerEl => {
  13549. this.addSpanWithText(itemContainerEl, "Run on plugin load");
  13550. const toggle = new obsidian.ToggleComponent(itemContainerEl);
  13551. toggle.setValue(macro.runOnStartup);
  13552. toggle.onChange(value => {
  13553. macro.runOnStartup = value;
  13554. this.updateMacro(macro);
  13555. });
  13556. });
  13557. configureMacroContainer.addClass("configureMacroDiv");
  13558. this.addMacroConfigurationItem(configureMacroContainer, itemContainerEl => {
  13559. const deleteButton = new obsidian.ButtonComponent(itemContainerEl);
  13560. deleteButton.setClass('mod-warning');
  13561. deleteButton.buttonEl.style.marginRight = "0";
  13562. deleteButton.setButtonText("Delete").onClick(evt => {
  13563. this.macros = this.macros.filter(m => m.id !== macro.id);
  13564. const scroll = this.macroContainer.scrollTop;
  13565. this.reload();
  13566. this.macroContainer.scrollTop = scroll;
  13567. });
  13568. const configureButton = new obsidian.ButtonComponent(itemContainerEl);
  13569. configureButton.setClass('mod-cta');
  13570. configureButton.buttonEl.style.marginRight = "0";
  13571. configureButton.setButtonText("Configure").onClick(async (evt) => {
  13572. const getReachableChoices = (choices) => {
  13573. let reachableChoices = [];
  13574. choices.forEach(choice => {
  13575. if (choice.type === ChoiceType.Multi)
  13576. reachableChoices.push(...getReachableChoices(choice.choices));
  13577. if (choice.type !== ChoiceType.Multi)
  13578. reachableChoices.push(choice);
  13579. });
  13580. return reachableChoices;
  13581. };
  13582. const reachableChoices = getReachableChoices(this.choices);
  13583. const newMacro = await new MacroBuilder(this.app, this.plugin, macro, reachableChoices).waitForClose;
  13584. if (newMacro) {
  13585. this.updateMacro(newMacro);
  13586. this.reload();
  13587. }
  13588. });
  13589. });
  13590. }
  13591. addMacroConfigurationItem(container, callback, classString = "configureMacroDivItem") {
  13592. const item = container.createDiv();
  13593. item.addClass(classString);
  13594. callback(item);
  13595. }
  13596. addSpanWithText(container, text) {
  13597. const configureText = container.createEl('span');
  13598. configureText.setText(text);
  13599. }
  13600. updateMacro(macro) {
  13601. const index = this.macros.findIndex(v => v.id === macro.id);
  13602. this.macros[index] = macro;
  13603. if (this.updateMacroContainer)
  13604. this.updateMacroContainer();
  13605. this.reload();
  13606. }
  13607. reload() {
  13608. this.contentEl.empty();
  13609. this.display();
  13610. }
  13611. addAddMacroBar() {
  13612. const addMacroBarContainer = this.contentEl.createDiv();
  13613. addMacroBarContainer.addClass("addMacroBarContainer");
  13614. const nameInput = new obsidian.TextComponent(addMacroBarContainer);
  13615. nameInput.setPlaceholder("Macro name");
  13616. const addMacroButton = new obsidian.ButtonComponent(addMacroBarContainer);
  13617. addMacroButton.setButtonText("Add macro")
  13618. .setClass("mod-cta")
  13619. .onClick(() => {
  13620. const inputValue = nameInput.getValue();
  13621. if (inputValue !== "" && !this.macros.find(m => m.name === inputValue)) {
  13622. const macro = new QuickAddMacro(inputValue);
  13623. if (!macro) {
  13624. log.logError("macro invalid - will not be added");
  13625. return;
  13626. }
  13627. this.macros.push(macro);
  13628. this.reload();
  13629. this.macroContainer.scrollTo(0, this.macroContainer.scrollHeight);
  13630. }
  13631. });
  13632. }
  13633. onClose() {
  13634. super.onClose();
  13635. this.resolvePromise(this.macros);
  13636. }
  13637. }
  13638. /* src/gui/choiceList/ChoiceView.svelte generated by Svelte v3.47.0 */
  13639. function add_css(target) {
  13640. append_styles(target, "svelte-wcmtyt", ".choiceViewBottomBar.svelte-wcmtyt{display:flex;flex-direction:row;align-items:center;justify-content:space-between;margin-top:1rem}@media(max-width: 800px){.choiceViewBottomBar.svelte-wcmtyt{flex-direction:column}}");
  13641. }
  13642. function create_fragment(ctx) {
  13643. let div1;
  13644. let choicelist;
  13645. let updating_choices;
  13646. let t0;
  13647. let div0;
  13648. let button;
  13649. let t2;
  13650. let addchoicebox;
  13651. let current;
  13652. let mounted;
  13653. let dispose;
  13654. function choicelist_choices_binding(value) {
  13655. /*choicelist_choices_binding*/ ctx[11](value);
  13656. }
  13657. let choicelist_props = { type: "main" };
  13658. if (/*choices*/ ctx[0] !== void 0) {
  13659. choicelist_props.choices = /*choices*/ ctx[0];
  13660. }
  13661. choicelist = new ChoiceList({ props: choicelist_props });
  13662. binding_callbacks.push(() => bind(choicelist, 'choices', choicelist_choices_binding));
  13663. choicelist.$on("deleteChoice", /*deleteChoice*/ ctx[3]);
  13664. choicelist.$on("configureChoice", /*configureChoice*/ ctx[4]);
  13665. choicelist.$on("toggleCommand", /*toggleCommandForChoice*/ ctx[5]);
  13666. choicelist.$on("reorderChoices", /*reorderChoices_handler*/ ctx[12]);
  13667. addchoicebox = new AddChoiceBox({});
  13668. addchoicebox.$on("addChoice", /*addChoiceToList*/ ctx[2]);
  13669. return {
  13670. c() {
  13671. div1 = element("div");
  13672. create_component(choicelist.$$.fragment);
  13673. t0 = space();
  13674. div0 = element("div");
  13675. button = element("button");
  13676. button.textContent = "Manage Macros";
  13677. t2 = space();
  13678. create_component(addchoicebox.$$.fragment);
  13679. attr(button, "class", "mod-cta");
  13680. attr(div0, "class", "choiceViewBottomBar svelte-wcmtyt");
  13681. },
  13682. m(target, anchor) {
  13683. insert(target, div1, anchor);
  13684. mount_component(choicelist, div1, null);
  13685. append(div1, t0);
  13686. append(div1, div0);
  13687. append(div0, button);
  13688. append(div0, t2);
  13689. mount_component(addchoicebox, div0, null);
  13690. current = true;
  13691. if (!mounted) {
  13692. dispose = listen(button, "click", /*openMacroManager*/ ctx[6]);
  13693. mounted = true;
  13694. }
  13695. },
  13696. p(ctx, [dirty]) {
  13697. const choicelist_changes = {};
  13698. if (!updating_choices && dirty & /*choices*/ 1) {
  13699. updating_choices = true;
  13700. choicelist_changes.choices = /*choices*/ ctx[0];
  13701. add_flush_callback(() => updating_choices = false);
  13702. }
  13703. choicelist.$set(choicelist_changes);
  13704. },
  13705. i(local) {
  13706. if (current) return;
  13707. transition_in(choicelist.$$.fragment, local);
  13708. transition_in(addchoicebox.$$.fragment, local);
  13709. current = true;
  13710. },
  13711. o(local) {
  13712. transition_out(choicelist.$$.fragment, local);
  13713. transition_out(addchoicebox.$$.fragment, local);
  13714. current = false;
  13715. },
  13716. d(detaching) {
  13717. if (detaching) detach(div1);
  13718. destroy_component(choicelist);
  13719. destroy_component(addchoicebox);
  13720. mounted = false;
  13721. dispose();
  13722. }
  13723. };
  13724. }
  13725. function instance($$self, $$props, $$invalidate) {
  13726. let { choices = [] } = $$props;
  13727. let { macros = [] } = $$props;
  13728. let { saveChoices } = $$props;
  13729. let { saveMacros } = $$props;
  13730. let { app } = $$props;
  13731. let { plugin } = $$props;
  13732. function addChoiceToList(event) {
  13733. const { name, type } = event.detail;
  13734. switch (type) {
  13735. case ChoiceType.Template:
  13736. const templateChoice = new TemplateChoice(name);
  13737. $$invalidate(0, choices = [...choices, templateChoice]);
  13738. break;
  13739. case ChoiceType.Capture:
  13740. const captureChoice = new CaptureChoice(name);
  13741. $$invalidate(0, choices = [...choices, captureChoice]);
  13742. break;
  13743. case ChoiceType.Macro:
  13744. const macroChoice = new MacroChoice(name);
  13745. $$invalidate(0, choices = [...choices, macroChoice]);
  13746. break;
  13747. case ChoiceType.Multi:
  13748. const multiChoice = new MultiChoice(name);
  13749. $$invalidate(0, choices = [...choices, multiChoice]);
  13750. break;
  13751. }
  13752. saveChoices(choices);
  13753. }
  13754. async function deleteChoice(e) {
  13755. const choice = e.detail.choice;
  13756. const userConfirmed = await GenericYesNoPrompt.Prompt(app, `Confirm deletion of choice`, `Please confirm that you wish to delete '${choice.name}'.
  13757. ${choice.type === ChoiceType.Multi
  13758. ? "Deleting this choice will delete all (" + choice.choices.length + ") choices inside it!"
  13759. : ""}
  13760. `);
  13761. if (userConfirmed) {
  13762. $$invalidate(0, choices = choices.filter(value => deleteChoiceHelper(choice.id, value)));
  13763. plugin.removeCommandForChoice(choice);
  13764. saveChoices(choices);
  13765. }
  13766. }
  13767. function deleteChoiceHelper(id, value) {
  13768. if (value.type === ChoiceType.Multi) {
  13769. value.choices = value.choices.filter(v => deleteChoiceHelper(id, v));
  13770. }
  13771. return value.id !== id;
  13772. }
  13773. async function configureChoice(e) {
  13774. const { choice: oldChoice } = e.detail;
  13775. let updatedChoice;
  13776. if (oldChoice.type === ChoiceType.Multi) {
  13777. updatedChoice = oldChoice;
  13778. const name = await GenericInputPrompt.Prompt(app, `Rename ${oldChoice.name}`, '', oldChoice.name);
  13779. if (!name) return;
  13780. updatedChoice.name = name;
  13781. } else {
  13782. updatedChoice = await getChoiceBuilder(oldChoice).waitForClose;
  13783. }
  13784. if (!updatedChoice) return;
  13785. $$invalidate(0, choices = choices.map(choice => updateChoiceHelper(choice, updatedChoice)));
  13786. saveChoices(choices);
  13787. }
  13788. async function toggleCommandForChoice(e) {
  13789. const { choice: oldChoice } = e.detail;
  13790. const updatedChoice = Object.assign(Object.assign({}, oldChoice), { command: !oldChoice.command });
  13791. updatedChoice.command
  13792. ? plugin.addCommandForChoice(updatedChoice)
  13793. : plugin.removeCommandForChoice(updatedChoice);
  13794. $$invalidate(0, choices = choices.map(choice => updateChoiceHelper(choice, updatedChoice)));
  13795. saveChoices(choices);
  13796. }
  13797. function updateChoiceHelper(oldChoice, newChoice) {
  13798. if (oldChoice.id === newChoice.id) {
  13799. oldChoice = Object.assign(Object.assign({}, oldChoice), newChoice);
  13800. return oldChoice;
  13801. }
  13802. if (oldChoice.type === ChoiceType.Multi) {
  13803. const multiChoice = oldChoice;
  13804. const multiChoiceChoices = multiChoice.choices.map(c => updateChoiceHelper(c, newChoice));
  13805. return Object.assign(Object.assign({}, multiChoice), { choices: multiChoiceChoices });
  13806. }
  13807. return oldChoice;
  13808. }
  13809. function getChoiceBuilder(choice) {
  13810. switch (choice.type) {
  13811. case ChoiceType.Template:
  13812. return new TemplateChoiceBuilder(app, choice, plugin);
  13813. case ChoiceType.Capture:
  13814. return new CaptureChoiceBuilder(app, choice, plugin);
  13815. case ChoiceType.Macro:
  13816. return new MacroChoiceBuilder(app, choice, macros);
  13817. case ChoiceType.Multi:
  13818. }
  13819. }
  13820. async function openMacroManager() {
  13821. const newMacros = await new MacrosManager(app, plugin, macros, choices).waitForClose;
  13822. if (newMacros) {
  13823. saveMacros(newMacros);
  13824. $$invalidate(7, macros = newMacros);
  13825. }
  13826. }
  13827. function choicelist_choices_binding(value) {
  13828. choices = value;
  13829. $$invalidate(0, choices);
  13830. }
  13831. const reorderChoices_handler = e => saveChoices(e.detail.choices);
  13832. $$self.$$set = $$props => {
  13833. if ('choices' in $$props) $$invalidate(0, choices = $$props.choices);
  13834. if ('macros' in $$props) $$invalidate(7, macros = $$props.macros);
  13835. if ('saveChoices' in $$props) $$invalidate(1, saveChoices = $$props.saveChoices);
  13836. if ('saveMacros' in $$props) $$invalidate(8, saveMacros = $$props.saveMacros);
  13837. if ('app' in $$props) $$invalidate(9, app = $$props.app);
  13838. if ('plugin' in $$props) $$invalidate(10, plugin = $$props.plugin);
  13839. };
  13840. return [
  13841. choices,
  13842. saveChoices,
  13843. addChoiceToList,
  13844. deleteChoice,
  13845. configureChoice,
  13846. toggleCommandForChoice,
  13847. openMacroManager,
  13848. macros,
  13849. saveMacros,
  13850. app,
  13851. plugin,
  13852. choicelist_choices_binding,
  13853. reorderChoices_handler
  13854. ];
  13855. }
  13856. class ChoiceView extends SvelteComponent {
  13857. constructor(options) {
  13858. super();
  13859. init(
  13860. this,
  13861. options,
  13862. instance,
  13863. create_fragment,
  13864. safe_not_equal,
  13865. {
  13866. choices: 0,
  13867. macros: 7,
  13868. saveChoices: 1,
  13869. saveMacros: 8,
  13870. app: 9,
  13871. plugin: 10
  13872. },
  13873. add_css
  13874. );
  13875. }
  13876. }
  13877. const DEFAULT_SETTINGS = {
  13878. choices: [],
  13879. macros: [],
  13880. inputPrompt: "single-line"
  13881. };
  13882. class QuickAddSettingsTab extends obsidian.PluginSettingTab {
  13883. constructor(app, plugin) {
  13884. super(app, plugin);
  13885. this.plugin = plugin;
  13886. }
  13887. display() {
  13888. let { containerEl } = this;
  13889. containerEl.empty();
  13890. containerEl.createEl('h2', { text: 'QuickAdd Settings' });
  13891. this.addChoicesSetting();
  13892. new obsidian.Setting(this.containerEl)
  13893. .setName('Use Multi-line Input Prompt')
  13894. .setDesc('Use multi-line input prompt instead of single-line input prompt')
  13895. .addToggle(toggle => toggle
  13896. .setValue(this.plugin.settings.inputPrompt === "multi-line")
  13897. .setTooltip("Use multi-line input prompt")
  13898. .onChange(value => {
  13899. if (value) {
  13900. this.plugin.settings.inputPrompt = "multi-line";
  13901. }
  13902. else {
  13903. this.plugin.settings.inputPrompt = "single-line";
  13904. }
  13905. this.plugin.saveSettings();
  13906. }));
  13907. }
  13908. hide() {
  13909. if (this.choiceView)
  13910. this.choiceView.$destroy();
  13911. }
  13912. addChoicesSetting() {
  13913. const setting = new obsidian.Setting(this.containerEl);
  13914. setting.infoEl.remove();
  13915. setting.settingEl.style.display = "block";
  13916. this.choiceView = new ChoiceView({
  13917. target: setting.settingEl,
  13918. props: {
  13919. app: this.app,
  13920. plugin: this.plugin,
  13921. choices: this.plugin.settings.choices,
  13922. saveChoices: async (choices) => {
  13923. this.plugin.settings.choices = choices;
  13924. await this.plugin.saveSettings();
  13925. },
  13926. macros: this.plugin.settings.macros,
  13927. saveMacros: async (macros) => {
  13928. this.plugin.settings.macros = macros;
  13929. await this.plugin.saveSettings();
  13930. }
  13931. }
  13932. });
  13933. }
  13934. }
  13935. var ErrorLevel;
  13936. (function (ErrorLevel) {
  13937. ErrorLevel["Error"] = "ERROR";
  13938. ErrorLevel["Warning"] = "WARNING";
  13939. ErrorLevel["Log"] = "LOG";
  13940. })(ErrorLevel || (ErrorLevel = {}));
  13941. class QuickAddLogger {
  13942. formatOutputString(error) {
  13943. return `QuickAdd: (${error.level}) ${error.message}`;
  13944. }
  13945. getQuickAddError(message, level) {
  13946. return { message, level, time: Date.now() };
  13947. }
  13948. }
  13949. class ConsoleErrorLogger extends QuickAddLogger {
  13950. constructor() {
  13951. super(...arguments);
  13952. this.ErrorLog = [];
  13953. }
  13954. logError(errorMsg) {
  13955. const error = this.getQuickAddError(errorMsg, ErrorLevel.Error);
  13956. this.addMessageToErrorLog(error);
  13957. console.error(this.formatOutputString(error));
  13958. }
  13959. logWarning(warningMsg) {
  13960. const warning = this.getQuickAddError(warningMsg, ErrorLevel.Warning);
  13961. this.addMessageToErrorLog(warning);
  13962. console.warn(this.formatOutputString(warning));
  13963. }
  13964. logMessage(logMsg) {
  13965. const log = this.getQuickAddError(logMsg, ErrorLevel.Log);
  13966. this.addMessageToErrorLog(log);
  13967. console.log(this.formatOutputString(log));
  13968. }
  13969. addMessageToErrorLog(error) {
  13970. this.ErrorLog.push(error);
  13971. }
  13972. }
  13973. class GuiLogger extends QuickAddLogger {
  13974. constructor(plugin) {
  13975. super();
  13976. this.plugin = plugin;
  13977. }
  13978. logError(msg) {
  13979. const error = this.getQuickAddError(msg, ErrorLevel.Error);
  13980. new obsidian.Notice(this.formatOutputString(error));
  13981. }
  13982. logWarning(msg) {
  13983. const warning = this.getQuickAddError(msg, ErrorLevel.Warning);
  13984. new obsidian.Notice(this.formatOutputString(warning));
  13985. }
  13986. logMessage(msg) { }
  13987. }
  13988. class StartupMacroEngine extends MacroChoiceEngine {
  13989. constructor(app, plugin, macros, choiceExecutor) {
  13990. super(app, plugin, null, macros, choiceExecutor, null);
  13991. }
  13992. async run() {
  13993. this.macros.forEach(macro => {
  13994. if (macro.runOnStartup) {
  13995. this.executeCommands(macro.commands);
  13996. }
  13997. });
  13998. }
  13999. }
  14000. class TemplateChoiceEngine extends TemplateEngine {
  14001. constructor(app, plugin, choice, choiceExecutor) {
  14002. super(app, plugin, choiceExecutor);
  14003. this.choice = choice;
  14004. }
  14005. async run() {
  14006. let folderPath = "";
  14007. if (this.choice.folder.enabled) {
  14008. folderPath = await this.getFolderPath();
  14009. }
  14010. let filePath;
  14011. if (this.choice.fileNameFormat.enabled) {
  14012. filePath = await this.getFormattedFilePath(folderPath, this.choice.fileNameFormat.format, this.choice.name);
  14013. }
  14014. else {
  14015. filePath = await this.getFormattedFilePath(folderPath, VALUE_SYNTAX, this.choice.name);
  14016. }
  14017. if (this.choice.incrementFileName)
  14018. filePath = await this.incrementFileName(filePath);
  14019. let createdFile;
  14020. if (await this.app.vault.adapter.exists(filePath)) {
  14021. const file = this.app.vault.getAbstractFileByPath(filePath);
  14022. if (!(file instanceof obsidian.TFile) || file.extension !== 'md') {
  14023. log.logError(`'${filePath}' already exists and is not a valid markdown file.`);
  14024. return;
  14025. }
  14026. await this.app.workspace.splitActiveLeaf('vertical').openFile(file);
  14027. const userChoice = await GenericSuggester.Suggest(this.app, fileExistsChoices, fileExistsChoices);
  14028. switch (userChoice) {
  14029. case fileExistsAppendToTop:
  14030. createdFile = await this.appendToFileWithTemplate(file, this.choice.templatePath, 'top');
  14031. break;
  14032. case fileExistsAppendToBottom:
  14033. createdFile = await this.appendToFileWithTemplate(file, this.choice.templatePath, 'bottom');
  14034. break;
  14035. case fileExistsOverwriteFile:
  14036. createdFile = await this.overwriteFileWithTemplate(file, this.choice.templatePath);
  14037. break;
  14038. case fileExistsDoNothing:
  14039. default:
  14040. log.logWarning("File not written to.");
  14041. return;
  14042. }
  14043. }
  14044. else {
  14045. createdFile = await this.createFileWithTemplate(filePath, this.choice.templatePath);
  14046. if (!createdFile) {
  14047. log.logWarning(`Could not create file '${filePath}'.`);
  14048. return;
  14049. }
  14050. }
  14051. if (this.choice.appendLink) {
  14052. appendToCurrentLine(this.app.fileManager.generateMarkdownLink(createdFile, ''), this.app);
  14053. }
  14054. if (this.choice.openFile) {
  14055. await openFile(this.app, createdFile, {
  14056. openInNewTab: this.choice.openFileInNewTab.enabled,
  14057. direction: this.choice.openFileInNewTab.direction,
  14058. focus: this.choice.openFileInNewTab.focus,
  14059. mode: this.choice.openFileInMode
  14060. });
  14061. }
  14062. }
  14063. async formatFolderPaths(folders) {
  14064. const folderPaths = await Promise.all(folders.map(async (folder) => {
  14065. return await this.formatter.formatFolderPath(folder);
  14066. }));
  14067. return folderPaths;
  14068. }
  14069. async getFolderPath() {
  14070. var _a, _b;
  14071. let folders = await this.formatFolderPaths([...this.choice.folder.folders]);
  14072. if ((_a = this.choice.folder) === null || _a === void 0 ? void 0 : _a.chooseWhenCreatingNote) {
  14073. const allFoldersInVault = getAllFolderPathsInVault(this.app);
  14074. return await this.getOrCreateFolder(allFoldersInVault);
  14075. }
  14076. if ((_b = this.choice.folder) === null || _b === void 0 ? void 0 : _b.createInSameFolderAsActiveFile) {
  14077. const activeFile = this.app.workspace.getActiveFile();
  14078. if (!activeFile)
  14079. log.logError("No active file. Cannot create new file.");
  14080. return this.getOrCreateFolder([activeFile.parent.path]);
  14081. }
  14082. return await this.getOrCreateFolder(folders);
  14083. }
  14084. }
  14085. class CaptureChoiceFormatter extends CompleteFormatter {
  14086. constructor(app, plugin, choiceExecutor) {
  14087. super(app, plugin, choiceExecutor);
  14088. this.file = null;
  14089. this.fileContent = "";
  14090. }
  14091. async formatContentWithFile(input, choice, fileContent, file) {
  14092. this.choice = choice;
  14093. this.file = file;
  14094. this.fileContent = fileContent;
  14095. if (!choice || !file || fileContent === null)
  14096. return input;
  14097. const formatted = await this.formatFileContent(input);
  14098. const templaterFormatted = templaterParseTemplate(this.app, formatted, this.file);
  14099. if (!templaterFormatted)
  14100. return formatted;
  14101. return templaterFormatted;
  14102. }
  14103. async formatContent(input, choice) {
  14104. this.choice = choice;
  14105. if (!choice)
  14106. return input;
  14107. return await this.formatFileContent(input);
  14108. }
  14109. async formatFileContent(input) {
  14110. let formatted = await super.formatFileContent(input);
  14111. formatted = this.replaceLinebreakInString(formatted);
  14112. const formattedContentIsEmpty = formatted.trim() === "";
  14113. if (formattedContentIsEmpty)
  14114. return this.fileContent;
  14115. if (this.choice.prepend) {
  14116. const shouldInsertLinebreak = !this.choice.task;
  14117. return `${this.fileContent}${shouldInsertLinebreak ? "\n" : ""}${formatted}`;
  14118. }
  14119. if (this.choice.insertAfter.enabled) {
  14120. return await this.insertAfterHandler(formatted);
  14121. }
  14122. const frontmatterEndPosition = this.file ? await this.getFrontmatterEndPosition(this.file) : null;
  14123. if (!frontmatterEndPosition)
  14124. return `${formatted}${this.fileContent}`;
  14125. return this.insertTextAfterPositionInBody(formatted, this.fileContent, frontmatterEndPosition);
  14126. }
  14127. async insertAfterHandler(formatted) {
  14128. var _a, _b;
  14129. const targetString = await this.format(this.choice.insertAfter.after);
  14130. const targetRegex = new RegExp(`\s*${escapeRegExp(targetString.replace('\\n', ''))}\s*`);
  14131. let fileContentLines = getLinesInString(this.fileContent);
  14132. const targetPosition = fileContentLines.findIndex(line => targetRegex.test(line));
  14133. const targetNotFound = targetPosition === -1;
  14134. if (targetNotFound) {
  14135. if ((_a = this.choice.insertAfter) === null || _a === void 0 ? void 0 : _a.createIfNotFound) {
  14136. return await this.createInsertAfterIfNotFound(formatted);
  14137. }
  14138. log.logError("unable to find insert after line in file.");
  14139. }
  14140. if ((_b = this.choice.insertAfter) === null || _b === void 0 ? void 0 : _b.insertAtEnd) {
  14141. const nextHeaderPositionAfterTargetPosition = fileContentLines
  14142. .slice(targetPosition + 1)
  14143. .findIndex(line => (/^#+ |---/).test(line));
  14144. const foundNextHeader = nextHeaderPositionAfterTargetPosition !== -1;
  14145. if (foundNextHeader) {
  14146. let endOfSectionIndex;
  14147. for (let i = nextHeaderPositionAfterTargetPosition + targetPosition; i > targetPosition; i--) {
  14148. const lineIsNewline = (/^[\s\n ]*$/).test(fileContentLines[i]);
  14149. if (!lineIsNewline) {
  14150. endOfSectionIndex = i;
  14151. break;
  14152. }
  14153. }
  14154. if (!endOfSectionIndex)
  14155. endOfSectionIndex = targetPosition;
  14156. return this.insertTextAfterPositionInBody(formatted, this.fileContent, endOfSectionIndex);
  14157. }
  14158. else {
  14159. return this.insertTextAfterPositionInBody(formatted, this.fileContent, fileContentLines.length - 1);
  14160. }
  14161. }
  14162. return this.insertTextAfterPositionInBody(formatted, this.fileContent, targetPosition);
  14163. }
  14164. async createInsertAfterIfNotFound(formatted) {
  14165. var _a, _b;
  14166. const insertAfterLine = this.replaceLinebreakInString(await this.format(this.choice.insertAfter.after));
  14167. const insertAfterLineAndFormatted = `${insertAfterLine}\n${formatted}`;
  14168. if (((_a = this.choice.insertAfter) === null || _a === void 0 ? void 0 : _a.createIfNotFoundLocation) === CREATE_IF_NOT_FOUND_TOP) {
  14169. const frontmatterEndPosition = this.file ? await this.getFrontmatterEndPosition(this.file) : -1;
  14170. return this.insertTextAfterPositionInBody(insertAfterLineAndFormatted, this.fileContent, frontmatterEndPosition);
  14171. }
  14172. if (((_b = this.choice.insertAfter) === null || _b === void 0 ? void 0 : _b.createIfNotFoundLocation) === CREATE_IF_NOT_FOUND_BOTTOM) {
  14173. return `${this.fileContent}\n${insertAfterLineAndFormatted}`;
  14174. }
  14175. }
  14176. async getFrontmatterEndPosition(file) {
  14177. const fileCache = await this.app.metadataCache.getFileCache(file);
  14178. if (!fileCache || !fileCache.frontmatter) {
  14179. log.logMessage("could not get frontmatter. Maybe there isn't any.");
  14180. return -1;
  14181. }
  14182. if (fileCache.frontmatter.position)
  14183. return fileCache.frontmatter.position.end.line;
  14184. return -1;
  14185. }
  14186. insertTextAfterPositionInBody(text, body, pos) {
  14187. if (pos === -1) {
  14188. // For the case that there is no frontmatter and we're adding to the top of the file.
  14189. // We already add a linebreak for the task in CaptureChoiceEngine.tsx in getCapturedContent.
  14190. const shouldAddLinebreak = !this.choice.task;
  14191. return `${text}${shouldAddLinebreak ? "\n" : ""}${body}`;
  14192. }
  14193. const splitContent = body.split("\n");
  14194. const pre = splitContent.slice(0, pos + 1).join("\n");
  14195. const post = splitContent.slice(pos + 1).join("\n");
  14196. return `${pre}\n${text}${post}`;
  14197. }
  14198. }
  14199. class CaptureChoiceEngine extends QuickAddChoiceEngine {
  14200. constructor(app, plugin, choice, choiceExecutor) {
  14201. super(app);
  14202. this.choiceExecutor = choiceExecutor;
  14203. this.choice = choice;
  14204. this.plugin = plugin;
  14205. this.formatter = new CaptureChoiceFormatter(app, plugin, choiceExecutor);
  14206. }
  14207. async run() {
  14208. var _a, _b, _c, _d;
  14209. try {
  14210. if ((_a = this.choice) === null || _a === void 0 ? void 0 : _a.captureToActiveFile) {
  14211. await this.captureToActiveFile();
  14212. return;
  14213. }
  14214. const captureTo = this.choice.captureTo;
  14215. if (!captureTo) {
  14216. log.logError(`Invalid capture to for ${this.choice.name}`);
  14217. return;
  14218. }
  14219. const filePath = await this.getFilePath(captureTo);
  14220. const content = await this.getCaptureContent();
  14221. let getFileAndAddContentFn;
  14222. if (await this.fileExists(filePath)) {
  14223. getFileAndAddContentFn = this.onFileExists;
  14224. }
  14225. else if ((_c = (_b = this.choice) === null || _b === void 0 ? void 0 : _b.createFileIfItDoesntExist) === null || _c === void 0 ? void 0 : _c.enabled) {
  14226. getFileAndAddContentFn = this.onCreateFileIfItDoesntExist;
  14227. }
  14228. else {
  14229. log.logWarning(`The file ${filePath} does not exist and "Create file if it doesn't exist" is disabled.`);
  14230. return;
  14231. }
  14232. const { file, content: newFileContent } = await getFileAndAddContentFn.bind(this)(filePath, content);
  14233. if (this.choice.appendLink) {
  14234. const markdownLink = this.app.fileManager.generateMarkdownLink(file, '');
  14235. appendToCurrentLine(markdownLink, this.app);
  14236. }
  14237. if ((_d = this.choice) === null || _d === void 0 ? void 0 : _d.openFile) {
  14238. await openFile(this.app, file, {
  14239. openInNewTab: this.choice.openFileInNewTab.enabled,
  14240. direction: this.choice.openFileInNewTab.direction,
  14241. focus: this.choice.openFileInNewTab.focus,
  14242. mode: this.choice.openFileInMode
  14243. });
  14244. }
  14245. await this.app.vault.modify(file, newFileContent);
  14246. }
  14247. catch (e) {
  14248. log.logMessage(e);
  14249. }
  14250. }
  14251. async getCaptureContent() {
  14252. let content;
  14253. if (!this.choice.format.enabled)
  14254. content = VALUE_SYNTAX;
  14255. else
  14256. content = this.choice.format.format;
  14257. if (this.choice.task)
  14258. content = `- [ ] ${content}\n`;
  14259. return content;
  14260. }
  14261. async onFileExists(filePath, content) {
  14262. const file = await this.getFileByPath(filePath);
  14263. if (!file)
  14264. return;
  14265. const fileContent = await this.app.vault.read(file);
  14266. const newFileContent = await this.formatter.formatContentWithFile(content, this.choice, fileContent, file);
  14267. return { file, content: newFileContent };
  14268. }
  14269. async onCreateFileIfItDoesntExist(filePath, content) {
  14270. let fileContent = "";
  14271. if (this.choice.createFileIfItDoesntExist.createWithTemplate) {
  14272. const singleTemplateEngine = new SingleTemplateEngine(this.app, this.plugin, this.choice.createFileIfItDoesntExist.template, this.choiceExecutor);
  14273. fileContent = await singleTemplateEngine.run();
  14274. }
  14275. const file = await this.createFileWithInput(filePath, fileContent);
  14276. await replaceTemplaterTemplatesInCreatedFile(this.app, file);
  14277. const updatedFileContent = await this.app.vault.cachedRead(file);
  14278. const newFileContent = await this.formatter.formatContentWithFile(content, this.choice, updatedFileContent, file);
  14279. return { file, content: newFileContent };
  14280. }
  14281. async getFilePath(captureTo) {
  14282. const formattedCaptureTo = await this.formatter.formatFileName(captureTo, this.choice.name);
  14283. return this.formatFilePath("", formattedCaptureTo);
  14284. }
  14285. async captureToActiveFile() {
  14286. const activeFile = this.app.workspace.getActiveFile();
  14287. if (!activeFile) {
  14288. log.logError("Cannot capture to active file - no active file.");
  14289. }
  14290. let content = await this.getCaptureContent();
  14291. content = await this.formatter.formatContent(content, this.choice);
  14292. if (this.choice.format.enabled) {
  14293. content = await templaterParseTemplate(this.app, content, activeFile);
  14294. }
  14295. if (!content)
  14296. return;
  14297. if (this.choice.prepend) {
  14298. const fileContent = await this.app.vault.cachedRead(activeFile);
  14299. const newFileContent = `${fileContent}${content}`;
  14300. await this.app.vault.modify(activeFile, newFileContent);
  14301. }
  14302. else {
  14303. appendToCurrentLine(content, this.app);
  14304. }
  14305. }
  14306. }
  14307. class ChoiceSuggester extends obsidian.FuzzySuggestModal {
  14308. constructor(plugin, choices, choiceExecutor) {
  14309. super(plugin.app);
  14310. this.plugin = plugin;
  14311. this.choices = choices;
  14312. this.choiceExecutor = new ChoiceExecutor(this.app, this.plugin);
  14313. if (choiceExecutor)
  14314. this.choiceExecutor = choiceExecutor;
  14315. }
  14316. static Open(plugin, choices, choiceExecutor) {
  14317. new ChoiceSuggester(plugin, choices, choiceExecutor).open();
  14318. }
  14319. getItemText(item) {
  14320. return item.name;
  14321. }
  14322. getItems() {
  14323. return this.choices;
  14324. }
  14325. async onChooseItem(item, evt) {
  14326. if (item.type === ChoiceType.Multi)
  14327. this.onChooseMultiType(item);
  14328. else
  14329. await this.choiceExecutor.execute(item);
  14330. }
  14331. onChooseMultiType(multi) {
  14332. const choices = [...multi.choices];
  14333. if (multi.name != "← Back")
  14334. choices.push(new MultiChoice("← Back").addChoices(this.choices));
  14335. ChoiceSuggester.Open(this.plugin, choices);
  14336. }
  14337. }
  14338. class ChoiceExecutor {
  14339. constructor(app, plugin) {
  14340. this.app = app;
  14341. this.plugin = plugin;
  14342. this.variables = new Map();
  14343. }
  14344. async execute(choice) {
  14345. switch (choice.type) {
  14346. case ChoiceType.Template:
  14347. const templateChoice = choice;
  14348. await this.onChooseTemplateType(templateChoice);
  14349. break;
  14350. case ChoiceType.Capture:
  14351. const captureChoice = choice;
  14352. await this.onChooseCaptureType(captureChoice);
  14353. break;
  14354. case ChoiceType.Macro:
  14355. const macroChoice = choice;
  14356. await this.onChooseMacroType(macroChoice);
  14357. break;
  14358. case ChoiceType.Multi:
  14359. const multiChoice = choice;
  14360. await this.onChooseMultiType(multiChoice);
  14361. break;
  14362. }
  14363. }
  14364. async onChooseTemplateType(templateChoice) {
  14365. if (!templateChoice.templatePath) {
  14366. log.logError(`please provide a template path for ${templateChoice.name}`);
  14367. return;
  14368. }
  14369. await new TemplateChoiceEngine(this.app, this.plugin, templateChoice, this).run();
  14370. }
  14371. async onChooseCaptureType(captureChoice) {
  14372. if (!captureChoice.captureTo && !(captureChoice === null || captureChoice === void 0 ? void 0 : captureChoice.captureToActiveFile)) {
  14373. log.logError(`please provide a capture path for ${captureChoice.name}`);
  14374. return;
  14375. }
  14376. await new CaptureChoiceEngine(this.app, this.plugin, captureChoice, this).run();
  14377. }
  14378. async onChooseMacroType(macroChoice) {
  14379. const macroEngine = await new MacroChoiceEngine(this.app, this.plugin, macroChoice, this.plugin.settings.macros, this, this.variables);
  14380. await macroEngine.run();
  14381. Object.keys(macroEngine.params.variables).forEach(key => {
  14382. this.variables.set(key, macroEngine.params.variables[key]);
  14383. });
  14384. }
  14385. async onChooseMultiType(multiChoice) {
  14386. ChoiceSuggester.Open(this.plugin, multiChoice.choices, this);
  14387. }
  14388. }
  14389. class QuickAdd extends obsidian.Plugin {
  14390. async onload() {
  14391. console.log('Loading QuickAdd');
  14392. QuickAdd.instance = this;
  14393. await this.loadSettings();
  14394. this.addCommand({
  14395. id: 'runQuickAdd',
  14396. name: 'Run QuickAdd',
  14397. callback: () => {
  14398. ChoiceSuggester.Open(this, this.settings.choices);
  14399. }
  14400. });
  14401. log.register(new ConsoleErrorLogger())
  14402. .register(new GuiLogger(this));
  14403. this.addSettingTab(new QuickAddSettingsTab(this.app, this));
  14404. this.app.workspace.onLayoutReady(() => new StartupMacroEngine(this.app, this, this.settings.macros, new ChoiceExecutor(this.app, this)).run());
  14405. this.addCommandsForChoices(this.settings.choices);
  14406. await this.convertMacroChoicesMacroToId();
  14407. }
  14408. onunload() {
  14409. console.log('Unloading QuickAdd');
  14410. }
  14411. async loadSettings() {
  14412. this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
  14413. }
  14414. async saveSettings() {
  14415. await this.saveData(this.settings);
  14416. }
  14417. addCommandsForChoices(choices) {
  14418. choices.forEach(choice => this.addCommandForChoice(choice));
  14419. }
  14420. addCommandForChoice(choice) {
  14421. if (choice.type === ChoiceType.Multi) {
  14422. this.addCommandsForChoices(choice.choices);
  14423. }
  14424. if (choice.command) {
  14425. this.addCommand({
  14426. id: `choice:${choice.id}`,
  14427. name: choice.name,
  14428. callback: async () => {
  14429. await new ChoiceExecutor(this.app, this).execute(choice);
  14430. }
  14431. });
  14432. }
  14433. }
  14434. getChoiceById(choiceId) {
  14435. return this.getChoice("id", choiceId);
  14436. }
  14437. getChoiceByName(choiceName) {
  14438. return this.getChoice("name", choiceName);
  14439. }
  14440. getChoice(by, targetPropertyValue) {
  14441. let tempChoice;
  14442. const findChoice = (choice) => {
  14443. if (choice[by] === targetPropertyValue) {
  14444. tempChoice = choice;
  14445. return tempChoice;
  14446. }
  14447. if (choice.type === ChoiceType.Multi)
  14448. choice.choices.forEach(findChoice);
  14449. };
  14450. this.settings.choices.forEach(findChoice);
  14451. return tempChoice;
  14452. }
  14453. removeCommandForChoice(choice) {
  14454. deleteObsidianCommand(this.app, `quickadd:choice:${choice.id}`);
  14455. }
  14456. // Did not make sense to have copies of macros in the choices when they are maintained for themselves.
  14457. // Instead we reference by id now. Have to port this over for all users.
  14458. async convertMacroChoicesMacroToId() {
  14459. function convertMacroChoiceMacroToIdHelper(choice) {
  14460. if (choice.type === ChoiceType.Multi) {
  14461. let multiChoice = choice;
  14462. const multiChoices = multiChoice.choices.map(convertMacroChoiceMacroToIdHelper);
  14463. multiChoice = Object.assign(Object.assign({}, multiChoice), { choices: multiChoices });
  14464. return multiChoice;
  14465. }
  14466. if (choice.type !== ChoiceType.Macro)
  14467. return choice;
  14468. const macroChoice = choice;
  14469. if (macroChoice.macro) {
  14470. macroChoice.macroId = macroChoice.macro.id;
  14471. delete macroChoice.macro;
  14472. }
  14473. return macroChoice;
  14474. }
  14475. this.settings.choices = this.settings.choices.map(convertMacroChoiceMacroToIdHelper);
  14476. await this.saveSettings();
  14477. }
  14478. }
  14479. module.exports = QuickAdd;