theme.js 445 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605
  1. /**
  2. * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3. * Licensed under the LGPL or a commercial license.
  4. * For LGPL see License.txt in the project root for license information.
  5. * For commercial licenses see https://www.tiny.cloud/
  6. *
  7. * Version: 5.9.1 (2021-08-27)
  8. */
  9. (function () {
  10. 'use strict';
  11. var __assign = function () {
  12. __assign = Object.assign || function __assign(t) {
  13. for (var s, i = 1, n = arguments.length; i < n; i++) {
  14. s = arguments[i];
  15. for (var p in s)
  16. if (Object.prototype.hasOwnProperty.call(s, p))
  17. t[p] = s[p];
  18. }
  19. return t;
  20. };
  21. return __assign.apply(this, arguments);
  22. };
  23. function __rest(s, e) {
  24. var t = {};
  25. for (var p in s)
  26. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  27. t[p] = s[p];
  28. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  29. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  30. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  31. t[p[i]] = s[p[i]];
  32. }
  33. return t;
  34. }
  35. function __spreadArray(to, from, pack) {
  36. if (pack || arguments.length === 2)
  37. for (var i = 0, l = from.length, ar; i < l; i++) {
  38. if (ar || !(i in from)) {
  39. if (!ar)
  40. ar = Array.prototype.slice.call(from, 0, i);
  41. ar[i] = from[i];
  42. }
  43. }
  44. return to.concat(ar || Array.prototype.slice.call(from));
  45. }
  46. var typeOf = function (x) {
  47. var t = typeof x;
  48. if (x === null) {
  49. return 'null';
  50. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  51. return 'array';
  52. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  53. return 'string';
  54. } else {
  55. return t;
  56. }
  57. };
  58. var isType$1 = function (type) {
  59. return function (value) {
  60. return typeOf(value) === type;
  61. };
  62. };
  63. var isSimpleType = function (type) {
  64. return function (value) {
  65. return typeof value === type;
  66. };
  67. };
  68. var eq$1 = function (t) {
  69. return function (a) {
  70. return t === a;
  71. };
  72. };
  73. var isString = isType$1('string');
  74. var isObject = isType$1('object');
  75. var isArray = isType$1('array');
  76. var isNull = eq$1(null);
  77. var isBoolean = isSimpleType('boolean');
  78. var isUndefined = eq$1(undefined);
  79. var isNullable = function (a) {
  80. return a === null || a === undefined;
  81. };
  82. var isNonNullable = function (a) {
  83. return !isNullable(a);
  84. };
  85. var isFunction = isSimpleType('function');
  86. var isNumber = isSimpleType('number');
  87. var noop = function () {
  88. };
  89. var compose = function (fa, fb) {
  90. return function () {
  91. var args = [];
  92. for (var _i = 0; _i < arguments.length; _i++) {
  93. args[_i] = arguments[_i];
  94. }
  95. return fa(fb.apply(null, args));
  96. };
  97. };
  98. var compose1 = function (fbc, fab) {
  99. return function (a) {
  100. return fbc(fab(a));
  101. };
  102. };
  103. var constant$1 = function (value) {
  104. return function () {
  105. return value;
  106. };
  107. };
  108. var identity = function (x) {
  109. return x;
  110. };
  111. var tripleEquals = function (a, b) {
  112. return a === b;
  113. };
  114. function curry(fn) {
  115. var initialArgs = [];
  116. for (var _i = 1; _i < arguments.length; _i++) {
  117. initialArgs[_i - 1] = arguments[_i];
  118. }
  119. return function () {
  120. var restArgs = [];
  121. for (var _i = 0; _i < arguments.length; _i++) {
  122. restArgs[_i] = arguments[_i];
  123. }
  124. var all = initialArgs.concat(restArgs);
  125. return fn.apply(null, all);
  126. };
  127. }
  128. var not = function (f) {
  129. return function (t) {
  130. return !f(t);
  131. };
  132. };
  133. var die = function (msg) {
  134. return function () {
  135. throw new Error(msg);
  136. };
  137. };
  138. var apply$1 = function (f) {
  139. return f();
  140. };
  141. var never = constant$1(false);
  142. var always = constant$1(true);
  143. var none = function () {
  144. return NONE;
  145. };
  146. var NONE = function () {
  147. var call = function (thunk) {
  148. return thunk();
  149. };
  150. var id = identity;
  151. var me = {
  152. fold: function (n, _s) {
  153. return n();
  154. },
  155. isSome: never,
  156. isNone: always,
  157. getOr: id,
  158. getOrThunk: call,
  159. getOrDie: function (msg) {
  160. throw new Error(msg || 'error: getOrDie called on none.');
  161. },
  162. getOrNull: constant$1(null),
  163. getOrUndefined: constant$1(undefined),
  164. or: id,
  165. orThunk: call,
  166. map: none,
  167. each: noop,
  168. bind: none,
  169. exists: never,
  170. forall: always,
  171. filter: function () {
  172. return none();
  173. },
  174. toArray: function () {
  175. return [];
  176. },
  177. toString: constant$1('none()')
  178. };
  179. return me;
  180. }();
  181. var some = function (a) {
  182. var constant_a = constant$1(a);
  183. var self = function () {
  184. return me;
  185. };
  186. var bind = function (f) {
  187. return f(a);
  188. };
  189. var me = {
  190. fold: function (n, s) {
  191. return s(a);
  192. },
  193. isSome: always,
  194. isNone: never,
  195. getOr: constant_a,
  196. getOrThunk: constant_a,
  197. getOrDie: constant_a,
  198. getOrNull: constant_a,
  199. getOrUndefined: constant_a,
  200. or: self,
  201. orThunk: self,
  202. map: function (f) {
  203. return some(f(a));
  204. },
  205. each: function (f) {
  206. f(a);
  207. },
  208. bind: bind,
  209. exists: bind,
  210. forall: bind,
  211. filter: function (f) {
  212. return f(a) ? me : NONE;
  213. },
  214. toArray: function () {
  215. return [a];
  216. },
  217. toString: function () {
  218. return 'some(' + a + ')';
  219. }
  220. };
  221. return me;
  222. };
  223. var from = function (value) {
  224. return value === null || value === undefined ? NONE : some(value);
  225. };
  226. var Optional = {
  227. some: some,
  228. none: none,
  229. from: from
  230. };
  231. var cached = function (f) {
  232. var called = false;
  233. var r;
  234. return function () {
  235. var args = [];
  236. for (var _i = 0; _i < arguments.length; _i++) {
  237. args[_i] = arguments[_i];
  238. }
  239. if (!called) {
  240. called = true;
  241. r = f.apply(null, args);
  242. }
  243. return r;
  244. };
  245. };
  246. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  247. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  248. var isiPhone = os.isiOS() && !isiPad;
  249. var isMobile = os.isiOS() || os.isAndroid();
  250. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  251. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  252. var isPhone = isiPhone || isMobile && !isTablet;
  253. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  254. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  255. return {
  256. isiPad: constant$1(isiPad),
  257. isiPhone: constant$1(isiPhone),
  258. isTablet: constant$1(isTablet),
  259. isPhone: constant$1(isPhone),
  260. isTouch: constant$1(isTouch),
  261. isAndroid: os.isAndroid,
  262. isiOS: os.isiOS,
  263. isWebView: constant$1(iOSwebview),
  264. isDesktop: constant$1(isDesktop)
  265. };
  266. };
  267. var nativeSlice = Array.prototype.slice;
  268. var nativeIndexOf = Array.prototype.indexOf;
  269. var nativePush = Array.prototype.push;
  270. var rawIndexOf = function (ts, t) {
  271. return nativeIndexOf.call(ts, t);
  272. };
  273. var contains$1 = function (xs, x) {
  274. return rawIndexOf(xs, x) > -1;
  275. };
  276. var exists = function (xs, pred) {
  277. for (var i = 0, len = xs.length; i < len; i++) {
  278. var x = xs[i];
  279. if (pred(x, i)) {
  280. return true;
  281. }
  282. }
  283. return false;
  284. };
  285. var map$2 = function (xs, f) {
  286. var len = xs.length;
  287. var r = new Array(len);
  288. for (var i = 0; i < len; i++) {
  289. var x = xs[i];
  290. r[i] = f(x, i);
  291. }
  292. return r;
  293. };
  294. var each$1 = function (xs, f) {
  295. for (var i = 0, len = xs.length; i < len; i++) {
  296. var x = xs[i];
  297. f(x, i);
  298. }
  299. };
  300. var eachr = function (xs, f) {
  301. for (var i = xs.length - 1; i >= 0; i--) {
  302. var x = xs[i];
  303. f(x, i);
  304. }
  305. };
  306. var filter$2 = function (xs, pred) {
  307. var r = [];
  308. for (var i = 0, len = xs.length; i < len; i++) {
  309. var x = xs[i];
  310. if (pred(x, i)) {
  311. r.push(x);
  312. }
  313. }
  314. return r;
  315. };
  316. var foldr = function (xs, f, acc) {
  317. eachr(xs, function (x, i) {
  318. acc = f(acc, x, i);
  319. });
  320. return acc;
  321. };
  322. var foldl = function (xs, f, acc) {
  323. each$1(xs, function (x, i) {
  324. acc = f(acc, x, i);
  325. });
  326. return acc;
  327. };
  328. var findUntil = function (xs, pred, until) {
  329. for (var i = 0, len = xs.length; i < len; i++) {
  330. var x = xs[i];
  331. if (pred(x, i)) {
  332. return Optional.some(x);
  333. } else if (until(x, i)) {
  334. break;
  335. }
  336. }
  337. return Optional.none();
  338. };
  339. var find$2 = function (xs, pred) {
  340. return findUntil(xs, pred, never);
  341. };
  342. var findIndex$1 = function (xs, pred) {
  343. for (var i = 0, len = xs.length; i < len; i++) {
  344. var x = xs[i];
  345. if (pred(x, i)) {
  346. return Optional.some(i);
  347. }
  348. }
  349. return Optional.none();
  350. };
  351. var flatten = function (xs) {
  352. var r = [];
  353. for (var i = 0, len = xs.length; i < len; ++i) {
  354. if (!isArray(xs[i])) {
  355. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  356. }
  357. nativePush.apply(r, xs[i]);
  358. }
  359. return r;
  360. };
  361. var bind$3 = function (xs, f) {
  362. return flatten(map$2(xs, f));
  363. };
  364. var forall = function (xs, pred) {
  365. for (var i = 0, len = xs.length; i < len; ++i) {
  366. var x = xs[i];
  367. if (pred(x, i) !== true) {
  368. return false;
  369. }
  370. }
  371. return true;
  372. };
  373. var reverse = function (xs) {
  374. var r = nativeSlice.call(xs, 0);
  375. r.reverse();
  376. return r;
  377. };
  378. var difference = function (a1, a2) {
  379. return filter$2(a1, function (x) {
  380. return !contains$1(a2, x);
  381. });
  382. };
  383. var pure$2 = function (x) {
  384. return [x];
  385. };
  386. var sort = function (xs, comparator) {
  387. var copy = nativeSlice.call(xs, 0);
  388. copy.sort(comparator);
  389. return copy;
  390. };
  391. var get$d = function (xs, i) {
  392. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  393. };
  394. var head = function (xs) {
  395. return get$d(xs, 0);
  396. };
  397. var findMap = function (arr, f) {
  398. for (var i = 0; i < arr.length; i++) {
  399. var r = f(arr[i], i);
  400. if (r.isSome()) {
  401. return r;
  402. }
  403. }
  404. return Optional.none();
  405. };
  406. var firstMatch = function (regexes, s) {
  407. for (var i = 0; i < regexes.length; i++) {
  408. var x = regexes[i];
  409. if (x.test(s)) {
  410. return x;
  411. }
  412. }
  413. return undefined;
  414. };
  415. var find$1 = function (regexes, agent) {
  416. var r = firstMatch(regexes, agent);
  417. if (!r) {
  418. return {
  419. major: 0,
  420. minor: 0
  421. };
  422. }
  423. var group = function (i) {
  424. return Number(agent.replace(r, '$' + i));
  425. };
  426. return nu$8(group(1), group(2));
  427. };
  428. var detect$4 = function (versionRegexes, agent) {
  429. var cleanedAgent = String(agent).toLowerCase();
  430. if (versionRegexes.length === 0) {
  431. return unknown$3();
  432. }
  433. return find$1(versionRegexes, cleanedAgent);
  434. };
  435. var unknown$3 = function () {
  436. return nu$8(0, 0);
  437. };
  438. var nu$8 = function (major, minor) {
  439. return {
  440. major: major,
  441. minor: minor
  442. };
  443. };
  444. var Version = {
  445. nu: nu$8,
  446. detect: detect$4,
  447. unknown: unknown$3
  448. };
  449. var detectBrowser$1 = function (browsers, userAgentData) {
  450. return findMap(userAgentData.brands, function (uaBrand) {
  451. var lcBrand = uaBrand.brand.toLowerCase();
  452. return find$2(browsers, function (browser) {
  453. var _a;
  454. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  455. }).map(function (info) {
  456. return {
  457. current: info.name,
  458. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  459. };
  460. });
  461. });
  462. };
  463. var detect$3 = function (candidates, userAgent) {
  464. var agent = String(userAgent).toLowerCase();
  465. return find$2(candidates, function (candidate) {
  466. return candidate.search(agent);
  467. });
  468. };
  469. var detectBrowser = function (browsers, userAgent) {
  470. return detect$3(browsers, userAgent).map(function (browser) {
  471. var version = Version.detect(browser.versionRegexes, userAgent);
  472. return {
  473. current: browser.name,
  474. version: version
  475. };
  476. });
  477. };
  478. var detectOs = function (oses, userAgent) {
  479. return detect$3(oses, userAgent).map(function (os) {
  480. var version = Version.detect(os.versionRegexes, userAgent);
  481. return {
  482. current: os.name,
  483. version: version
  484. };
  485. });
  486. };
  487. var checkRange = function (str, substr, start) {
  488. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  489. };
  490. var supplant = function (str, obj) {
  491. var isStringOrNumber = function (a) {
  492. var t = typeof a;
  493. return t === 'string' || t === 'number';
  494. };
  495. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  496. var value = obj[key];
  497. return isStringOrNumber(value) ? value.toString() : fullMatch;
  498. });
  499. };
  500. var contains = function (str, substr) {
  501. return str.indexOf(substr) !== -1;
  502. };
  503. var endsWith = function (str, suffix) {
  504. return checkRange(str, suffix, str.length - suffix.length);
  505. };
  506. var blank = function (r) {
  507. return function (s) {
  508. return s.replace(r, '');
  509. };
  510. };
  511. var trim = blank(/^\s+|\s+$/g);
  512. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  513. var checkContains = function (target) {
  514. return function (uastring) {
  515. return contains(uastring, target);
  516. };
  517. };
  518. var browsers = [
  519. {
  520. name: 'Edge',
  521. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  522. search: function (uastring) {
  523. return contains(uastring, 'edge/') && contains(uastring, 'chrome') && contains(uastring, 'safari') && contains(uastring, 'applewebkit');
  524. }
  525. },
  526. {
  527. name: 'Chrome',
  528. brand: 'Chromium',
  529. versionRegexes: [
  530. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  531. normalVersionRegex
  532. ],
  533. search: function (uastring) {
  534. return contains(uastring, 'chrome') && !contains(uastring, 'chromeframe');
  535. }
  536. },
  537. {
  538. name: 'IE',
  539. versionRegexes: [
  540. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  541. /.*?rv:([0-9]+)\.([0-9]+).*/
  542. ],
  543. search: function (uastring) {
  544. return contains(uastring, 'msie') || contains(uastring, 'trident');
  545. }
  546. },
  547. {
  548. name: 'Opera',
  549. versionRegexes: [
  550. normalVersionRegex,
  551. /.*?opera\/([0-9]+)\.([0-9]+).*/
  552. ],
  553. search: checkContains('opera')
  554. },
  555. {
  556. name: 'Firefox',
  557. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  558. search: checkContains('firefox')
  559. },
  560. {
  561. name: 'Safari',
  562. versionRegexes: [
  563. normalVersionRegex,
  564. /.*?cpu os ([0-9]+)_([0-9]+).*/
  565. ],
  566. search: function (uastring) {
  567. return (contains(uastring, 'safari') || contains(uastring, 'mobile/')) && contains(uastring, 'applewebkit');
  568. }
  569. }
  570. ];
  571. var oses = [
  572. {
  573. name: 'Windows',
  574. search: checkContains('win'),
  575. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  576. },
  577. {
  578. name: 'iOS',
  579. search: function (uastring) {
  580. return contains(uastring, 'iphone') || contains(uastring, 'ipad');
  581. },
  582. versionRegexes: [
  583. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  584. /.*cpu os ([0-9]+)_([0-9]+).*/,
  585. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  586. ]
  587. },
  588. {
  589. name: 'Android',
  590. search: checkContains('android'),
  591. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  592. },
  593. {
  594. name: 'OSX',
  595. search: checkContains('mac os x'),
  596. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  597. },
  598. {
  599. name: 'Linux',
  600. search: checkContains('linux'),
  601. versionRegexes: []
  602. },
  603. {
  604. name: 'Solaris',
  605. search: checkContains('sunos'),
  606. versionRegexes: []
  607. },
  608. {
  609. name: 'FreeBSD',
  610. search: checkContains('freebsd'),
  611. versionRegexes: []
  612. },
  613. {
  614. name: 'ChromeOS',
  615. search: checkContains('cros'),
  616. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  617. }
  618. ];
  619. var PlatformInfo = {
  620. browsers: constant$1(browsers),
  621. oses: constant$1(oses)
  622. };
  623. var edge = 'Edge';
  624. var chrome = 'Chrome';
  625. var ie = 'IE';
  626. var opera = 'Opera';
  627. var firefox = 'Firefox';
  628. var safari = 'Safari';
  629. var unknown$2 = function () {
  630. return nu$7({
  631. current: undefined,
  632. version: Version.unknown()
  633. });
  634. };
  635. var nu$7 = function (info) {
  636. var current = info.current;
  637. var version = info.version;
  638. var isBrowser = function (name) {
  639. return function () {
  640. return current === name;
  641. };
  642. };
  643. return {
  644. current: current,
  645. version: version,
  646. isEdge: isBrowser(edge),
  647. isChrome: isBrowser(chrome),
  648. isIE: isBrowser(ie),
  649. isOpera: isBrowser(opera),
  650. isFirefox: isBrowser(firefox),
  651. isSafari: isBrowser(safari)
  652. };
  653. };
  654. var Browser = {
  655. unknown: unknown$2,
  656. nu: nu$7,
  657. edge: constant$1(edge),
  658. chrome: constant$1(chrome),
  659. ie: constant$1(ie),
  660. opera: constant$1(opera),
  661. firefox: constant$1(firefox),
  662. safari: constant$1(safari)
  663. };
  664. var windows = 'Windows';
  665. var ios = 'iOS';
  666. var android = 'Android';
  667. var linux = 'Linux';
  668. var osx = 'OSX';
  669. var solaris = 'Solaris';
  670. var freebsd = 'FreeBSD';
  671. var chromeos = 'ChromeOS';
  672. var unknown$1 = function () {
  673. return nu$6({
  674. current: undefined,
  675. version: Version.unknown()
  676. });
  677. };
  678. var nu$6 = function (info) {
  679. var current = info.current;
  680. var version = info.version;
  681. var isOS = function (name) {
  682. return function () {
  683. return current === name;
  684. };
  685. };
  686. return {
  687. current: current,
  688. version: version,
  689. isWindows: isOS(windows),
  690. isiOS: isOS(ios),
  691. isAndroid: isOS(android),
  692. isOSX: isOS(osx),
  693. isLinux: isOS(linux),
  694. isSolaris: isOS(solaris),
  695. isFreeBSD: isOS(freebsd),
  696. isChromeOS: isOS(chromeos)
  697. };
  698. };
  699. var OperatingSystem = {
  700. unknown: unknown$1,
  701. nu: nu$6,
  702. windows: constant$1(windows),
  703. ios: constant$1(ios),
  704. android: constant$1(android),
  705. linux: constant$1(linux),
  706. osx: constant$1(osx),
  707. solaris: constant$1(solaris),
  708. freebsd: constant$1(freebsd),
  709. chromeos: constant$1(chromeos)
  710. };
  711. var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) {
  712. var browsers = PlatformInfo.browsers();
  713. var oses = PlatformInfo.oses();
  714. var browser = userAgentDataOpt.bind(function (userAgentData) {
  715. return detectBrowser$1(browsers, userAgentData);
  716. }).orThunk(function () {
  717. return detectBrowser(browsers, userAgent);
  718. }).fold(Browser.unknown, Browser.nu);
  719. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  720. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  721. return {
  722. browser: browser,
  723. os: os,
  724. deviceType: deviceType
  725. };
  726. };
  727. var PlatformDetection = { detect: detect$2 };
  728. var mediaMatch = function (query) {
  729. return window.matchMedia(query).matches;
  730. };
  731. var platform$1 = cached(function () {
  732. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  733. });
  734. var detect$1 = function () {
  735. return platform$1();
  736. };
  737. var constant = constant$1;
  738. var touchstart = constant('touchstart');
  739. var touchmove = constant('touchmove');
  740. var touchend = constant('touchend');
  741. var mousedown = constant('mousedown');
  742. var mousemove = constant('mousemove');
  743. var mouseup = constant('mouseup');
  744. var mouseover = constant('mouseover');
  745. var keydown = constant('keydown');
  746. var keyup = constant('keyup');
  747. var input$1 = constant('input');
  748. var change = constant('change');
  749. var click = constant('click');
  750. var transitionend = constant('transitionend');
  751. var selectstart = constant('selectstart');
  752. var prefixName = function (name) {
  753. return constant$1('alloy.' + name);
  754. };
  755. var alloy = { tap: prefixName('tap') };
  756. var focus$4 = prefixName('focus');
  757. var postBlur = prefixName('blur.post');
  758. var postPaste = prefixName('paste.post');
  759. var receive$1 = prefixName('receive');
  760. var execute$5 = prefixName('execute');
  761. var focusItem = prefixName('focus.item');
  762. var tap = alloy.tap;
  763. var longpress = prefixName('longpress');
  764. var systemInit = prefixName('system.init');
  765. var attachedToDom = prefixName('system.attached');
  766. var detachedFromDom = prefixName('system.detached');
  767. var focusShifted = prefixName('focusmanager.shifted');
  768. var highlight$1 = prefixName('highlight');
  769. var dehighlight$1 = prefixName('dehighlight');
  770. var emit = function (component, event) {
  771. dispatchWith(component, component.element, event, {});
  772. };
  773. var emitWith = function (component, event, properties) {
  774. dispatchWith(component, component.element, event, properties);
  775. };
  776. var emitExecute = function (component) {
  777. emit(component, execute$5());
  778. };
  779. var dispatch = function (component, target, event) {
  780. dispatchWith(component, target, event, {});
  781. };
  782. var dispatchWith = function (component, target, event, properties) {
  783. var data = __assign({ target: target }, properties);
  784. component.getSystem().triggerEvent(event, target, data);
  785. };
  786. var dispatchEvent = function (component, target, event, simulatedEvent) {
  787. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  788. };
  789. var dispatchFocus = function (component, target) {
  790. component.getSystem().triggerFocus(target, component.element);
  791. };
  792. var DOCUMENT = 9;
  793. var DOCUMENT_FRAGMENT = 11;
  794. var ELEMENT = 1;
  795. var TEXT = 3;
  796. var fromHtml$2 = function (html, scope) {
  797. var doc = scope || document;
  798. var div = doc.createElement('div');
  799. div.innerHTML = html;
  800. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  801. console.error('HTML does not have a single root node', html);
  802. throw new Error('HTML must have a single root node');
  803. }
  804. return fromDom(div.childNodes[0]);
  805. };
  806. var fromTag = function (tag, scope) {
  807. var doc = scope || document;
  808. var node = doc.createElement(tag);
  809. return fromDom(node);
  810. };
  811. var fromText = function (text, scope) {
  812. var doc = scope || document;
  813. var node = doc.createTextNode(text);
  814. return fromDom(node);
  815. };
  816. var fromDom = function (node) {
  817. if (node === null || node === undefined) {
  818. throw new Error('Node cannot be null or undefined');
  819. }
  820. return { dom: node };
  821. };
  822. var fromPoint = function (docElm, x, y) {
  823. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  824. };
  825. var SugarElement = {
  826. fromHtml: fromHtml$2,
  827. fromTag: fromTag,
  828. fromText: fromText,
  829. fromDom: fromDom,
  830. fromPoint: fromPoint
  831. };
  832. var is$1 = function (element, selector) {
  833. var dom = element.dom;
  834. if (dom.nodeType !== ELEMENT) {
  835. return false;
  836. } else {
  837. var elem = dom;
  838. if (elem.matches !== undefined) {
  839. return elem.matches(selector);
  840. } else if (elem.msMatchesSelector !== undefined) {
  841. return elem.msMatchesSelector(selector);
  842. } else if (elem.webkitMatchesSelector !== undefined) {
  843. return elem.webkitMatchesSelector(selector);
  844. } else if (elem.mozMatchesSelector !== undefined) {
  845. return elem.mozMatchesSelector(selector);
  846. } else {
  847. throw new Error('Browser lacks native selectors');
  848. }
  849. }
  850. };
  851. var bypassSelector = function (dom) {
  852. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  853. };
  854. var all$2 = function (selector, scope) {
  855. var base = scope === undefined ? document : scope.dom;
  856. return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  857. };
  858. var one = function (selector, scope) {
  859. var base = scope === undefined ? document : scope.dom;
  860. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  861. };
  862. var eq = function (e1, e2) {
  863. return e1.dom === e2.dom;
  864. };
  865. typeof window !== 'undefined' ? window : Function('return this;')();
  866. var name$1 = function (element) {
  867. var r = element.dom.nodeName;
  868. return r.toLowerCase();
  869. };
  870. var type = function (element) {
  871. return element.dom.nodeType;
  872. };
  873. var isType = function (t) {
  874. return function (element) {
  875. return type(element) === t;
  876. };
  877. };
  878. var isElement = isType(ELEMENT);
  879. var isText = isType(TEXT);
  880. var isDocument = isType(DOCUMENT);
  881. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  882. var owner$2 = function (element) {
  883. return SugarElement.fromDom(element.dom.ownerDocument);
  884. };
  885. var documentOrOwner = function (dos) {
  886. return isDocument(dos) ? dos : owner$2(dos);
  887. };
  888. var defaultView = function (element) {
  889. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  890. };
  891. var parent = function (element) {
  892. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  893. };
  894. var parents = function (element, isRoot) {
  895. var stop = isFunction(isRoot) ? isRoot : never;
  896. var dom = element.dom;
  897. var ret = [];
  898. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  899. var rawParent = dom.parentNode;
  900. var p = SugarElement.fromDom(rawParent);
  901. ret.push(p);
  902. if (stop(p) === true) {
  903. break;
  904. } else {
  905. dom = rawParent;
  906. }
  907. }
  908. return ret;
  909. };
  910. var siblings$2 = function (element) {
  911. var filterSelf = function (elements) {
  912. return filter$2(elements, function (x) {
  913. return !eq(element, x);
  914. });
  915. };
  916. return parent(element).map(children).map(filterSelf).getOr([]);
  917. };
  918. var nextSibling = function (element) {
  919. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  920. };
  921. var children = function (element) {
  922. return map$2(element.dom.childNodes, SugarElement.fromDom);
  923. };
  924. var child = function (element, index) {
  925. var cs = element.dom.childNodes;
  926. return Optional.from(cs[index]).map(SugarElement.fromDom);
  927. };
  928. var firstChild = function (element) {
  929. return child(element, 0);
  930. };
  931. var before$1 = function (marker, element) {
  932. var parent$1 = parent(marker);
  933. parent$1.each(function (v) {
  934. v.dom.insertBefore(element.dom, marker.dom);
  935. });
  936. };
  937. var after$2 = function (marker, element) {
  938. var sibling = nextSibling(marker);
  939. sibling.fold(function () {
  940. var parent$1 = parent(marker);
  941. parent$1.each(function (v) {
  942. append$2(v, element);
  943. });
  944. }, function (v) {
  945. before$1(v, element);
  946. });
  947. };
  948. var prepend$1 = function (parent, element) {
  949. var firstChild$1 = firstChild(parent);
  950. firstChild$1.fold(function () {
  951. append$2(parent, element);
  952. }, function (v) {
  953. parent.dom.insertBefore(element.dom, v.dom);
  954. });
  955. };
  956. var append$2 = function (parent, element) {
  957. parent.dom.appendChild(element.dom);
  958. };
  959. var appendAt = function (parent, element, index) {
  960. child(parent, index).fold(function () {
  961. append$2(parent, element);
  962. }, function (v) {
  963. before$1(v, element);
  964. });
  965. };
  966. var append$1 = function (parent, elements) {
  967. each$1(elements, function (x) {
  968. append$2(parent, x);
  969. });
  970. };
  971. var empty = function (element) {
  972. element.dom.textContent = '';
  973. each$1(children(element), function (rogue) {
  974. remove$7(rogue);
  975. });
  976. };
  977. var remove$7 = function (element) {
  978. var dom = element.dom;
  979. if (dom.parentNode !== null) {
  980. dom.parentNode.removeChild(dom);
  981. }
  982. };
  983. var isShadowRoot = function (dos) {
  984. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  985. };
  986. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  987. var isSupported$1 = constant$1(supported);
  988. var getRootNode = supported ? function (e) {
  989. return SugarElement.fromDom(e.dom.getRootNode());
  990. } : documentOrOwner;
  991. var getShadowRoot = function (e) {
  992. var r = getRootNode(e);
  993. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  994. };
  995. var getShadowHost = function (e) {
  996. return SugarElement.fromDom(e.dom.host);
  997. };
  998. var getOriginalEventTarget = function (event) {
  999. if (isSupported$1() && isNonNullable(event.target)) {
  1000. var el = SugarElement.fromDom(event.target);
  1001. if (isElement(el) && isOpenShadowHost(el)) {
  1002. if (event.composed && event.composedPath) {
  1003. var composedPath = event.composedPath();
  1004. if (composedPath) {
  1005. return head(composedPath);
  1006. }
  1007. }
  1008. }
  1009. }
  1010. return Optional.from(event.target);
  1011. };
  1012. var isOpenShadowHost = function (element) {
  1013. return isNonNullable(element.dom.shadowRoot);
  1014. };
  1015. var inBody = function (element) {
  1016. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1017. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1018. return false;
  1019. }
  1020. var doc = dom.ownerDocument;
  1021. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1022. return doc.body.contains(dom);
  1023. }, compose1(inBody, getShadowHost));
  1024. };
  1025. var body = function () {
  1026. return getBody(SugarElement.fromDom(document));
  1027. };
  1028. var getBody = function (doc) {
  1029. var b = doc.dom.body;
  1030. if (b === null || b === undefined) {
  1031. throw new Error('Body is not available yet');
  1032. }
  1033. return SugarElement.fromDom(b);
  1034. };
  1035. var fireDetaching = function (component) {
  1036. emit(component, detachedFromDom());
  1037. var children = component.components();
  1038. each$1(children, fireDetaching);
  1039. };
  1040. var fireAttaching = function (component) {
  1041. var children = component.components();
  1042. each$1(children, fireAttaching);
  1043. emit(component, attachedToDom());
  1044. };
  1045. var attach$1 = function (parent, child) {
  1046. append$2(parent.element, child.element);
  1047. };
  1048. var detachChildren = function (component) {
  1049. each$1(component.components(), function (childComp) {
  1050. return remove$7(childComp.element);
  1051. });
  1052. empty(component.element);
  1053. component.syncComponents();
  1054. };
  1055. var replaceChildren = function (component, newChildren) {
  1056. var subs = component.components();
  1057. detachChildren(component);
  1058. var deleted = difference(subs, newChildren);
  1059. each$1(deleted, function (comp) {
  1060. fireDetaching(comp);
  1061. component.getSystem().removeFromWorld(comp);
  1062. });
  1063. each$1(newChildren, function (childComp) {
  1064. if (!childComp.getSystem().isConnected()) {
  1065. component.getSystem().addToWorld(childComp);
  1066. attach$1(component, childComp);
  1067. if (inBody(component.element)) {
  1068. fireAttaching(childComp);
  1069. }
  1070. } else {
  1071. attach$1(component, childComp);
  1072. }
  1073. component.syncComponents();
  1074. });
  1075. };
  1076. var attach = function (parent, child) {
  1077. attachWith(parent, child, append$2);
  1078. };
  1079. var attachWith = function (parent, child, insertion) {
  1080. parent.getSystem().addToWorld(child);
  1081. insertion(parent.element, child.element);
  1082. if (inBody(parent.element)) {
  1083. fireAttaching(child);
  1084. }
  1085. parent.syncComponents();
  1086. };
  1087. var doDetach = function (component) {
  1088. fireDetaching(component);
  1089. remove$7(component.element);
  1090. component.getSystem().removeFromWorld(component);
  1091. };
  1092. var detach = function (component) {
  1093. var parent$1 = parent(component.element).bind(function (p) {
  1094. return component.getSystem().getByDom(p).toOptional();
  1095. });
  1096. doDetach(component);
  1097. parent$1.each(function (p) {
  1098. p.syncComponents();
  1099. });
  1100. };
  1101. var attachSystemAfter = function (element, guiSystem) {
  1102. attachSystemWith(element, guiSystem, after$2);
  1103. };
  1104. var attachSystemWith = function (element, guiSystem, inserter) {
  1105. inserter(element, guiSystem.element);
  1106. var children$1 = children(guiSystem.element);
  1107. each$1(children$1, function (child) {
  1108. guiSystem.getByDom(child).each(fireAttaching);
  1109. });
  1110. };
  1111. var detachSystem = function (guiSystem) {
  1112. var children$1 = children(guiSystem.element);
  1113. each$1(children$1, function (child) {
  1114. guiSystem.getByDom(child).each(fireDetaching);
  1115. });
  1116. remove$7(guiSystem.element);
  1117. };
  1118. var keys = Object.keys;
  1119. var hasOwnProperty = Object.hasOwnProperty;
  1120. var each = function (obj, f) {
  1121. var props = keys(obj);
  1122. for (var k = 0, len = props.length; k < len; k++) {
  1123. var i = props[k];
  1124. var x = obj[i];
  1125. f(x, i);
  1126. }
  1127. };
  1128. var map$1 = function (obj, f) {
  1129. return tupleMap(obj, function (x, i) {
  1130. return {
  1131. k: i,
  1132. v: f(x, i)
  1133. };
  1134. });
  1135. };
  1136. var tupleMap = function (obj, f) {
  1137. var r = {};
  1138. each(obj, function (x, i) {
  1139. var tuple = f(x, i);
  1140. r[tuple.k] = tuple.v;
  1141. });
  1142. return r;
  1143. };
  1144. var objAcc = function (r) {
  1145. return function (x, i) {
  1146. r[i] = x;
  1147. };
  1148. };
  1149. var internalFilter = function (obj, pred, onTrue, onFalse) {
  1150. var r = {};
  1151. each(obj, function (x, i) {
  1152. (pred(x, i) ? onTrue : onFalse)(x, i);
  1153. });
  1154. return r;
  1155. };
  1156. var filter$1 = function (obj, pred) {
  1157. var t = {};
  1158. internalFilter(obj, pred, objAcc(t), noop);
  1159. return t;
  1160. };
  1161. var mapToArray = function (obj, f) {
  1162. var r = [];
  1163. each(obj, function (value, name) {
  1164. r.push(f(value, name));
  1165. });
  1166. return r;
  1167. };
  1168. var find = function (obj, pred) {
  1169. var props = keys(obj);
  1170. for (var k = 0, len = props.length; k < len; k++) {
  1171. var i = props[k];
  1172. var x = obj[i];
  1173. if (pred(x, i, obj)) {
  1174. return Optional.some(x);
  1175. }
  1176. }
  1177. return Optional.none();
  1178. };
  1179. var values = function (obj) {
  1180. return mapToArray(obj, identity);
  1181. };
  1182. var get$c = function (obj, key) {
  1183. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  1184. };
  1185. var has$2 = function (obj, key) {
  1186. return hasOwnProperty.call(obj, key);
  1187. };
  1188. var hasNonNullableKey = function (obj, key) {
  1189. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  1190. };
  1191. var rawSet = function (dom, key, value) {
  1192. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1193. dom.setAttribute(key, value + '');
  1194. } else {
  1195. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1196. throw new Error('Attribute value was not simple');
  1197. }
  1198. };
  1199. var set$8 = function (element, key, value) {
  1200. rawSet(element.dom, key, value);
  1201. };
  1202. var setAll$1 = function (element, attrs) {
  1203. var dom = element.dom;
  1204. each(attrs, function (v, k) {
  1205. rawSet(dom, k, v);
  1206. });
  1207. };
  1208. var get$b = function (element, key) {
  1209. var v = element.dom.getAttribute(key);
  1210. return v === null ? undefined : v;
  1211. };
  1212. var getOpt = function (element, key) {
  1213. return Optional.from(get$b(element, key));
  1214. };
  1215. var has$1 = function (element, key) {
  1216. var dom = element.dom;
  1217. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1218. };
  1219. var remove$6 = function (element, key) {
  1220. element.dom.removeAttribute(key);
  1221. };
  1222. var read$2 = function (element, attr) {
  1223. var value = get$b(element, attr);
  1224. return value === undefined || value === '' ? [] : value.split(' ');
  1225. };
  1226. var add$3 = function (element, attr, id) {
  1227. var old = read$2(element, attr);
  1228. var nu = old.concat([id]);
  1229. set$8(element, attr, nu.join(' '));
  1230. return true;
  1231. };
  1232. var remove$5 = function (element, attr, id) {
  1233. var nu = filter$2(read$2(element, attr), function (v) {
  1234. return v !== id;
  1235. });
  1236. if (nu.length > 0) {
  1237. set$8(element, attr, nu.join(' '));
  1238. } else {
  1239. remove$6(element, attr);
  1240. }
  1241. return false;
  1242. };
  1243. var supports = function (element) {
  1244. return element.dom.classList !== undefined;
  1245. };
  1246. var get$a = function (element) {
  1247. return read$2(element, 'class');
  1248. };
  1249. var add$2 = function (element, clazz) {
  1250. return add$3(element, 'class', clazz);
  1251. };
  1252. var remove$4 = function (element, clazz) {
  1253. return remove$5(element, 'class', clazz);
  1254. };
  1255. var add$1 = function (element, clazz) {
  1256. if (supports(element)) {
  1257. element.dom.classList.add(clazz);
  1258. } else {
  1259. add$2(element, clazz);
  1260. }
  1261. };
  1262. var cleanClass = function (element) {
  1263. var classList = supports(element) ? element.dom.classList : get$a(element);
  1264. if (classList.length === 0) {
  1265. remove$6(element, 'class');
  1266. }
  1267. };
  1268. var remove$3 = function (element, clazz) {
  1269. if (supports(element)) {
  1270. var classList = element.dom.classList;
  1271. classList.remove(clazz);
  1272. } else {
  1273. remove$4(element, clazz);
  1274. }
  1275. cleanClass(element);
  1276. };
  1277. var has = function (element, clazz) {
  1278. return supports(element) && element.dom.classList.contains(clazz);
  1279. };
  1280. var swap = function (element, addCls, removeCls) {
  1281. remove$3(element, removeCls);
  1282. add$1(element, addCls);
  1283. };
  1284. var toAlpha = function (component, swapConfig, _swapState) {
  1285. swap(component.element, swapConfig.alpha, swapConfig.omega);
  1286. };
  1287. var toOmega = function (component, swapConfig, _swapState) {
  1288. swap(component.element, swapConfig.omega, swapConfig.alpha);
  1289. };
  1290. var clear$1 = function (component, swapConfig, _swapState) {
  1291. remove$3(component.element, swapConfig.alpha);
  1292. remove$3(component.element, swapConfig.omega);
  1293. };
  1294. var isAlpha = function (component, swapConfig, _swapState) {
  1295. return has(component.element, swapConfig.alpha);
  1296. };
  1297. var isOmega = function (component, swapConfig, _swapState) {
  1298. return has(component.element, swapConfig.omega);
  1299. };
  1300. var SwapApis = /*#__PURE__*/Object.freeze({
  1301. __proto__: null,
  1302. toAlpha: toAlpha,
  1303. toOmega: toOmega,
  1304. isAlpha: isAlpha,
  1305. isOmega: isOmega,
  1306. clear: clear$1
  1307. });
  1308. var value$2 = function (o) {
  1309. var or = function (_opt) {
  1310. return value$2(o);
  1311. };
  1312. var orThunk = function (_f) {
  1313. return value$2(o);
  1314. };
  1315. var map = function (f) {
  1316. return value$2(f(o));
  1317. };
  1318. var mapError = function (_f) {
  1319. return value$2(o);
  1320. };
  1321. var each = function (f) {
  1322. f(o);
  1323. };
  1324. var bind = function (f) {
  1325. return f(o);
  1326. };
  1327. var fold = function (_, onValue) {
  1328. return onValue(o);
  1329. };
  1330. var exists = function (f) {
  1331. return f(o);
  1332. };
  1333. var forall = function (f) {
  1334. return f(o);
  1335. };
  1336. var toOptional = function () {
  1337. return Optional.some(o);
  1338. };
  1339. return {
  1340. isValue: always,
  1341. isError: never,
  1342. getOr: constant$1(o),
  1343. getOrThunk: constant$1(o),
  1344. getOrDie: constant$1(o),
  1345. or: or,
  1346. orThunk: orThunk,
  1347. fold: fold,
  1348. map: map,
  1349. mapError: mapError,
  1350. each: each,
  1351. bind: bind,
  1352. exists: exists,
  1353. forall: forall,
  1354. toOptional: toOptional
  1355. };
  1356. };
  1357. var error = function (message) {
  1358. var getOrThunk = function (f) {
  1359. return f();
  1360. };
  1361. var getOrDie = function () {
  1362. return die(String(message))();
  1363. };
  1364. var or = identity;
  1365. var orThunk = function (f) {
  1366. return f();
  1367. };
  1368. var map = function (_f) {
  1369. return error(message);
  1370. };
  1371. var mapError = function (f) {
  1372. return error(f(message));
  1373. };
  1374. var bind = function (_f) {
  1375. return error(message);
  1376. };
  1377. var fold = function (onError, _) {
  1378. return onError(message);
  1379. };
  1380. return {
  1381. isValue: never,
  1382. isError: always,
  1383. getOr: identity,
  1384. getOrThunk: getOrThunk,
  1385. getOrDie: getOrDie,
  1386. or: or,
  1387. orThunk: orThunk,
  1388. fold: fold,
  1389. map: map,
  1390. mapError: mapError,
  1391. each: noop,
  1392. bind: bind,
  1393. exists: never,
  1394. forall: always,
  1395. toOptional: Optional.none
  1396. };
  1397. };
  1398. var fromOption = function (opt, err) {
  1399. return opt.fold(function () {
  1400. return error(err);
  1401. }, value$2);
  1402. };
  1403. var Result = {
  1404. value: value$2,
  1405. error: error,
  1406. fromOption: fromOption
  1407. };
  1408. var SimpleResultType;
  1409. (function (SimpleResultType) {
  1410. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1411. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1412. }(SimpleResultType || (SimpleResultType = {})));
  1413. var fold$1 = function (res, onError, onValue) {
  1414. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1415. };
  1416. var partition$1 = function (results) {
  1417. var values = [];
  1418. var errors = [];
  1419. each$1(results, function (obj) {
  1420. fold$1(obj, function (err) {
  1421. return errors.push(err);
  1422. }, function (val) {
  1423. return values.push(val);
  1424. });
  1425. });
  1426. return {
  1427. values: values,
  1428. errors: errors
  1429. };
  1430. };
  1431. var mapError = function (res, f) {
  1432. if (res.stype === SimpleResultType.Error) {
  1433. return {
  1434. stype: SimpleResultType.Error,
  1435. serror: f(res.serror)
  1436. };
  1437. } else {
  1438. return res;
  1439. }
  1440. };
  1441. var map = function (res, f) {
  1442. if (res.stype === SimpleResultType.Value) {
  1443. return {
  1444. stype: SimpleResultType.Value,
  1445. svalue: f(res.svalue)
  1446. };
  1447. } else {
  1448. return res;
  1449. }
  1450. };
  1451. var bind$2 = function (res, f) {
  1452. if (res.stype === SimpleResultType.Value) {
  1453. return f(res.svalue);
  1454. } else {
  1455. return res;
  1456. }
  1457. };
  1458. var bindError = function (res, f) {
  1459. if (res.stype === SimpleResultType.Error) {
  1460. return f(res.serror);
  1461. } else {
  1462. return res;
  1463. }
  1464. };
  1465. var svalue = function (v) {
  1466. return {
  1467. stype: SimpleResultType.Value,
  1468. svalue: v
  1469. };
  1470. };
  1471. var serror = function (e) {
  1472. return {
  1473. stype: SimpleResultType.Error,
  1474. serror: e
  1475. };
  1476. };
  1477. var toResult$1 = function (res) {
  1478. return fold$1(res, Result.error, Result.value);
  1479. };
  1480. var fromResult = function (res) {
  1481. return res.fold(serror, svalue);
  1482. };
  1483. var SimpleResult = {
  1484. fromResult: fromResult,
  1485. toResult: toResult$1,
  1486. svalue: svalue,
  1487. partition: partition$1,
  1488. serror: serror,
  1489. bind: bind$2,
  1490. bindError: bindError,
  1491. map: map,
  1492. mapError: mapError,
  1493. fold: fold$1
  1494. };
  1495. var field$3 = function (key, newKey, presence, prop) {
  1496. return {
  1497. tag: 'field',
  1498. key: key,
  1499. newKey: newKey,
  1500. presence: presence,
  1501. prop: prop
  1502. };
  1503. };
  1504. var customField$1 = function (newKey, instantiator) {
  1505. return {
  1506. tag: 'custom',
  1507. newKey: newKey,
  1508. instantiator: instantiator
  1509. };
  1510. };
  1511. var fold = function (value, ifField, ifCustom) {
  1512. switch (value.tag) {
  1513. case 'field':
  1514. return ifField(value.key, value.newKey, value.presence, value.prop);
  1515. case 'custom':
  1516. return ifCustom(value.newKey, value.instantiator);
  1517. }
  1518. };
  1519. var shallow$1 = function (old, nu) {
  1520. return nu;
  1521. };
  1522. var deep = function (old, nu) {
  1523. var bothObjects = isObject(old) && isObject(nu);
  1524. return bothObjects ? deepMerge(old, nu) : nu;
  1525. };
  1526. var baseMerge = function (merger) {
  1527. return function () {
  1528. var objects = [];
  1529. for (var _i = 0; _i < arguments.length; _i++) {
  1530. objects[_i] = arguments[_i];
  1531. }
  1532. if (objects.length === 0) {
  1533. throw new Error('Can\'t merge zero objects');
  1534. }
  1535. var ret = {};
  1536. for (var j = 0; j < objects.length; j++) {
  1537. var curObject = objects[j];
  1538. for (var key in curObject) {
  1539. if (has$2(curObject, key)) {
  1540. ret[key] = merger(ret[key], curObject[key]);
  1541. }
  1542. }
  1543. }
  1544. return ret;
  1545. };
  1546. };
  1547. var deepMerge = baseMerge(deep);
  1548. var merge$1 = baseMerge(shallow$1);
  1549. var required$2 = function () {
  1550. return {
  1551. tag: 'required',
  1552. process: {}
  1553. };
  1554. };
  1555. var defaultedThunk = function (fallbackThunk) {
  1556. return {
  1557. tag: 'defaultedThunk',
  1558. process: fallbackThunk
  1559. };
  1560. };
  1561. var defaulted$1 = function (fallback) {
  1562. return defaultedThunk(constant$1(fallback));
  1563. };
  1564. var asOption = function () {
  1565. return {
  1566. tag: 'option',
  1567. process: {}
  1568. };
  1569. };
  1570. var mergeWithThunk = function (baseThunk) {
  1571. return {
  1572. tag: 'mergeWithThunk',
  1573. process: baseThunk
  1574. };
  1575. };
  1576. var mergeWith = function (base) {
  1577. return mergeWithThunk(constant$1(base));
  1578. };
  1579. var mergeValues$1 = function (values, base) {
  1580. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  1581. };
  1582. var mergeErrors$1 = function (errors) {
  1583. return compose(SimpleResult.serror, flatten)(errors);
  1584. };
  1585. var consolidateObj = function (objects, base) {
  1586. var partition = SimpleResult.partition(objects);
  1587. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1588. };
  1589. var consolidateArr = function (objects) {
  1590. var partitions = SimpleResult.partition(objects);
  1591. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1592. };
  1593. var ResultCombine = {
  1594. consolidateObj: consolidateObj,
  1595. consolidateArr: consolidateArr
  1596. };
  1597. var formatObj = function (input) {
  1598. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1599. };
  1600. var formatErrors = function (errors) {
  1601. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1602. path: [],
  1603. getErrorInfo: constant$1('... (only showing first ten failures)')
  1604. }]) : errors;
  1605. return map$2(es, function (e) {
  1606. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1607. });
  1608. };
  1609. var nu$5 = function (path, getErrorInfo) {
  1610. return SimpleResult.serror([{
  1611. path: path,
  1612. getErrorInfo: getErrorInfo
  1613. }]);
  1614. };
  1615. var missingRequired = function (path, key, obj) {
  1616. return nu$5(path, function () {
  1617. return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
  1618. });
  1619. };
  1620. var missingKey = function (path, key) {
  1621. return nu$5(path, function () {
  1622. return 'Choice schema did not contain choice key: "' + key + '"';
  1623. });
  1624. };
  1625. var missingBranch = function (path, branches, branch) {
  1626. return nu$5(path, function () {
  1627. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1628. });
  1629. };
  1630. var unsupportedFields = function (path, unsupported) {
  1631. return nu$5(path, function () {
  1632. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1633. });
  1634. };
  1635. var custom = function (path, err) {
  1636. return nu$5(path, constant$1(err));
  1637. };
  1638. var value$1 = function (validator) {
  1639. var extract = function (path, val) {
  1640. return SimpleResult.bindError(validator(val), function (err) {
  1641. return custom(path, err);
  1642. });
  1643. };
  1644. var toString = constant$1('val');
  1645. return {
  1646. extract: extract,
  1647. toString: toString
  1648. };
  1649. };
  1650. var anyValue$1 = value$1(SimpleResult.svalue);
  1651. var requiredAccess = function (path, obj, key, bundle) {
  1652. return get$c(obj, key).fold(function () {
  1653. return missingRequired(path, key, obj);
  1654. }, bundle);
  1655. };
  1656. var fallbackAccess = function (obj, key, fallback, bundle) {
  1657. var v = get$c(obj, key).getOrThunk(function () {
  1658. return fallback(obj);
  1659. });
  1660. return bundle(v);
  1661. };
  1662. var optionAccess = function (obj, key, bundle) {
  1663. return bundle(get$c(obj, key));
  1664. };
  1665. var optionDefaultedAccess = function (obj, key, fallback, bundle) {
  1666. var opt = get$c(obj, key).map(function (val) {
  1667. return val === true ? fallback(obj) : val;
  1668. });
  1669. return bundle(opt);
  1670. };
  1671. var extractField = function (field, path, obj, key, prop) {
  1672. var bundle = function (av) {
  1673. return prop.extract(path.concat([key]), av);
  1674. };
  1675. var bundleAsOption = function (optValue) {
  1676. return optValue.fold(function () {
  1677. return SimpleResult.svalue(Optional.none());
  1678. }, function (ov) {
  1679. var result = prop.extract(path.concat([key]), ov);
  1680. return SimpleResult.map(result, Optional.some);
  1681. });
  1682. };
  1683. switch (field.tag) {
  1684. case 'required':
  1685. return requiredAccess(path, obj, key, bundle);
  1686. case 'defaultedThunk':
  1687. return fallbackAccess(obj, key, field.process, bundle);
  1688. case 'option':
  1689. return optionAccess(obj, key, bundleAsOption);
  1690. case 'defaultedOptionThunk':
  1691. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  1692. case 'mergeWithThunk': {
  1693. return fallbackAccess(obj, key, constant$1({}), function (v) {
  1694. var result = deepMerge(field.process(obj), v);
  1695. return bundle(result);
  1696. });
  1697. }
  1698. }
  1699. };
  1700. var extractFields = function (path, obj, fields) {
  1701. var success = {};
  1702. var errors = [];
  1703. for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
  1704. var field = fields_1[_i];
  1705. fold(field, function (key, newKey, presence, prop) {
  1706. var result = extractField(presence, path, obj, key, prop);
  1707. SimpleResult.fold(result, function (err) {
  1708. errors.push.apply(errors, err);
  1709. }, function (res) {
  1710. success[newKey] = res;
  1711. });
  1712. }, function (newKey, instantiator) {
  1713. success[newKey] = instantiator(obj);
  1714. });
  1715. }
  1716. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  1717. };
  1718. var getSetKeys = function (obj) {
  1719. return keys(filter$1(obj, isNonNullable));
  1720. };
  1721. var objOfOnly = function (fields) {
  1722. var delegate = objOf(fields);
  1723. var fieldNames = foldr(fields, function (acc, value) {
  1724. return fold(value, function (key) {
  1725. var _a;
  1726. return deepMerge(acc, (_a = {}, _a[key] = true, _a));
  1727. }, constant$1(acc));
  1728. }, {});
  1729. var extract = function (path, o) {
  1730. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1731. var extra = filter$2(keys, function (k) {
  1732. return !hasNonNullableKey(fieldNames, k);
  1733. });
  1734. return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  1735. };
  1736. return {
  1737. extract: extract,
  1738. toString: delegate.toString
  1739. };
  1740. };
  1741. var objOf = function (values) {
  1742. var extract = function (path, o) {
  1743. return extractFields(path, o, values);
  1744. };
  1745. var toString = function () {
  1746. var fieldStrings = map$2(values, function (value) {
  1747. return fold(value, function (key, _okey, _presence, prop) {
  1748. return key + ' -> ' + prop.toString();
  1749. }, function (newKey, _instantiator) {
  1750. return 'state(' + newKey + ')';
  1751. });
  1752. });
  1753. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1754. };
  1755. return {
  1756. extract: extract,
  1757. toString: toString
  1758. };
  1759. };
  1760. var arrOf = function (prop) {
  1761. var extract = function (path, array) {
  1762. var results = map$2(array, function (a, i) {
  1763. return prop.extract(path.concat(['[' + i + ']']), a);
  1764. });
  1765. return ResultCombine.consolidateArr(results);
  1766. };
  1767. var toString = function () {
  1768. return 'array(' + prop.toString() + ')';
  1769. };
  1770. return {
  1771. extract: extract,
  1772. toString: toString
  1773. };
  1774. };
  1775. var setOf$1 = function (validator, prop) {
  1776. var validateKeys = function (path, keys) {
  1777. return arrOf(value$1(validator)).extract(path, keys);
  1778. };
  1779. var extract = function (path, o) {
  1780. var keys$1 = keys(o);
  1781. var validatedKeys = validateKeys(path, keys$1);
  1782. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1783. var schema = map$2(validKeys, function (vk) {
  1784. return field$3(vk, vk, required$2(), prop);
  1785. });
  1786. return objOf(schema).extract(path, o);
  1787. });
  1788. };
  1789. var toString = function () {
  1790. return 'setOf(' + prop.toString() + ')';
  1791. };
  1792. return {
  1793. extract: extract,
  1794. toString: toString
  1795. };
  1796. };
  1797. var anyValue = constant$1(anyValue$1);
  1798. var typedValue = function (validator, expectedType) {
  1799. return value$1(function (a) {
  1800. var actualType = typeof a;
  1801. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1802. });
  1803. };
  1804. var functionProcessor = typedValue(isFunction, 'function');
  1805. var chooseFrom = function (path, input, branches, ch) {
  1806. var fields = get$c(branches, ch);
  1807. return fields.fold(function () {
  1808. return missingBranch(path, branches, ch);
  1809. }, function (vp) {
  1810. return vp.extract(path.concat(['branch: ' + ch]), input);
  1811. });
  1812. };
  1813. var choose$2 = function (key, branches) {
  1814. var extract = function (path, input) {
  1815. var choice = get$c(input, key);
  1816. return choice.fold(function () {
  1817. return missingKey(path, key);
  1818. }, function (chosen) {
  1819. return chooseFrom(path, input, branches, chosen);
  1820. });
  1821. };
  1822. var toString = function () {
  1823. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1824. };
  1825. return {
  1826. extract: extract,
  1827. toString: toString
  1828. };
  1829. };
  1830. var valueOf = function (validator) {
  1831. return value$1(function (v) {
  1832. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1833. });
  1834. };
  1835. var setOf = function (validator, prop) {
  1836. return setOf$1(function (v) {
  1837. return SimpleResult.fromResult(validator(v));
  1838. }, prop);
  1839. };
  1840. var extractValue = function (label, prop, obj) {
  1841. var res = prop.extract([label], obj);
  1842. return SimpleResult.mapError(res, function (errs) {
  1843. return {
  1844. input: obj,
  1845. errors: errs
  1846. };
  1847. });
  1848. };
  1849. var asRaw = function (label, prop, obj) {
  1850. return SimpleResult.toResult(extractValue(label, prop, obj));
  1851. };
  1852. var getOrDie = function (extraction) {
  1853. return extraction.fold(function (errInfo) {
  1854. throw new Error(formatError(errInfo));
  1855. }, identity);
  1856. };
  1857. var asRawOrDie$1 = function (label, prop, obj) {
  1858. return getOrDie(asRaw(label, prop, obj));
  1859. };
  1860. var formatError = function (errInfo) {
  1861. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1862. };
  1863. var choose$1 = function (key, branches) {
  1864. return choose$2(key, map$1(branches, objOf));
  1865. };
  1866. var field$2 = field$3;
  1867. var customField = customField$1;
  1868. var required$1 = function (key) {
  1869. return field$2(key, key, required$2(), anyValue());
  1870. };
  1871. var requiredOf = function (key, schema) {
  1872. return field$2(key, key, required$2(), schema);
  1873. };
  1874. var requiredFunction = function (key) {
  1875. return requiredOf(key, functionProcessor);
  1876. };
  1877. var forbid = function (key, message) {
  1878. return field$2(key, key, asOption(), value$1(function (_v) {
  1879. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1880. }));
  1881. };
  1882. var requiredObjOf = function (key, objSchema) {
  1883. return field$2(key, key, required$2(), objOf(objSchema));
  1884. };
  1885. var option = function (key) {
  1886. return field$2(key, key, asOption(), anyValue());
  1887. };
  1888. var optionOf = function (key, schema) {
  1889. return field$2(key, key, asOption(), schema);
  1890. };
  1891. var optionObjOf = function (key, objSchema) {
  1892. return optionOf(key, objOf(objSchema));
  1893. };
  1894. var optionObjOfOnly = function (key, objSchema) {
  1895. return optionOf(key, objOfOnly(objSchema));
  1896. };
  1897. var defaulted = function (key, fallback) {
  1898. return field$2(key, key, defaulted$1(fallback), anyValue());
  1899. };
  1900. var defaultedOf = function (key, fallback, schema) {
  1901. return field$2(key, key, defaulted$1(fallback), schema);
  1902. };
  1903. var defaultedFunction = function (key, fallback) {
  1904. return defaultedOf(key, fallback, functionProcessor);
  1905. };
  1906. var defaultedObjOf = function (key, fallback, objSchema) {
  1907. return defaultedOf(key, fallback, objOf(objSchema));
  1908. };
  1909. var SwapSchema = [
  1910. required$1('alpha'),
  1911. required$1('omega')
  1912. ];
  1913. var generate$5 = function (cases) {
  1914. if (!isArray(cases)) {
  1915. throw new Error('cases must be an array');
  1916. }
  1917. if (cases.length === 0) {
  1918. throw new Error('there must be at least one case');
  1919. }
  1920. var constructors = [];
  1921. var adt = {};
  1922. each$1(cases, function (acase, count) {
  1923. var keys$1 = keys(acase);
  1924. if (keys$1.length !== 1) {
  1925. throw new Error('one and only one name per case');
  1926. }
  1927. var key = keys$1[0];
  1928. var value = acase[key];
  1929. if (adt[key] !== undefined) {
  1930. throw new Error('duplicate key detected:' + key);
  1931. } else if (key === 'cata') {
  1932. throw new Error('cannot have a case named cata (sorry)');
  1933. } else if (!isArray(value)) {
  1934. throw new Error('case arguments must be an array');
  1935. }
  1936. constructors.push(key);
  1937. adt[key] = function () {
  1938. var args = [];
  1939. for (var _i = 0; _i < arguments.length; _i++) {
  1940. args[_i] = arguments[_i];
  1941. }
  1942. var argLength = args.length;
  1943. if (argLength !== value.length) {
  1944. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1945. }
  1946. var match = function (branches) {
  1947. var branchKeys = keys(branches);
  1948. if (constructors.length !== branchKeys.length) {
  1949. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1950. }
  1951. var allReqd = forall(constructors, function (reqKey) {
  1952. return contains$1(branchKeys, reqKey);
  1953. });
  1954. if (!allReqd) {
  1955. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1956. }
  1957. return branches[key].apply(null, args);
  1958. };
  1959. return {
  1960. fold: function () {
  1961. var foldArgs = [];
  1962. for (var _i = 0; _i < arguments.length; _i++) {
  1963. foldArgs[_i] = arguments[_i];
  1964. }
  1965. if (foldArgs.length !== cases.length) {
  1966. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  1967. }
  1968. var target = foldArgs[count];
  1969. return target.apply(null, args);
  1970. },
  1971. match: match,
  1972. log: function (label) {
  1973. console.log(label, {
  1974. constructors: constructors,
  1975. constructor: key,
  1976. params: args
  1977. });
  1978. }
  1979. };
  1980. };
  1981. });
  1982. return adt;
  1983. };
  1984. var Adt = { generate: generate$5 };
  1985. Adt.generate([
  1986. {
  1987. bothErrors: [
  1988. 'error1',
  1989. 'error2'
  1990. ]
  1991. },
  1992. {
  1993. firstError: [
  1994. 'error1',
  1995. 'value2'
  1996. ]
  1997. },
  1998. {
  1999. secondError: [
  2000. 'value1',
  2001. 'error2'
  2002. ]
  2003. },
  2004. {
  2005. bothValues: [
  2006. 'value1',
  2007. 'value2'
  2008. ]
  2009. }
  2010. ]);
  2011. var partition = function (results) {
  2012. var errors = [];
  2013. var values = [];
  2014. each$1(results, function (result) {
  2015. result.fold(function (err) {
  2016. errors.push(err);
  2017. }, function (value) {
  2018. values.push(value);
  2019. });
  2020. });
  2021. return {
  2022. errors: errors,
  2023. values: values
  2024. };
  2025. };
  2026. var exclude$1 = function (obj, fields) {
  2027. var r = {};
  2028. each(obj, function (v, k) {
  2029. if (!contains$1(fields, k)) {
  2030. r[k] = v;
  2031. }
  2032. });
  2033. return r;
  2034. };
  2035. var wrap$1 = function (key, value) {
  2036. var _a;
  2037. return _a = {}, _a[key] = value, _a;
  2038. };
  2039. var wrapAll$1 = function (keyvalues) {
  2040. var r = {};
  2041. each$1(keyvalues, function (kv) {
  2042. r[kv.key] = kv.value;
  2043. });
  2044. return r;
  2045. };
  2046. var exclude = function (obj, fields) {
  2047. return exclude$1(obj, fields);
  2048. };
  2049. var wrap = function (key, value) {
  2050. return wrap$1(key, value);
  2051. };
  2052. var wrapAll = function (keyvalues) {
  2053. return wrapAll$1(keyvalues);
  2054. };
  2055. var mergeValues = function (values, base) {
  2056. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  2057. };
  2058. var mergeErrors = function (errors) {
  2059. return Result.error(flatten(errors));
  2060. };
  2061. var consolidate = function (objs, base) {
  2062. var partitions = partition(objs);
  2063. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2064. };
  2065. var is = function (lhs, rhs, comparator) {
  2066. if (comparator === void 0) {
  2067. comparator = tripleEquals;
  2068. }
  2069. return lhs.exists(function (left) {
  2070. return comparator(left, rhs);
  2071. });
  2072. };
  2073. var cat = function (arr) {
  2074. var r = [];
  2075. var push = function (x) {
  2076. r.push(x);
  2077. };
  2078. for (var i = 0; i < arr.length; i++) {
  2079. arr[i].each(push);
  2080. }
  2081. return r;
  2082. };
  2083. var sequence = function (arr) {
  2084. var r = [];
  2085. for (var i = 0; i < arr.length; i++) {
  2086. var x = arr[i];
  2087. if (x.isSome()) {
  2088. r.push(x.getOrDie());
  2089. } else {
  2090. return Optional.none();
  2091. }
  2092. }
  2093. return Optional.some(r);
  2094. };
  2095. var lift2 = function (oa, ob, f) {
  2096. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  2097. };
  2098. var someIf = function (b, a) {
  2099. return b ? Optional.some(a) : Optional.none();
  2100. };
  2101. var ensureIsRoot = function (isRoot) {
  2102. return isFunction(isRoot) ? isRoot : never;
  2103. };
  2104. var ancestor$2 = function (scope, transform, isRoot) {
  2105. var element = scope.dom;
  2106. var stop = ensureIsRoot(isRoot);
  2107. while (element.parentNode) {
  2108. element = element.parentNode;
  2109. var el = SugarElement.fromDom(element);
  2110. var transformed = transform(el);
  2111. if (transformed.isSome()) {
  2112. return transformed;
  2113. } else if (stop(el)) {
  2114. break;
  2115. }
  2116. }
  2117. return Optional.none();
  2118. };
  2119. var closest$3 = function (scope, transform, isRoot) {
  2120. var current = transform(scope);
  2121. var stop = ensureIsRoot(isRoot);
  2122. return current.orThunk(function () {
  2123. return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop);
  2124. });
  2125. };
  2126. var isSource = function (component, simulatedEvent) {
  2127. return eq(component.element, simulatedEvent.event.target);
  2128. };
  2129. var defaultEventHandler = {
  2130. can: always,
  2131. abort: never,
  2132. run: noop
  2133. };
  2134. var nu$4 = function (parts) {
  2135. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2136. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2137. }
  2138. return __assign(__assign({}, defaultEventHandler), parts);
  2139. };
  2140. var all$1 = function (handlers, f) {
  2141. return function () {
  2142. var args = [];
  2143. for (var _i = 0; _i < arguments.length; _i++) {
  2144. args[_i] = arguments[_i];
  2145. }
  2146. return foldl(handlers, function (acc, handler) {
  2147. return acc && f(handler).apply(undefined, args);
  2148. }, true);
  2149. };
  2150. };
  2151. var any = function (handlers, f) {
  2152. return function () {
  2153. var args = [];
  2154. for (var _i = 0; _i < arguments.length; _i++) {
  2155. args[_i] = arguments[_i];
  2156. }
  2157. return foldl(handlers, function (acc, handler) {
  2158. return acc || f(handler).apply(undefined, args);
  2159. }, false);
  2160. };
  2161. };
  2162. var read$1 = function (handler) {
  2163. return isFunction(handler) ? {
  2164. can: always,
  2165. abort: never,
  2166. run: handler
  2167. } : handler;
  2168. };
  2169. var fuse$1 = function (handlers) {
  2170. var can = all$1(handlers, function (handler) {
  2171. return handler.can;
  2172. });
  2173. var abort = any(handlers, function (handler) {
  2174. return handler.abort;
  2175. });
  2176. var run = function () {
  2177. var args = [];
  2178. for (var _i = 0; _i < arguments.length; _i++) {
  2179. args[_i] = arguments[_i];
  2180. }
  2181. each$1(handlers, function (handler) {
  2182. handler.run.apply(undefined, args);
  2183. });
  2184. };
  2185. return {
  2186. can: can,
  2187. abort: abort,
  2188. run: run
  2189. };
  2190. };
  2191. var derive$3 = function (configs) {
  2192. return wrapAll(configs);
  2193. };
  2194. var abort = function (name, predicate) {
  2195. return {
  2196. key: name,
  2197. value: nu$4({ abort: predicate })
  2198. };
  2199. };
  2200. var can = function (name, predicate) {
  2201. return {
  2202. key: name,
  2203. value: nu$4({ can: predicate })
  2204. };
  2205. };
  2206. var run = function (name, handler) {
  2207. return {
  2208. key: name,
  2209. value: nu$4({ run: handler })
  2210. };
  2211. };
  2212. var runActionExtra = function (name, action, extra) {
  2213. return {
  2214. key: name,
  2215. value: nu$4({
  2216. run: function (component, simulatedEvent) {
  2217. action.apply(undefined, [
  2218. component,
  2219. simulatedEvent
  2220. ].concat(extra));
  2221. }
  2222. })
  2223. };
  2224. };
  2225. var runOnName = function (name) {
  2226. return function (handler) {
  2227. return run(name, handler);
  2228. };
  2229. };
  2230. var runOnSourceName = function (name) {
  2231. return function (handler) {
  2232. return {
  2233. key: name,
  2234. value: nu$4({
  2235. run: function (component, simulatedEvent) {
  2236. if (isSource(component, simulatedEvent)) {
  2237. handler(component, simulatedEvent);
  2238. }
  2239. }
  2240. })
  2241. };
  2242. };
  2243. };
  2244. var redirectToUid = function (name, uid) {
  2245. return run(name, function (component, simulatedEvent) {
  2246. component.getSystem().getByUid(uid).each(function (redirectee) {
  2247. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2248. });
  2249. });
  2250. };
  2251. var redirectToPart = function (name, detail, partName) {
  2252. var uid = detail.partUids[partName];
  2253. return redirectToUid(name, uid);
  2254. };
  2255. var cutter = function (name) {
  2256. return run(name, function (component, simulatedEvent) {
  2257. simulatedEvent.cut();
  2258. });
  2259. };
  2260. var stopper = function (name) {
  2261. return run(name, function (component, simulatedEvent) {
  2262. simulatedEvent.stop();
  2263. });
  2264. };
  2265. var runOnSource = function (name, f) {
  2266. return runOnSourceName(name)(f);
  2267. };
  2268. var runOnAttached = runOnSourceName(attachedToDom());
  2269. var runOnDetached = runOnSourceName(detachedFromDom());
  2270. var runOnInit = runOnSourceName(systemInit());
  2271. var runOnExecute = runOnName(execute$5());
  2272. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2273. var delegate = apiFunction.toString();
  2274. var endIndex = delegate.indexOf(')') + 1;
  2275. var openBracketIndex = delegate.indexOf('(');
  2276. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2277. f.toFunctionAnnotation = function () {
  2278. return {
  2279. name: apiName,
  2280. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2281. };
  2282. };
  2283. return f;
  2284. };
  2285. var cleanParameters = function (parameters) {
  2286. return map$2(parameters, function (p) {
  2287. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2288. });
  2289. };
  2290. var markAsExtraApi = function (f, extraName) {
  2291. var delegate = f.toString();
  2292. var endIndex = delegate.indexOf(')') + 1;
  2293. var openBracketIndex = delegate.indexOf('(');
  2294. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2295. f.toFunctionAnnotation = function () {
  2296. return {
  2297. name: extraName,
  2298. parameters: cleanParameters(parameters)
  2299. };
  2300. };
  2301. return f;
  2302. };
  2303. var markAsSketchApi = function (f, apiFunction) {
  2304. var delegate = apiFunction.toString();
  2305. var endIndex = delegate.indexOf(')') + 1;
  2306. var openBracketIndex = delegate.indexOf('(');
  2307. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2308. f.toFunctionAnnotation = function () {
  2309. return {
  2310. name: 'OVERRIDE',
  2311. parameters: cleanParameters(parameters.slice(1))
  2312. };
  2313. };
  2314. return f;
  2315. };
  2316. var nu$3 = function (s) {
  2317. return {
  2318. classes: isUndefined(s.classes) ? [] : s.classes,
  2319. attributes: isUndefined(s.attributes) ? {} : s.attributes,
  2320. styles: isUndefined(s.styles) ? {} : s.styles
  2321. };
  2322. };
  2323. var merge = function (defnA, mod) {
  2324. return __assign(__assign({}, defnA), {
  2325. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2326. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2327. classes: defnA.classes.concat(mod.classes)
  2328. });
  2329. };
  2330. var executeEvent = function (bConfig, bState, executor) {
  2331. return runOnExecute(function (component) {
  2332. executor(component, bConfig, bState);
  2333. });
  2334. };
  2335. var loadEvent = function (bConfig, bState, f) {
  2336. return runOnInit(function (component, _simulatedEvent) {
  2337. f(component, bConfig, bState);
  2338. });
  2339. };
  2340. var create$6 = function (schema, name, active, apis, extra, state) {
  2341. var configSchema = objOfOnly(schema);
  2342. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2343. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2344. };
  2345. var createModes$1 = function (modes, name, active, apis, extra, state) {
  2346. var configSchema = modes;
  2347. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2348. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2349. };
  2350. var wrapApi = function (bName, apiFunction, apiName) {
  2351. var f = function (component) {
  2352. var rest = [];
  2353. for (var _i = 1; _i < arguments.length; _i++) {
  2354. rest[_i - 1] = arguments[_i];
  2355. }
  2356. var args = [component].concat(rest);
  2357. return component.config({ name: constant$1(bName) }).fold(function () {
  2358. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2359. }, function (info) {
  2360. var rest = Array.prototype.slice.call(args, 1);
  2361. return apiFunction.apply(undefined, [
  2362. component,
  2363. info.config,
  2364. info.state
  2365. ].concat(rest));
  2366. });
  2367. };
  2368. return markAsBehaviourApi(f, apiName, apiFunction);
  2369. };
  2370. var revokeBehaviour = function (name) {
  2371. return {
  2372. key: name,
  2373. value: undefined
  2374. };
  2375. };
  2376. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2377. var getConfig = function (info) {
  2378. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  2379. };
  2380. var wrappedApis = map$1(apis, function (apiF, apiName) {
  2381. return wrapApi(name, apiF, apiName);
  2382. });
  2383. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  2384. return markAsExtraApi(extraF, extraName);
  2385. });
  2386. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2387. revoke: curry(revokeBehaviour, name),
  2388. config: function (spec) {
  2389. var prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  2390. return {
  2391. key: name,
  2392. value: {
  2393. config: prepared,
  2394. me: me,
  2395. configAsRaw: cached(function () {
  2396. return asRawOrDie$1(name + '-config', configSchema, spec);
  2397. }),
  2398. initialConfig: spec,
  2399. state: state
  2400. }
  2401. };
  2402. },
  2403. schema: constant$1(schemaSchema),
  2404. exhibit: function (info, base) {
  2405. return lift2(getConfig(info), get$c(active, 'exhibit'), function (behaviourInfo, exhibitor) {
  2406. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2407. }).getOrThunk(function () {
  2408. return nu$3({});
  2409. });
  2410. },
  2411. name: constant$1(name),
  2412. handlers: function (info) {
  2413. return getConfig(info).map(function (behaviourInfo) {
  2414. var getEvents = get$c(active, 'events').getOr(function () {
  2415. return {};
  2416. });
  2417. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2418. }).getOr({});
  2419. }
  2420. });
  2421. return me;
  2422. };
  2423. var NoState = {
  2424. init: function () {
  2425. return nu$2({ readState: constant$1('No State required') });
  2426. }
  2427. };
  2428. var nu$2 = function (spec) {
  2429. return spec;
  2430. };
  2431. var derive$2 = function (capabilities) {
  2432. return wrapAll(capabilities);
  2433. };
  2434. var simpleSchema = objOfOnly([
  2435. required$1('fields'),
  2436. required$1('name'),
  2437. defaulted('active', {}),
  2438. defaulted('apis', {}),
  2439. defaulted('state', NoState),
  2440. defaulted('extra', {})
  2441. ]);
  2442. var create$5 = function (data) {
  2443. var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  2444. return create$6(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2445. };
  2446. var modeSchema = objOfOnly([
  2447. required$1('branchKey'),
  2448. required$1('branches'),
  2449. required$1('name'),
  2450. defaulted('active', {}),
  2451. defaulted('apis', {}),
  2452. defaulted('state', NoState),
  2453. defaulted('extra', {})
  2454. ]);
  2455. var createModes = function (data) {
  2456. var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  2457. return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2458. };
  2459. var revoke = constant$1(undefined);
  2460. var Swapping = create$5({
  2461. fields: SwapSchema,
  2462. name: 'swapping',
  2463. apis: SwapApis
  2464. });
  2465. var Cell = function (initial) {
  2466. var value = initial;
  2467. var get = function () {
  2468. return value;
  2469. };
  2470. var set = function (v) {
  2471. value = v;
  2472. };
  2473. return {
  2474. get: get,
  2475. set: set
  2476. };
  2477. };
  2478. var getDocument = function () {
  2479. return SugarElement.fromDom(document);
  2480. };
  2481. var focus$3 = function (element) {
  2482. return element.dom.focus();
  2483. };
  2484. var blur$1 = function (element) {
  2485. return element.dom.blur();
  2486. };
  2487. var hasFocus = function (element) {
  2488. var root = getRootNode(element).dom;
  2489. return element.dom === root.activeElement;
  2490. };
  2491. var active = function (root) {
  2492. if (root === void 0) {
  2493. root = getDocument();
  2494. }
  2495. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  2496. };
  2497. var search = function (element) {
  2498. return active(getRootNode(element)).filter(function (e) {
  2499. return element.dom.contains(e.dom);
  2500. });
  2501. };
  2502. var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2503. var global$4 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2504. var openLink = function (target) {
  2505. var link = document.createElement('a');
  2506. link.target = '_blank';
  2507. link.href = target.href;
  2508. link.rel = 'noreferrer noopener';
  2509. var nuEvt = document.createEvent('MouseEvents');
  2510. nuEvt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2511. document.body.appendChild(link);
  2512. link.dispatchEvent(nuEvt);
  2513. document.body.removeChild(link);
  2514. };
  2515. var DefaultStyleFormats = [
  2516. {
  2517. title: 'Headings',
  2518. items: [
  2519. {
  2520. title: 'Heading 1',
  2521. format: 'h1'
  2522. },
  2523. {
  2524. title: 'Heading 2',
  2525. format: 'h2'
  2526. },
  2527. {
  2528. title: 'Heading 3',
  2529. format: 'h3'
  2530. },
  2531. {
  2532. title: 'Heading 4',
  2533. format: 'h4'
  2534. },
  2535. {
  2536. title: 'Heading 5',
  2537. format: 'h5'
  2538. },
  2539. {
  2540. title: 'Heading 6',
  2541. format: 'h6'
  2542. }
  2543. ]
  2544. },
  2545. {
  2546. title: 'Inline',
  2547. items: [
  2548. {
  2549. title: 'Bold',
  2550. icon: 'bold',
  2551. format: 'bold'
  2552. },
  2553. {
  2554. title: 'Italic',
  2555. icon: 'italic',
  2556. format: 'italic'
  2557. },
  2558. {
  2559. title: 'Underline',
  2560. icon: 'underline',
  2561. format: 'underline'
  2562. },
  2563. {
  2564. title: 'Strikethrough',
  2565. icon: 'strikethrough',
  2566. format: 'strikethrough'
  2567. },
  2568. {
  2569. title: 'Superscript',
  2570. icon: 'superscript',
  2571. format: 'superscript'
  2572. },
  2573. {
  2574. title: 'Subscript',
  2575. icon: 'subscript',
  2576. format: 'subscript'
  2577. },
  2578. {
  2579. title: 'Code',
  2580. icon: 'code',
  2581. format: 'code'
  2582. }
  2583. ]
  2584. },
  2585. {
  2586. title: 'Blocks',
  2587. items: [
  2588. {
  2589. title: 'Paragraph',
  2590. format: 'p'
  2591. },
  2592. {
  2593. title: 'Blockquote',
  2594. format: 'blockquote'
  2595. },
  2596. {
  2597. title: 'Div',
  2598. format: 'div'
  2599. },
  2600. {
  2601. title: 'Pre',
  2602. format: 'pre'
  2603. }
  2604. ]
  2605. },
  2606. {
  2607. title: 'Alignment',
  2608. items: [
  2609. {
  2610. title: 'Left',
  2611. icon: 'alignleft',
  2612. format: 'alignleft'
  2613. },
  2614. {
  2615. title: 'Center',
  2616. icon: 'aligncenter',
  2617. format: 'aligncenter'
  2618. },
  2619. {
  2620. title: 'Right',
  2621. icon: 'alignright',
  2622. format: 'alignright'
  2623. },
  2624. {
  2625. title: 'Justify',
  2626. icon: 'alignjustify',
  2627. format: 'alignjustify'
  2628. }
  2629. ]
  2630. }
  2631. ];
  2632. var defaults = [
  2633. 'undo',
  2634. 'bold',
  2635. 'italic',
  2636. 'link',
  2637. 'image',
  2638. 'bullist',
  2639. 'styleselect'
  2640. ];
  2641. var isSkinDisabled = function (editor) {
  2642. return editor.getParam('skin') === false;
  2643. };
  2644. var readOnlyOnInit = function (_editor) {
  2645. return false;
  2646. };
  2647. var getToolbar = function (editor) {
  2648. return editor.getParam('toolbar', defaults, 'array');
  2649. };
  2650. var getStyleFormats = function (editor) {
  2651. return editor.getParam('style_formats', DefaultStyleFormats, 'array');
  2652. };
  2653. var getSkinUrl = function (editor) {
  2654. return editor.getParam('skin_url');
  2655. };
  2656. var formatChanged = 'formatChanged';
  2657. var orientationChanged = 'orientationChanged';
  2658. var dropupDismissed = 'dropupDismissed';
  2659. var fromHtml$1 = function (html, scope) {
  2660. var doc = scope || document;
  2661. var div = doc.createElement('div');
  2662. div.innerHTML = html;
  2663. return children(SugarElement.fromDom(div));
  2664. };
  2665. var get$9 = function (element) {
  2666. return element.dom.innerHTML;
  2667. };
  2668. var set$7 = function (element, content) {
  2669. var owner = owner$2(element);
  2670. var docDom = owner.dom;
  2671. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2672. var contentElements = fromHtml$1(content, docDom);
  2673. append$1(fragment, contentElements);
  2674. empty(element);
  2675. append$2(element, fragment);
  2676. };
  2677. var getOuter = function (element) {
  2678. var container = SugarElement.fromTag('div');
  2679. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2680. append$2(container, clone);
  2681. return get$9(container);
  2682. };
  2683. var clone = function (original, isDeep) {
  2684. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2685. };
  2686. var shallow = function (original) {
  2687. return clone(original, false);
  2688. };
  2689. var getHtml = function (element) {
  2690. if (isShadowRoot(element)) {
  2691. return '#shadow-root';
  2692. } else {
  2693. var clone = shallow(element);
  2694. return getOuter(clone);
  2695. }
  2696. };
  2697. var element = function (elem) {
  2698. return getHtml(elem);
  2699. };
  2700. var chooseChannels = function (channels, message) {
  2701. return message.universal ? channels : filter$2(channels, function (ch) {
  2702. return contains$1(message.channels, ch);
  2703. });
  2704. };
  2705. var events$a = function (receiveConfig) {
  2706. return derive$3([run(receive$1(), function (component, message) {
  2707. var channelMap = receiveConfig.channels;
  2708. var channels = keys(channelMap);
  2709. var receivingData = message;
  2710. var targetChannels = chooseChannels(channels, receivingData);
  2711. each$1(targetChannels, function (ch) {
  2712. var channelInfo = channelMap[ch];
  2713. var channelSchema = channelInfo.schema;
  2714. var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  2715. channelInfo.onReceive(component, data);
  2716. });
  2717. })]);
  2718. };
  2719. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2720. __proto__: null,
  2721. events: events$a
  2722. });
  2723. var unknown = 'unknown';
  2724. var EventConfiguration;
  2725. (function (EventConfiguration) {
  2726. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2727. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2728. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2729. }(EventConfiguration || (EventConfiguration = {})));
  2730. var eventConfig = Cell({});
  2731. var makeEventLogger = function (eventName, initialTarget) {
  2732. var sequence = [];
  2733. var startTime = new Date().getTime();
  2734. return {
  2735. logEventCut: function (_name, target, purpose) {
  2736. sequence.push({
  2737. outcome: 'cut',
  2738. target: target,
  2739. purpose: purpose
  2740. });
  2741. },
  2742. logEventStopped: function (_name, target, purpose) {
  2743. sequence.push({
  2744. outcome: 'stopped',
  2745. target: target,
  2746. purpose: purpose
  2747. });
  2748. },
  2749. logNoParent: function (_name, target, purpose) {
  2750. sequence.push({
  2751. outcome: 'no-parent',
  2752. target: target,
  2753. purpose: purpose
  2754. });
  2755. },
  2756. logEventNoHandlers: function (_name, target) {
  2757. sequence.push({
  2758. outcome: 'no-handlers-left',
  2759. target: target
  2760. });
  2761. },
  2762. logEventResponse: function (_name, target, purpose) {
  2763. sequence.push({
  2764. outcome: 'response',
  2765. purpose: purpose,
  2766. target: target
  2767. });
  2768. },
  2769. write: function () {
  2770. var finishTime = new Date().getTime();
  2771. if (contains$1([
  2772. 'mousemove',
  2773. 'mouseover',
  2774. 'mouseout',
  2775. systemInit()
  2776. ], eventName)) {
  2777. return;
  2778. }
  2779. console.log(eventName, {
  2780. event: eventName,
  2781. time: finishTime - startTime,
  2782. target: initialTarget.dom,
  2783. sequence: map$2(sequence, function (s) {
  2784. if (!contains$1([
  2785. 'cut',
  2786. 'stopped',
  2787. 'response'
  2788. ], s.outcome)) {
  2789. return s.outcome;
  2790. } else {
  2791. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2792. }
  2793. })
  2794. });
  2795. }
  2796. };
  2797. };
  2798. var processEvent = function (eventName, initialTarget, f) {
  2799. var status = get$c(eventConfig.get(), eventName).orThunk(function () {
  2800. var patterns = keys(eventConfig.get());
  2801. return findMap(patterns, function (p) {
  2802. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  2803. });
  2804. }).getOr(EventConfiguration.NORMAL);
  2805. switch (status) {
  2806. case EventConfiguration.NORMAL:
  2807. return f(noLogger());
  2808. case EventConfiguration.LOGGING: {
  2809. var logger = makeEventLogger(eventName, initialTarget);
  2810. var output = f(logger);
  2811. logger.write();
  2812. return output;
  2813. }
  2814. case EventConfiguration.STOP:
  2815. return true;
  2816. }
  2817. };
  2818. var path = [
  2819. 'alloy/data/Fields',
  2820. 'alloy/debugging/Debugging'
  2821. ];
  2822. var getTrace = function () {
  2823. var err = new Error();
  2824. if (err.stack !== undefined) {
  2825. var lines = err.stack.split('\n');
  2826. return find$2(lines, function (line) {
  2827. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2828. return line.indexOf(p) > -1;
  2829. });
  2830. }).getOr(unknown);
  2831. } else {
  2832. return unknown;
  2833. }
  2834. };
  2835. var ignoreEvent = {
  2836. logEventCut: noop,
  2837. logEventStopped: noop,
  2838. logNoParent: noop,
  2839. logEventNoHandlers: noop,
  2840. logEventResponse: noop,
  2841. write: noop
  2842. };
  2843. var monitorEvent = function (eventName, initialTarget, f) {
  2844. return processEvent(eventName, initialTarget, f);
  2845. };
  2846. var noLogger = constant$1(ignoreEvent);
  2847. var menuFields = constant$1([
  2848. required$1('menu'),
  2849. required$1('selectedMenu')
  2850. ]);
  2851. var itemFields = constant$1([
  2852. required$1('item'),
  2853. required$1('selectedItem')
  2854. ]);
  2855. constant$1(objOf(itemFields().concat(menuFields())));
  2856. var itemSchema$1 = constant$1(objOf(itemFields()));
  2857. var _initSize = requiredObjOf('initSize', [
  2858. required$1('numColumns'),
  2859. required$1('numRows')
  2860. ]);
  2861. var itemMarkers = function () {
  2862. return requiredOf('markers', itemSchema$1());
  2863. };
  2864. var tieredMenuMarkers = function () {
  2865. return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2866. };
  2867. var markers = function (required) {
  2868. return requiredObjOf('markers', map$2(required, required$1));
  2869. };
  2870. var onPresenceHandler = function (label, fieldName, presence) {
  2871. getTrace();
  2872. return field$2(fieldName, fieldName, presence, valueOf(function (f) {
  2873. return Result.value(function () {
  2874. var args = [];
  2875. for (var _i = 0; _i < arguments.length; _i++) {
  2876. args[_i] = arguments[_i];
  2877. }
  2878. return f.apply(undefined, args);
  2879. });
  2880. }));
  2881. };
  2882. var onHandler = function (fieldName) {
  2883. return onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  2884. };
  2885. var onKeyboardHandler = function (fieldName) {
  2886. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  2887. };
  2888. var onStrictHandler = function (fieldName) {
  2889. return onPresenceHandler('onHandler', fieldName, required$2());
  2890. };
  2891. var onStrictKeyboardHandler = function (fieldName) {
  2892. return onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  2893. };
  2894. var output = function (name, value) {
  2895. return customField(name, constant$1(value));
  2896. };
  2897. var snapshot = function (name) {
  2898. return customField(name, identity);
  2899. };
  2900. var initSize = constant$1(_initSize);
  2901. var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  2902. onStrictHandler('onReceive'),
  2903. defaulted('schema', anyValue())
  2904. ])))];
  2905. var Receiving = create$5({
  2906. fields: ReceivingSchema,
  2907. name: 'receiving',
  2908. active: ActiveReceiving
  2909. });
  2910. var SetupBehaviourCellState = function (initialState) {
  2911. var init = function () {
  2912. var cell = Cell(initialState);
  2913. var get = function () {
  2914. return cell.get();
  2915. };
  2916. var set = function (newState) {
  2917. return cell.set(newState);
  2918. };
  2919. var clear = function () {
  2920. return cell.set(initialState);
  2921. };
  2922. var readState = function () {
  2923. return cell.get();
  2924. };
  2925. return {
  2926. get: get,
  2927. set: set,
  2928. clear: clear,
  2929. readState: readState
  2930. };
  2931. };
  2932. return { init: init };
  2933. };
  2934. var updateAriaState = function (component, toggleConfig, toggleState) {
  2935. var ariaInfo = toggleConfig.aria;
  2936. ariaInfo.update(component, ariaInfo, toggleState.get());
  2937. };
  2938. var updateClass = function (component, toggleConfig, toggleState) {
  2939. toggleConfig.toggleClass.each(function (toggleClass) {
  2940. if (toggleState.get()) {
  2941. add$1(component.element, toggleClass);
  2942. } else {
  2943. remove$3(component.element, toggleClass);
  2944. }
  2945. });
  2946. };
  2947. var toggle = function (component, toggleConfig, toggleState) {
  2948. set$6(component, toggleConfig, toggleState, !toggleState.get());
  2949. };
  2950. var on$1 = function (component, toggleConfig, toggleState) {
  2951. toggleState.set(true);
  2952. updateClass(component, toggleConfig, toggleState);
  2953. updateAriaState(component, toggleConfig, toggleState);
  2954. };
  2955. var off = function (component, toggleConfig, toggleState) {
  2956. toggleState.set(false);
  2957. updateClass(component, toggleConfig, toggleState);
  2958. updateAriaState(component, toggleConfig, toggleState);
  2959. };
  2960. var set$6 = function (component, toggleConfig, toggleState, state) {
  2961. var action = state ? on$1 : off;
  2962. action(component, toggleConfig, toggleState);
  2963. };
  2964. var isOn = function (component, toggleConfig, toggleState) {
  2965. return toggleState.get();
  2966. };
  2967. var onLoad$5 = function (component, toggleConfig, toggleState) {
  2968. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  2969. };
  2970. var ToggleApis = /*#__PURE__*/Object.freeze({
  2971. __proto__: null,
  2972. onLoad: onLoad$5,
  2973. toggle: toggle,
  2974. isOn: isOn,
  2975. on: on$1,
  2976. off: off,
  2977. set: set$6
  2978. });
  2979. var exhibit$5 = function () {
  2980. return nu$3({});
  2981. };
  2982. var events$9 = function (toggleConfig, toggleState) {
  2983. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2984. var load = loadEvent(toggleConfig, toggleState, onLoad$5);
  2985. return derive$3(flatten([
  2986. toggleConfig.toggleOnExecute ? [execute] : [],
  2987. [load]
  2988. ]));
  2989. };
  2990. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2991. __proto__: null,
  2992. exhibit: exhibit$5,
  2993. events: events$9
  2994. });
  2995. var updatePressed = function (component, ariaInfo, status) {
  2996. set$8(component.element, 'aria-pressed', status);
  2997. if (ariaInfo.syncWithExpanded) {
  2998. updateExpanded(component, ariaInfo, status);
  2999. }
  3000. };
  3001. var updateSelected = function (component, ariaInfo, status) {
  3002. set$8(component.element, 'aria-selected', status);
  3003. };
  3004. var updateChecked = function (component, ariaInfo, status) {
  3005. set$8(component.element, 'aria-checked', status);
  3006. };
  3007. var updateExpanded = function (component, ariaInfo, status) {
  3008. set$8(component.element, 'aria-expanded', status);
  3009. };
  3010. var ToggleSchema = [
  3011. defaulted('selected', false),
  3012. option('toggleClass'),
  3013. defaulted('toggleOnExecute', true),
  3014. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  3015. pressed: [
  3016. defaulted('syncWithExpanded', false),
  3017. output('update', updatePressed)
  3018. ],
  3019. checked: [output('update', updateChecked)],
  3020. expanded: [output('update', updateExpanded)],
  3021. selected: [output('update', updateSelected)],
  3022. none: [output('update', noop)]
  3023. }))
  3024. ];
  3025. var Toggling = create$5({
  3026. fields: ToggleSchema,
  3027. name: 'toggling',
  3028. active: ActiveToggle,
  3029. apis: ToggleApis,
  3030. state: SetupBehaviourCellState(false)
  3031. });
  3032. var format = function (command, update) {
  3033. return Receiving.config({
  3034. channels: wrap(formatChanged, {
  3035. onReceive: function (button, data) {
  3036. if (data.command === command) {
  3037. update(button, data.state);
  3038. }
  3039. }
  3040. })
  3041. });
  3042. };
  3043. var orientation = function (onReceive) {
  3044. return Receiving.config({ channels: wrap(orientationChanged, { onReceive: onReceive }) });
  3045. };
  3046. var receive = function (channel, onReceive) {
  3047. return {
  3048. key: channel,
  3049. value: { onReceive: onReceive }
  3050. };
  3051. };
  3052. var prefix$2 = 'tinymce-mobile';
  3053. var resolve = function (p) {
  3054. return prefix$2 + '-' + p;
  3055. };
  3056. var pointerEvents = function () {
  3057. var onClick = function (component, simulatedEvent) {
  3058. simulatedEvent.stop();
  3059. emitExecute(component);
  3060. };
  3061. return [
  3062. run(click(), onClick),
  3063. run(tap(), onClick),
  3064. cutter(touchstart()),
  3065. cutter(mousedown())
  3066. ];
  3067. };
  3068. var events$8 = function (optAction) {
  3069. var executeHandler = function (action) {
  3070. return runOnExecute(function (component, simulatedEvent) {
  3071. action(component);
  3072. simulatedEvent.stop();
  3073. });
  3074. };
  3075. return derive$3(flatten([
  3076. optAction.map(executeHandler).toArray(),
  3077. pointerEvents()
  3078. ]));
  3079. };
  3080. var focus$2 = function (component, focusConfig) {
  3081. if (!focusConfig.ignore) {
  3082. focus$3(component.element);
  3083. focusConfig.onFocus(component);
  3084. }
  3085. };
  3086. var blur = function (component, focusConfig) {
  3087. if (!focusConfig.ignore) {
  3088. blur$1(component.element);
  3089. }
  3090. };
  3091. var isFocused = function (component) {
  3092. return hasFocus(component.element);
  3093. };
  3094. var FocusApis = /*#__PURE__*/Object.freeze({
  3095. __proto__: null,
  3096. focus: focus$2,
  3097. blur: blur,
  3098. isFocused: isFocused
  3099. });
  3100. var exhibit$4 = function (base, focusConfig) {
  3101. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3102. return nu$3(mod);
  3103. };
  3104. var events$7 = function (focusConfig) {
  3105. return derive$3([run(focus$4(), function (component, simulatedEvent) {
  3106. focus$2(component, focusConfig);
  3107. simulatedEvent.stop();
  3108. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3109. simulatedEvent.event.prevent();
  3110. })] : []));
  3111. };
  3112. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3113. __proto__: null,
  3114. exhibit: exhibit$4,
  3115. events: events$7
  3116. });
  3117. var FocusSchema = [
  3118. onHandler('onFocus'),
  3119. defaulted('stopMousedown', false),
  3120. defaulted('ignore', false)
  3121. ];
  3122. var Focusing = create$5({
  3123. fields: FocusSchema,
  3124. name: 'focusing',
  3125. active: ActiveFocus,
  3126. apis: FocusApis
  3127. });
  3128. var isSupported = function (dom) {
  3129. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  3130. };
  3131. var internalSet = function (dom, property, value) {
  3132. if (!isString(value)) {
  3133. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3134. throw new Error('CSS value must be a string: ' + value);
  3135. }
  3136. if (isSupported(dom)) {
  3137. dom.style.setProperty(property, value);
  3138. }
  3139. };
  3140. var internalRemove = function (dom, property) {
  3141. if (isSupported(dom)) {
  3142. dom.style.removeProperty(property);
  3143. }
  3144. };
  3145. var set$5 = function (element, property, value) {
  3146. var dom = element.dom;
  3147. internalSet(dom, property, value);
  3148. };
  3149. var setAll = function (element, css) {
  3150. var dom = element.dom;
  3151. each(css, function (v, k) {
  3152. internalSet(dom, k, v);
  3153. });
  3154. };
  3155. var get$8 = function (element, property) {
  3156. var dom = element.dom;
  3157. var styles = window.getComputedStyle(dom);
  3158. var r = styles.getPropertyValue(property);
  3159. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3160. };
  3161. var getUnsafeProperty = function (dom, property) {
  3162. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  3163. };
  3164. var getRaw = function (element, property) {
  3165. var dom = element.dom;
  3166. var raw = getUnsafeProperty(dom, property);
  3167. return Optional.from(raw).filter(function (r) {
  3168. return r.length > 0;
  3169. });
  3170. };
  3171. var remove$2 = function (element, property) {
  3172. var dom = element.dom;
  3173. internalRemove(dom, property);
  3174. if (is(getOpt(element, 'style').map(trim), '')) {
  3175. remove$6(element, 'style');
  3176. }
  3177. };
  3178. var reflow = function (e) {
  3179. return e.dom.offsetWidth;
  3180. };
  3181. var Dimension = function (name, getOffset) {
  3182. var set = function (element, h) {
  3183. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3184. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3185. }
  3186. var dom = element.dom;
  3187. if (isSupported(dom)) {
  3188. dom.style[name] = h + 'px';
  3189. }
  3190. };
  3191. var get = function (element) {
  3192. var r = getOffset(element);
  3193. if (r <= 0 || r === null) {
  3194. var css = get$8(element, name);
  3195. return parseFloat(css) || 0;
  3196. }
  3197. return r;
  3198. };
  3199. var getOuter = get;
  3200. var aggregate = function (element, properties) {
  3201. return foldl(properties, function (acc, property) {
  3202. var val = get$8(element, property);
  3203. var value = val === undefined ? 0 : parseInt(val, 10);
  3204. return isNaN(value) ? acc : acc + value;
  3205. }, 0);
  3206. };
  3207. var max = function (element, value, properties) {
  3208. var cumulativeInclusions = aggregate(element, properties);
  3209. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3210. return absoluteMax;
  3211. };
  3212. return {
  3213. set: set,
  3214. get: get,
  3215. getOuter: getOuter,
  3216. aggregate: aggregate,
  3217. max: max
  3218. };
  3219. };
  3220. var api$3 = Dimension('height', function (element) {
  3221. var dom = element.dom;
  3222. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3223. });
  3224. var get$7 = function (element) {
  3225. return api$3.get(element);
  3226. };
  3227. var ancestors$1 = function (scope, predicate, isRoot) {
  3228. return filter$2(parents(scope, isRoot), predicate);
  3229. };
  3230. var siblings$1 = function (scope, predicate) {
  3231. return filter$2(siblings$2(scope), predicate);
  3232. };
  3233. var all = function (selector) {
  3234. return all$2(selector);
  3235. };
  3236. var ancestors = function (scope, selector, isRoot) {
  3237. return ancestors$1(scope, function (e) {
  3238. return is$1(e, selector);
  3239. }, isRoot);
  3240. };
  3241. var siblings = function (scope, selector) {
  3242. return siblings$1(scope, function (e) {
  3243. return is$1(e, selector);
  3244. });
  3245. };
  3246. var descendants = function (scope, selector) {
  3247. return all$2(selector, scope);
  3248. };
  3249. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3250. if (is(scope, a)) {
  3251. return Optional.some(scope);
  3252. } else if (isFunction(isRoot) && isRoot(scope)) {
  3253. return Optional.none();
  3254. } else {
  3255. return ancestor(scope, a, isRoot);
  3256. }
  3257. }
  3258. var ancestor$1 = function (scope, predicate, isRoot) {
  3259. var element = scope.dom;
  3260. var stop = isFunction(isRoot) ? isRoot : never;
  3261. while (element.parentNode) {
  3262. element = element.parentNode;
  3263. var el = SugarElement.fromDom(element);
  3264. if (predicate(el)) {
  3265. return Optional.some(el);
  3266. } else if (stop(el)) {
  3267. break;
  3268. }
  3269. }
  3270. return Optional.none();
  3271. };
  3272. var closest$2 = function (scope, predicate, isRoot) {
  3273. var is = function (s, test) {
  3274. return test(s);
  3275. };
  3276. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3277. };
  3278. var descendant$1 = function (scope, predicate) {
  3279. var descend = function (node) {
  3280. for (var i = 0; i < node.childNodes.length; i++) {
  3281. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3282. if (predicate(child_1)) {
  3283. return Optional.some(child_1);
  3284. }
  3285. var res = descend(node.childNodes[i]);
  3286. if (res.isSome()) {
  3287. return res;
  3288. }
  3289. }
  3290. return Optional.none();
  3291. };
  3292. return descend(scope.dom);
  3293. };
  3294. var first$1 = function (selector) {
  3295. return one(selector);
  3296. };
  3297. var ancestor = function (scope, selector, isRoot) {
  3298. return ancestor$1(scope, function (e) {
  3299. return is$1(e, selector);
  3300. }, isRoot);
  3301. };
  3302. var descendant = function (scope, selector) {
  3303. return one(selector, scope);
  3304. };
  3305. var closest$1 = function (scope, selector, isRoot) {
  3306. var is = function (element, selector) {
  3307. return is$1(element, selector);
  3308. };
  3309. return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
  3310. };
  3311. var BACKSPACE = [8];
  3312. var TAB = [9];
  3313. var ENTER = [13];
  3314. var ESCAPE = [27];
  3315. var SPACE = [32];
  3316. var LEFT = [37];
  3317. var UP = [38];
  3318. var RIGHT = [39];
  3319. var DOWN = [40];
  3320. var cyclePrev = function (values, index, predicate) {
  3321. var before = reverse(values.slice(0, index));
  3322. var after = reverse(values.slice(index + 1));
  3323. return find$2(before.concat(after), predicate);
  3324. };
  3325. var tryPrev = function (values, index, predicate) {
  3326. var before = reverse(values.slice(0, index));
  3327. return find$2(before, predicate);
  3328. };
  3329. var cycleNext = function (values, index, predicate) {
  3330. var before = values.slice(0, index);
  3331. var after = values.slice(index + 1);
  3332. return find$2(after.concat(before), predicate);
  3333. };
  3334. var tryNext = function (values, index, predicate) {
  3335. var after = values.slice(index + 1);
  3336. return find$2(after, predicate);
  3337. };
  3338. var inSet = function (keys) {
  3339. return function (event) {
  3340. var raw = event.raw;
  3341. return contains$1(keys, raw.which);
  3342. };
  3343. };
  3344. var and = function (preds) {
  3345. return function (event) {
  3346. return forall(preds, function (pred) {
  3347. return pred(event);
  3348. });
  3349. };
  3350. };
  3351. var isShift = function (event) {
  3352. var raw = event.raw;
  3353. return raw.shiftKey === true;
  3354. };
  3355. var isControl = function (event) {
  3356. var raw = event.raw;
  3357. return raw.ctrlKey === true;
  3358. };
  3359. var isNotShift = not(isShift);
  3360. var rule = function (matches, action) {
  3361. return {
  3362. matches: matches,
  3363. classification: action
  3364. };
  3365. };
  3366. var choose = function (transitions, event) {
  3367. var transition = find$2(transitions, function (t) {
  3368. return t.matches(event);
  3369. });
  3370. return transition.map(function (t) {
  3371. return t.classification;
  3372. });
  3373. };
  3374. var cycleBy = function (value, delta, min, max) {
  3375. var r = value + delta;
  3376. if (r > max) {
  3377. return min;
  3378. } else if (r < min) {
  3379. return max;
  3380. } else {
  3381. return r;
  3382. }
  3383. };
  3384. var clamp = function (value, min, max) {
  3385. return Math.min(Math.max(value, min), max);
  3386. };
  3387. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3388. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  3389. each$1(highlighted, function (h) {
  3390. if (!exists(skip, function (skipComp) {
  3391. return skipComp.element === h;
  3392. })) {
  3393. remove$3(h, hConfig.highlightClass);
  3394. component.getSystem().getByDom(h).each(function (target) {
  3395. hConfig.onDehighlight(component, target);
  3396. emit(target, dehighlight$1());
  3397. });
  3398. }
  3399. });
  3400. };
  3401. var dehighlightAll = function (component, hConfig, hState) {
  3402. return dehighlightAllExcept(component, hConfig, hState, []);
  3403. };
  3404. var dehighlight = function (component, hConfig, hState, target) {
  3405. if (isHighlighted(component, hConfig, hState, target)) {
  3406. remove$3(target.element, hConfig.highlightClass);
  3407. hConfig.onDehighlight(component, target);
  3408. emit(target, dehighlight$1());
  3409. }
  3410. };
  3411. var highlight = function (component, hConfig, hState, target) {
  3412. dehighlightAllExcept(component, hConfig, hState, [target]);
  3413. if (!isHighlighted(component, hConfig, hState, target)) {
  3414. add$1(target.element, hConfig.highlightClass);
  3415. hConfig.onHighlight(component, target);
  3416. emit(target, highlight$1());
  3417. }
  3418. };
  3419. var highlightFirst = function (component, hConfig, hState) {
  3420. getFirst(component, hConfig).each(function (firstComp) {
  3421. highlight(component, hConfig, hState, firstComp);
  3422. });
  3423. };
  3424. var highlightLast = function (component, hConfig, hState) {
  3425. getLast(component, hConfig).each(function (lastComp) {
  3426. highlight(component, hConfig, hState, lastComp);
  3427. });
  3428. };
  3429. var highlightAt = function (component, hConfig, hState, index) {
  3430. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3431. throw err;
  3432. }, function (firstComp) {
  3433. highlight(component, hConfig, hState, firstComp);
  3434. });
  3435. };
  3436. var highlightBy = function (component, hConfig, hState, predicate) {
  3437. var candidates = getCandidates(component, hConfig);
  3438. var targetComp = find$2(candidates, predicate);
  3439. targetComp.each(function (c) {
  3440. highlight(component, hConfig, hState, c);
  3441. });
  3442. };
  3443. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3444. return has(queryTarget.element, hConfig.highlightClass);
  3445. };
  3446. var getHighlighted = function (component, hConfig, _hState) {
  3447. return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  3448. return component.getSystem().getByDom(e).toOptional();
  3449. });
  3450. };
  3451. var getByIndex = function (component, hConfig, hState, index) {
  3452. var items = descendants(component.element, '.' + hConfig.itemClass);
  3453. return Optional.from(items[index]).fold(function () {
  3454. return Result.error(new Error('No element found with index ' + index));
  3455. }, component.getSystem().getByDom);
  3456. };
  3457. var getFirst = function (component, hConfig, _hState) {
  3458. return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) {
  3459. return component.getSystem().getByDom(e).toOptional();
  3460. });
  3461. };
  3462. var getLast = function (component, hConfig, _hState) {
  3463. var items = descendants(component.element, '.' + hConfig.itemClass);
  3464. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  3465. return last.bind(function (c) {
  3466. return component.getSystem().getByDom(c).toOptional();
  3467. });
  3468. };
  3469. var getDelta = function (component, hConfig, hState, delta) {
  3470. var items = descendants(component.element, '.' + hConfig.itemClass);
  3471. var current = findIndex$1(items, function (item) {
  3472. return has(item, hConfig.highlightClass);
  3473. });
  3474. return current.bind(function (selected) {
  3475. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3476. return component.getSystem().getByDom(items[dest]).toOptional();
  3477. });
  3478. };
  3479. var getPrevious = function (component, hConfig, hState) {
  3480. return getDelta(component, hConfig, hState, -1);
  3481. };
  3482. var getNext = function (component, hConfig, hState) {
  3483. return getDelta(component, hConfig, hState, +1);
  3484. };
  3485. var getCandidates = function (component, hConfig, _hState) {
  3486. var items = descendants(component.element, '.' + hConfig.itemClass);
  3487. return cat(map$2(items, function (i) {
  3488. return component.getSystem().getByDom(i).toOptional();
  3489. }));
  3490. };
  3491. var HighlightApis = /*#__PURE__*/Object.freeze({
  3492. __proto__: null,
  3493. dehighlightAll: dehighlightAll,
  3494. dehighlight: dehighlight,
  3495. highlight: highlight,
  3496. highlightFirst: highlightFirst,
  3497. highlightLast: highlightLast,
  3498. highlightAt: highlightAt,
  3499. highlightBy: highlightBy,
  3500. isHighlighted: isHighlighted,
  3501. getHighlighted: getHighlighted,
  3502. getFirst: getFirst,
  3503. getLast: getLast,
  3504. getPrevious: getPrevious,
  3505. getNext: getNext,
  3506. getCandidates: getCandidates
  3507. });
  3508. var HighlightSchema = [
  3509. required$1('highlightClass'),
  3510. required$1('itemClass'),
  3511. onHandler('onHighlight'),
  3512. onHandler('onDehighlight')
  3513. ];
  3514. var Highlighting = create$5({
  3515. fields: HighlightSchema,
  3516. name: 'highlighting',
  3517. apis: HighlightApis
  3518. });
  3519. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3520. var noChange = prevFocus.exists(function (p) {
  3521. return newFocus.exists(function (n) {
  3522. return eq(n, p);
  3523. });
  3524. });
  3525. if (!noChange) {
  3526. emitWith(component, focusShifted(), {
  3527. prevFocus: prevFocus,
  3528. newFocus: newFocus
  3529. });
  3530. }
  3531. };
  3532. var dom$2 = function () {
  3533. var get = function (component) {
  3534. return search(component.element);
  3535. };
  3536. var set = function (component, focusee) {
  3537. var prevFocus = get(component);
  3538. component.getSystem().triggerFocus(focusee, component.element);
  3539. var newFocus = get(component);
  3540. reportFocusShifting(component, prevFocus, newFocus);
  3541. };
  3542. return {
  3543. get: get,
  3544. set: set
  3545. };
  3546. };
  3547. var highlights = function () {
  3548. var get = function (component) {
  3549. return Highlighting.getHighlighted(component).map(function (item) {
  3550. return item.element;
  3551. });
  3552. };
  3553. var set = function (component, element) {
  3554. var prevFocus = get(component);
  3555. component.getSystem().getByDom(element).fold(noop, function (item) {
  3556. Highlighting.highlight(component, item);
  3557. });
  3558. var newFocus = get(component);
  3559. reportFocusShifting(component, prevFocus, newFocus);
  3560. };
  3561. return {
  3562. get: get,
  3563. set: set
  3564. };
  3565. };
  3566. var FocusInsideModes;
  3567. (function (FocusInsideModes) {
  3568. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3569. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3570. FocusInsideModes['OnApiMode'] = 'onApi';
  3571. }(FocusInsideModes || (FocusInsideModes = {})));
  3572. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3573. var schema = function () {
  3574. return infoSchema.concat([
  3575. defaulted('focusManager', dom$2()),
  3576. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3577. return contains$1([
  3578. 'onFocus',
  3579. 'onEnterOrSpace',
  3580. 'onApi'
  3581. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3582. })),
  3583. output('handler', me),
  3584. output('state', stateInit),
  3585. output('sendFocusIn', optFocusIn)
  3586. ]);
  3587. };
  3588. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3589. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3590. return choose(rules, simulatedEvent.event).bind(function (rule) {
  3591. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3592. });
  3593. };
  3594. var toEvents = function (keyingConfig, keyingState) {
  3595. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3596. return run(focus$4(), function (component, simulatedEvent) {
  3597. focusIn(component, keyingConfig, keyingState);
  3598. simulatedEvent.stop();
  3599. });
  3600. });
  3601. var tryGoInsideComponent = function (component, simulatedEvent) {
  3602. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  3603. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3604. optFocusIn(keyingConfig).each(function (focusIn) {
  3605. focusIn(component, keyingConfig, keyingState);
  3606. simulatedEvent.stop();
  3607. });
  3608. }
  3609. };
  3610. var keyboardEvents = [
  3611. run(keydown(), function (component, simulatedEvent) {
  3612. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3613. tryGoInsideComponent(component, simulatedEvent);
  3614. }, function (_) {
  3615. simulatedEvent.stop();
  3616. });
  3617. }),
  3618. run(keyup(), function (component, simulatedEvent) {
  3619. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3620. simulatedEvent.stop();
  3621. });
  3622. })
  3623. ];
  3624. return derive$3(onFocusHandler.toArray().concat(keyboardEvents));
  3625. };
  3626. var me = {
  3627. schema: schema,
  3628. processKey: processKey,
  3629. toEvents: toEvents
  3630. };
  3631. return me;
  3632. };
  3633. var create$4 = function (cyclicField) {
  3634. var schema = [
  3635. option('onEscape'),
  3636. option('onEnter'),
  3637. defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3638. defaulted('firstTabstop', 0),
  3639. defaulted('useTabstopAt', always),
  3640. option('visibilitySelector')
  3641. ].concat([cyclicField]);
  3642. var isVisible = function (tabbingConfig, element) {
  3643. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3644. return closest$1(element, sel);
  3645. }).getOr(element);
  3646. return get$7(target) > 0;
  3647. };
  3648. var findInitial = function (component, tabbingConfig) {
  3649. var tabstops = descendants(component.element, tabbingConfig.selector);
  3650. var visibles = filter$2(tabstops, function (elem) {
  3651. return isVisible(tabbingConfig, elem);
  3652. });
  3653. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  3654. };
  3655. var findCurrent = function (component, tabbingConfig) {
  3656. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3657. return closest$1(elem, tabbingConfig.selector);
  3658. });
  3659. };
  3660. var isTabstop = function (tabbingConfig, element) {
  3661. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3662. };
  3663. var focusIn = function (component, tabbingConfig, _tabbingState) {
  3664. findInitial(component, tabbingConfig).each(function (target) {
  3665. tabbingConfig.focusManager.set(component, target);
  3666. });
  3667. };
  3668. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3669. return cycle(tabstops, stopIndex, function (elem) {
  3670. return isTabstop(tabbingConfig, elem);
  3671. }).fold(function () {
  3672. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  3673. }, function (target) {
  3674. tabbingConfig.focusManager.set(component, target);
  3675. return Optional.some(true);
  3676. });
  3677. };
  3678. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  3679. var tabstops = descendants(component.element, tabbingConfig.selector);
  3680. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3681. var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  3682. return optStopIndex.bind(function (stopIndex) {
  3683. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3684. });
  3685. });
  3686. };
  3687. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  3688. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3689. return go(component, simulatedEvent, tabbingConfig, navigate);
  3690. };
  3691. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  3692. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3693. return go(component, simulatedEvent, tabbingConfig, navigate);
  3694. };
  3695. var execute = function (component, simulatedEvent, tabbingConfig) {
  3696. return tabbingConfig.onEnter.bind(function (f) {
  3697. return f(component, simulatedEvent);
  3698. });
  3699. };
  3700. var exit = function (component, simulatedEvent, tabbingConfig) {
  3701. return tabbingConfig.onEscape.bind(function (f) {
  3702. return f(component, simulatedEvent);
  3703. });
  3704. };
  3705. var getKeydownRules = constant$1([
  3706. rule(and([
  3707. isShift,
  3708. inSet(TAB)
  3709. ]), goBackwards),
  3710. rule(inSet(TAB), goForwards),
  3711. rule(inSet(ESCAPE), exit),
  3712. rule(and([
  3713. isNotShift,
  3714. inSet(ENTER)
  3715. ]), execute)
  3716. ]);
  3717. var getKeyupRules = constant$1([]);
  3718. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3719. return Optional.some(focusIn);
  3720. });
  3721. };
  3722. var AcyclicType = create$4(customField('cyclic', never));
  3723. var CyclicType = create$4(customField('cyclic', always));
  3724. var inside = function (target) {
  3725. return name$1(target) === 'input' && get$b(target, 'type') !== 'radio' || name$1(target) === 'textarea';
  3726. };
  3727. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  3728. dispatch(component, focused, execute$5());
  3729. return Optional.some(true);
  3730. };
  3731. var defaultExecute = function (component, simulatedEvent, focused) {
  3732. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  3733. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  3734. };
  3735. var stopEventForFirefox = function (_component, _simulatedEvent) {
  3736. return Optional.some(true);
  3737. };
  3738. var schema$f = [
  3739. defaulted('execute', defaultExecute),
  3740. defaulted('useSpace', false),
  3741. defaulted('useEnter', true),
  3742. defaulted('useControlEnter', false),
  3743. defaulted('useDown', false)
  3744. ];
  3745. var execute$4 = function (component, simulatedEvent, executeConfig) {
  3746. return executeConfig.execute(component, simulatedEvent, component.element);
  3747. };
  3748. var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  3749. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  3750. var enterExec = executeConfig.useEnter ? ENTER : [];
  3751. var downExec = executeConfig.useDown ? DOWN : [];
  3752. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3753. return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  3754. isControl,
  3755. inSet(ENTER)
  3756. ]), execute$4)] : []);
  3757. };
  3758. var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  3759. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  3760. };
  3761. var ExecutionType = typical(schema$f, NoState.init, getKeydownRules$5, getKeyupRules$5, function () {
  3762. return Optional.none();
  3763. });
  3764. var singleton$1 = function (doRevoke) {
  3765. var subject = Cell(Optional.none());
  3766. var revoke = function () {
  3767. return subject.get().each(doRevoke);
  3768. };
  3769. var clear = function () {
  3770. revoke();
  3771. subject.set(Optional.none());
  3772. };
  3773. var isSet = function () {
  3774. return subject.get().isSome();
  3775. };
  3776. var get = function () {
  3777. return subject.get();
  3778. };
  3779. var set = function (s) {
  3780. revoke();
  3781. subject.set(Optional.some(s));
  3782. };
  3783. return {
  3784. clear: clear,
  3785. isSet: isSet,
  3786. get: get,
  3787. set: set
  3788. };
  3789. };
  3790. var destroyable = function () {
  3791. return singleton$1(function (s) {
  3792. return s.destroy();
  3793. });
  3794. };
  3795. var api$2 = function () {
  3796. var subject = destroyable();
  3797. var run = function (f) {
  3798. return subject.get().each(f);
  3799. };
  3800. return __assign(__assign({}, subject), { run: run });
  3801. };
  3802. var value = function () {
  3803. var subject = singleton$1(noop);
  3804. var on = function (f) {
  3805. return subject.get().each(f);
  3806. };
  3807. return __assign(__assign({}, subject), { on: on });
  3808. };
  3809. var flatgrid$1 = function () {
  3810. var dimensions = value();
  3811. var setGridSize = function (numRows, numColumns) {
  3812. dimensions.set({
  3813. numRows: numRows,
  3814. numColumns: numColumns
  3815. });
  3816. };
  3817. var getNumRows = function () {
  3818. return dimensions.get().map(function (d) {
  3819. return d.numRows;
  3820. });
  3821. };
  3822. var getNumColumns = function () {
  3823. return dimensions.get().map(function (d) {
  3824. return d.numColumns;
  3825. });
  3826. };
  3827. return nu$2({
  3828. readState: function () {
  3829. return dimensions.get().map(function (d) {
  3830. return {
  3831. numRows: String(d.numRows),
  3832. numColumns: String(d.numColumns)
  3833. };
  3834. }).getOr({
  3835. numRows: '?',
  3836. numColumns: '?'
  3837. });
  3838. },
  3839. setGridSize: setGridSize,
  3840. getNumRows: getNumRows,
  3841. getNumColumns: getNumColumns
  3842. });
  3843. };
  3844. var init$5 = function (spec) {
  3845. return spec.state(spec);
  3846. };
  3847. var KeyingState = /*#__PURE__*/Object.freeze({
  3848. __proto__: null,
  3849. flatgrid: flatgrid$1,
  3850. init: init$5
  3851. });
  3852. var onDirection = function (isLtr, isRtl) {
  3853. return function (element) {
  3854. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3855. };
  3856. };
  3857. var getDirection = function (element) {
  3858. return get$8(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3859. };
  3860. var useH = function (movement) {
  3861. return function (component, simulatedEvent, config, state) {
  3862. var move = movement(component.element);
  3863. return use(move, component, simulatedEvent, config, state);
  3864. };
  3865. };
  3866. var west = function (moveLeft, moveRight) {
  3867. var movement = onDirection(moveLeft, moveRight);
  3868. return useH(movement);
  3869. };
  3870. var east = function (moveLeft, moveRight) {
  3871. var movement = onDirection(moveRight, moveLeft);
  3872. return useH(movement);
  3873. };
  3874. var useV = function (move) {
  3875. return function (component, simulatedEvent, config, state) {
  3876. return use(move, component, simulatedEvent, config, state);
  3877. };
  3878. };
  3879. var use = function (move, component, simulatedEvent, config, state) {
  3880. var outcome = config.focusManager.get(component).bind(function (focused) {
  3881. return move(component.element, focused, config, state);
  3882. });
  3883. return outcome.map(function (newFocus) {
  3884. config.focusManager.set(component, newFocus);
  3885. return true;
  3886. });
  3887. };
  3888. var north = useV;
  3889. var south = useV;
  3890. var move$1 = useV;
  3891. var isHidden = function (dom) {
  3892. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3893. };
  3894. var isVisible = function (element) {
  3895. return !isHidden(element.dom);
  3896. };
  3897. var locate = function (candidates, predicate) {
  3898. return findIndex$1(candidates, predicate).map(function (index) {
  3899. return {
  3900. index: index,
  3901. candidates: candidates
  3902. };
  3903. });
  3904. };
  3905. var locateVisible = function (container, current, selector) {
  3906. var predicate = function (x) {
  3907. return eq(x, current);
  3908. };
  3909. var candidates = descendants(container, selector);
  3910. var visible = filter$2(candidates, isVisible);
  3911. return locate(visible, predicate);
  3912. };
  3913. var findIndex = function (elements, target) {
  3914. return findIndex$1(elements, function (elem) {
  3915. return eq(target, elem);
  3916. });
  3917. };
  3918. var withGrid = function (values, index, numCols, f) {
  3919. var oldRow = Math.floor(index / numCols);
  3920. var oldColumn = index % numCols;
  3921. return f(oldRow, oldColumn).bind(function (address) {
  3922. var newIndex = address.row * numCols + address.column;
  3923. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  3924. });
  3925. };
  3926. var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) {
  3927. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3928. var onLastRow = oldRow === numRows - 1;
  3929. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3930. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3931. return Optional.some({
  3932. row: oldRow,
  3933. column: newColumn
  3934. });
  3935. });
  3936. };
  3937. var cycleVertical$1 = function (values, index, numRows, numCols, delta) {
  3938. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3939. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3940. var onLastRow = newRow === numRows - 1;
  3941. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3942. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  3943. return Optional.some({
  3944. row: newRow,
  3945. column: newCol
  3946. });
  3947. });
  3948. };
  3949. var cycleRight$1 = function (values, index, numRows, numCols) {
  3950. return cycleHorizontal$1(values, index, numRows, numCols, +1);
  3951. };
  3952. var cycleLeft$1 = function (values, index, numRows, numCols) {
  3953. return cycleHorizontal$1(values, index, numRows, numCols, -1);
  3954. };
  3955. var cycleUp$1 = function (values, index, numRows, numCols) {
  3956. return cycleVertical$1(values, index, numRows, numCols, -1);
  3957. };
  3958. var cycleDown$1 = function (values, index, numRows, numCols) {
  3959. return cycleVertical$1(values, index, numRows, numCols, +1);
  3960. };
  3961. var schema$e = [
  3962. required$1('selector'),
  3963. defaulted('execute', defaultExecute),
  3964. onKeyboardHandler('onEscape'),
  3965. defaulted('captureTab', false),
  3966. initSize()
  3967. ];
  3968. var focusIn$3 = function (component, gridConfig, _gridState) {
  3969. descendant(component.element, gridConfig.selector).each(function (first) {
  3970. gridConfig.focusManager.set(component, first);
  3971. });
  3972. };
  3973. var findCurrent$1 = function (component, gridConfig) {
  3974. return gridConfig.focusManager.get(component).bind(function (elem) {
  3975. return closest$1(elem, gridConfig.selector);
  3976. });
  3977. };
  3978. var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) {
  3979. return findCurrent$1(component, gridConfig).bind(function (focused) {
  3980. return gridConfig.execute(component, simulatedEvent, focused);
  3981. });
  3982. };
  3983. var doMove$2 = function (cycle) {
  3984. return function (element, focused, gridConfig, gridState) {
  3985. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3986. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3987. });
  3988. };
  3989. };
  3990. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  3991. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  3992. };
  3993. var doEscape$1 = function (component, simulatedEvent, gridConfig) {
  3994. return gridConfig.onEscape(component, simulatedEvent);
  3995. };
  3996. var moveLeft$3 = doMove$2(cycleLeft$1);
  3997. var moveRight$3 = doMove$2(cycleRight$1);
  3998. var moveNorth$1 = doMove$2(cycleUp$1);
  3999. var moveSouth$1 = doMove$2(cycleDown$1);
  4000. var getKeydownRules$4 = constant$1([
  4001. rule(inSet(LEFT), west(moveLeft$3, moveRight$3)),
  4002. rule(inSet(RIGHT), east(moveLeft$3, moveRight$3)),
  4003. rule(inSet(UP), north(moveNorth$1)),
  4004. rule(inSet(DOWN), south(moveSouth$1)),
  4005. rule(and([
  4006. isShift,
  4007. inSet(TAB)
  4008. ]), handleTab),
  4009. rule(and([
  4010. isNotShift,
  4011. inSet(TAB)
  4012. ]), handleTab),
  4013. rule(inSet(ESCAPE), doEscape$1),
  4014. rule(inSet(SPACE.concat(ENTER)), execute$3)
  4015. ]);
  4016. var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4017. var FlatgridType = typical(schema$e, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () {
  4018. return Optional.some(focusIn$3);
  4019. });
  4020. var horizontal = function (container, selector, current, delta) {
  4021. var isDisabledButton = function (candidate) {
  4022. return name$1(candidate) === 'button' && get$b(candidate, 'disabled') === 'disabled';
  4023. };
  4024. var tryCycle = function (initial, index, candidates) {
  4025. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  4026. if (newIndex === initial) {
  4027. return Optional.none();
  4028. } else {
  4029. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  4030. }
  4031. };
  4032. return locateVisible(container, current, selector).bind(function (identified) {
  4033. var index = identified.index;
  4034. var candidates = identified.candidates;
  4035. return tryCycle(index, index, candidates);
  4036. });
  4037. };
  4038. var schema$d = [
  4039. required$1('selector'),
  4040. defaulted('getInitial', Optional.none),
  4041. defaulted('execute', defaultExecute),
  4042. onKeyboardHandler('onEscape'),
  4043. defaulted('executeOnMove', false),
  4044. defaulted('allowVertical', true)
  4045. ];
  4046. var findCurrent = function (component, flowConfig) {
  4047. return flowConfig.focusManager.get(component).bind(function (elem) {
  4048. return closest$1(elem, flowConfig.selector);
  4049. });
  4050. };
  4051. var execute$2 = function (component, simulatedEvent, flowConfig) {
  4052. return findCurrent(component, flowConfig).bind(function (focused) {
  4053. return flowConfig.execute(component, simulatedEvent, focused);
  4054. });
  4055. };
  4056. var focusIn$2 = function (component, flowConfig, _state) {
  4057. flowConfig.getInitial(component).orThunk(function () {
  4058. return descendant(component.element, flowConfig.selector);
  4059. }).each(function (first) {
  4060. flowConfig.focusManager.set(component, first);
  4061. });
  4062. };
  4063. var moveLeft$2 = function (element, focused, info) {
  4064. return horizontal(element, info.selector, focused, -1);
  4065. };
  4066. var moveRight$2 = function (element, focused, info) {
  4067. return horizontal(element, info.selector, focused, +1);
  4068. };
  4069. var doMove$1 = function (movement) {
  4070. return function (component, simulatedEvent, flowConfig, flowState) {
  4071. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  4072. return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
  4073. });
  4074. };
  4075. };
  4076. var doEscape = function (component, simulatedEvent, flowConfig) {
  4077. return flowConfig.onEscape(component, simulatedEvent);
  4078. };
  4079. var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) {
  4080. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  4081. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  4082. return [
  4083. rule(inSet(westMovers), doMove$1(west(moveLeft$2, moveRight$2))),
  4084. rule(inSet(eastMovers), doMove$1(east(moveLeft$2, moveRight$2))),
  4085. rule(inSet(ENTER), execute$2),
  4086. rule(inSet(SPACE), execute$2),
  4087. rule(inSet(ESCAPE), doEscape)
  4088. ];
  4089. };
  4090. var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4091. var FlowType = typical(schema$d, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4092. return Optional.some(focusIn$2);
  4093. });
  4094. var toCell = function (matrix, rowIndex, columnIndex) {
  4095. return Optional.from(matrix[rowIndex]).bind(function (row) {
  4096. return Optional.from(row[columnIndex]).map(function (cell) {
  4097. return {
  4098. rowIndex: rowIndex,
  4099. columnIndex: columnIndex,
  4100. cell: cell
  4101. };
  4102. });
  4103. });
  4104. };
  4105. var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4106. var row = matrix[rowIndex];
  4107. var colsInRow = row.length;
  4108. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  4109. return toCell(matrix, rowIndex, newColIndex);
  4110. };
  4111. var cycleVertical = function (matrix, colIndex, startRow, deltaRow) {
  4112. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  4113. var colsInNextRow = matrix[nextRowIndex].length;
  4114. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4115. return toCell(matrix, nextRowIndex, nextColIndex);
  4116. };
  4117. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4118. var row = matrix[rowIndex];
  4119. var colsInRow = row.length;
  4120. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  4121. return toCell(matrix, rowIndex, newColIndex);
  4122. };
  4123. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  4124. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  4125. var colsInNextRow = matrix[nextRowIndex].length;
  4126. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4127. return toCell(matrix, nextRowIndex, nextColIndex);
  4128. };
  4129. var cycleRight = function (matrix, startRow, startCol) {
  4130. return cycleHorizontal(matrix, startRow, startCol, +1);
  4131. };
  4132. var cycleLeft = function (matrix, startRow, startCol) {
  4133. return cycleHorizontal(matrix, startRow, startCol, -1);
  4134. };
  4135. var cycleUp = function (matrix, startRow, startCol) {
  4136. return cycleVertical(matrix, startCol, startRow, -1);
  4137. };
  4138. var cycleDown = function (matrix, startRow, startCol) {
  4139. return cycleVertical(matrix, startCol, startRow, +1);
  4140. };
  4141. var moveLeft$1 = function (matrix, startRow, startCol) {
  4142. return moveHorizontal(matrix, startRow, startCol, -1);
  4143. };
  4144. var moveRight$1 = function (matrix, startRow, startCol) {
  4145. return moveHorizontal(matrix, startRow, startCol, +1);
  4146. };
  4147. var moveUp$1 = function (matrix, startRow, startCol) {
  4148. return moveVertical(matrix, startCol, startRow, -1);
  4149. };
  4150. var moveDown$1 = function (matrix, startRow, startCol) {
  4151. return moveVertical(matrix, startCol, startRow, +1);
  4152. };
  4153. var schema$c = [
  4154. requiredObjOf('selectors', [
  4155. required$1('row'),
  4156. required$1('cell')
  4157. ]),
  4158. defaulted('cycles', true),
  4159. defaulted('previousSelector', Optional.none),
  4160. defaulted('execute', defaultExecute)
  4161. ];
  4162. var focusIn$1 = function (component, matrixConfig, _state) {
  4163. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4164. var selectors = matrixConfig.selectors;
  4165. return descendant(component.element, selectors.cell);
  4166. });
  4167. focused.each(function (cell) {
  4168. matrixConfig.focusManager.set(component, cell);
  4169. });
  4170. };
  4171. var execute$1 = function (component, simulatedEvent, matrixConfig) {
  4172. return search(component.element).bind(function (focused) {
  4173. return matrixConfig.execute(component, simulatedEvent, focused);
  4174. });
  4175. };
  4176. var toMatrix = function (rows, matrixConfig) {
  4177. return map$2(rows, function (row) {
  4178. return descendants(row, matrixConfig.selectors.cell);
  4179. });
  4180. };
  4181. var doMove = function (ifCycle, ifMove) {
  4182. return function (element, focused, matrixConfig) {
  4183. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4184. return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4185. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4186. return findIndex(cellsInRow, focused).bind(function (colIndex) {
  4187. var allRows = descendants(element, matrixConfig.selectors.row);
  4188. return findIndex(allRows, inRow).bind(function (rowIndex) {
  4189. var matrix = toMatrix(allRows, matrixConfig);
  4190. return move(matrix, rowIndex, colIndex).map(function (next) {
  4191. return next.cell;
  4192. });
  4193. });
  4194. });
  4195. });
  4196. };
  4197. };
  4198. var moveLeft = doMove(cycleLeft, moveLeft$1);
  4199. var moveRight = doMove(cycleRight, moveRight$1);
  4200. var moveNorth = doMove(cycleUp, moveUp$1);
  4201. var moveSouth = doMove(cycleDown, moveDown$1);
  4202. var getKeydownRules$2 = constant$1([
  4203. rule(inSet(LEFT), west(moveLeft, moveRight)),
  4204. rule(inSet(RIGHT), east(moveLeft, moveRight)),
  4205. rule(inSet(UP), north(moveNorth)),
  4206. rule(inSet(DOWN), south(moveSouth)),
  4207. rule(inSet(SPACE.concat(ENTER)), execute$1)
  4208. ]);
  4209. var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4210. var MatrixType = typical(schema$c, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  4211. return Optional.some(focusIn$1);
  4212. });
  4213. var schema$b = [
  4214. required$1('selector'),
  4215. defaulted('execute', defaultExecute),
  4216. defaulted('moveOnTab', false)
  4217. ];
  4218. var execute = function (component, simulatedEvent, menuConfig) {
  4219. return menuConfig.focusManager.get(component).bind(function (focused) {
  4220. return menuConfig.execute(component, simulatedEvent, focused);
  4221. });
  4222. };
  4223. var focusIn = function (component, menuConfig, _state) {
  4224. descendant(component.element, menuConfig.selector).each(function (first) {
  4225. menuConfig.focusManager.set(component, first);
  4226. });
  4227. };
  4228. var moveUp = function (element, focused, info) {
  4229. return horizontal(element, info.selector, focused, -1);
  4230. };
  4231. var moveDown = function (element, focused, info) {
  4232. return horizontal(element, info.selector, focused, +1);
  4233. };
  4234. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  4235. return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4236. };
  4237. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  4238. return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4239. };
  4240. var getKeydownRules$1 = constant$1([
  4241. rule(inSet(UP), move$1(moveUp)),
  4242. rule(inSet(DOWN), move$1(moveDown)),
  4243. rule(and([
  4244. isShift,
  4245. inSet(TAB)
  4246. ]), fireShiftTab),
  4247. rule(and([
  4248. isNotShift,
  4249. inSet(TAB)
  4250. ]), fireTab),
  4251. rule(inSet(ENTER), execute),
  4252. rule(inSet(SPACE), execute)
  4253. ]);
  4254. var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4255. var MenuType = typical(schema$b, NoState.init, getKeydownRules$1, getKeyupRules$1, function () {
  4256. return Optional.some(focusIn);
  4257. });
  4258. var schema$a = [
  4259. onKeyboardHandler('onSpace'),
  4260. onKeyboardHandler('onEnter'),
  4261. onKeyboardHandler('onShiftEnter'),
  4262. onKeyboardHandler('onLeft'),
  4263. onKeyboardHandler('onRight'),
  4264. onKeyboardHandler('onTab'),
  4265. onKeyboardHandler('onShiftTab'),
  4266. onKeyboardHandler('onUp'),
  4267. onKeyboardHandler('onDown'),
  4268. onKeyboardHandler('onEscape'),
  4269. defaulted('stopSpaceKeyup', false),
  4270. option('focusIn')
  4271. ];
  4272. var getKeydownRules = function (component, simulatedEvent, specialInfo) {
  4273. return [
  4274. rule(inSet(SPACE), specialInfo.onSpace),
  4275. rule(and([
  4276. isNotShift,
  4277. inSet(ENTER)
  4278. ]), specialInfo.onEnter),
  4279. rule(and([
  4280. isShift,
  4281. inSet(ENTER)
  4282. ]), specialInfo.onShiftEnter),
  4283. rule(and([
  4284. isShift,
  4285. inSet(TAB)
  4286. ]), specialInfo.onShiftTab),
  4287. rule(and([
  4288. isNotShift,
  4289. inSet(TAB)
  4290. ]), specialInfo.onTab),
  4291. rule(inSet(UP), specialInfo.onUp),
  4292. rule(inSet(DOWN), specialInfo.onDown),
  4293. rule(inSet(LEFT), specialInfo.onLeft),
  4294. rule(inSet(RIGHT), specialInfo.onRight),
  4295. rule(inSet(SPACE), specialInfo.onSpace),
  4296. rule(inSet(ESCAPE), specialInfo.onEscape)
  4297. ];
  4298. };
  4299. var getKeyupRules = function (component, simulatedEvent, specialInfo) {
  4300. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  4301. };
  4302. var SpecialType = typical(schema$a, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) {
  4303. return specialInfo.focusIn;
  4304. });
  4305. var acyclic = AcyclicType.schema();
  4306. var cyclic = CyclicType.schema();
  4307. var flow = FlowType.schema();
  4308. var flatgrid = FlatgridType.schema();
  4309. var matrix = MatrixType.schema();
  4310. var execution = ExecutionType.schema();
  4311. var menu = MenuType.schema();
  4312. var special = SpecialType.schema();
  4313. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4314. __proto__: null,
  4315. acyclic: acyclic,
  4316. cyclic: cyclic,
  4317. flow: flow,
  4318. flatgrid: flatgrid,
  4319. matrix: matrix,
  4320. execution: execution,
  4321. menu: menu,
  4322. special: special
  4323. });
  4324. var isFlatgridState = function (keyState) {
  4325. return hasNonNullableKey(keyState, 'setGridSize');
  4326. };
  4327. var Keying = createModes({
  4328. branchKey: 'mode',
  4329. branches: KeyboardBranches,
  4330. name: 'keying',
  4331. active: {
  4332. events: function (keyingConfig, keyingState) {
  4333. var handler = keyingConfig.handler;
  4334. return handler.toEvents(keyingConfig, keyingState);
  4335. }
  4336. },
  4337. apis: {
  4338. focusIn: function (component, keyConfig, keyState) {
  4339. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4340. component.getSystem().triggerFocus(component.element, component.element);
  4341. }, function (sendFocusIn) {
  4342. sendFocusIn(component, keyConfig, keyState);
  4343. });
  4344. },
  4345. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4346. if (!isFlatgridState(keyState)) {
  4347. console.error('Layout does not support setGridSize');
  4348. } else {
  4349. keyState.setGridSize(numRows, numColumns);
  4350. }
  4351. }
  4352. },
  4353. state: KeyingState
  4354. });
  4355. var field$1 = function (name, forbidden) {
  4356. return defaultedObjOf(name, {}, map$2(forbidden, function (f) {
  4357. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4358. }).concat([customField('dump', identity)]));
  4359. };
  4360. var get$6 = function (data) {
  4361. return data.dump;
  4362. };
  4363. var augment = function (data, original) {
  4364. return __assign(__assign({}, data.dump), derive$2(original));
  4365. };
  4366. var SketchBehaviours = {
  4367. field: field$1,
  4368. augment: augment,
  4369. get: get$6
  4370. };
  4371. var _placeholder = 'placeholder';
  4372. var adt$5 = Adt.generate([
  4373. {
  4374. single: [
  4375. 'required',
  4376. 'valueThunk'
  4377. ]
  4378. },
  4379. {
  4380. multiple: [
  4381. 'required',
  4382. 'valueThunks'
  4383. ]
  4384. }
  4385. ]);
  4386. var isSubstituted = function (spec) {
  4387. return has$2(spec, 'uiType');
  4388. };
  4389. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4390. if (owner.exists(function (o) {
  4391. return o !== compSpec.owner;
  4392. })) {
  4393. return adt$5.single(true, constant$1(compSpec));
  4394. }
  4395. return get$c(placeholders, compSpec.name).fold(function () {
  4396. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4397. }, function (newSpec) {
  4398. return newSpec.replace();
  4399. });
  4400. };
  4401. var scan = function (owner, detail, compSpec, placeholders) {
  4402. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  4403. return subPlaceholder(owner, detail, compSpec, placeholders);
  4404. } else {
  4405. return adt$5.single(false, constant$1(compSpec));
  4406. }
  4407. };
  4408. var substitute = function (owner, detail, compSpec, placeholders) {
  4409. var base = scan(owner, detail, compSpec, placeholders);
  4410. return base.fold(function (req, valueThunk) {
  4411. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  4412. var childSpecs = get$c(value, 'components').getOr([]);
  4413. var substituted = bind$3(childSpecs, function (c) {
  4414. return substitute(owner, detail, c, placeholders);
  4415. });
  4416. return [__assign(__assign({}, value), { components: substituted })];
  4417. }, function (req, valuesThunk) {
  4418. if (isSubstituted(compSpec)) {
  4419. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4420. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4421. return preprocessor(values);
  4422. } else {
  4423. return valuesThunk(detail);
  4424. }
  4425. });
  4426. };
  4427. var substituteAll = function (owner, detail, components, placeholders) {
  4428. return bind$3(components, function (c) {
  4429. return substitute(owner, detail, c, placeholders);
  4430. });
  4431. };
  4432. var oneReplace = function (label, replacements) {
  4433. var called = false;
  4434. var used = function () {
  4435. return called;
  4436. };
  4437. var replace = function () {
  4438. if (called) {
  4439. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4440. }
  4441. called = true;
  4442. return replacements;
  4443. };
  4444. var required = function () {
  4445. return replacements.fold(function (req, _) {
  4446. return req;
  4447. }, function (req, _) {
  4448. return req;
  4449. });
  4450. };
  4451. return {
  4452. name: constant$1(label),
  4453. required: required,
  4454. used: used,
  4455. replace: replace
  4456. };
  4457. };
  4458. var substitutePlaces = function (owner, detail, components, placeholders) {
  4459. var ps = map$1(placeholders, function (ph, name) {
  4460. return oneReplace(name, ph);
  4461. });
  4462. var outcome = substituteAll(owner, detail, components, ps);
  4463. each(ps, function (p) {
  4464. if (p.used() === false && p.required()) {
  4465. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4466. }
  4467. });
  4468. return outcome;
  4469. };
  4470. var single$2 = adt$5.single;
  4471. var multiple = adt$5.multiple;
  4472. var placeholder = constant$1(_placeholder);
  4473. var unique = 0;
  4474. var generate$4 = function (prefix) {
  4475. var date = new Date();
  4476. var time = date.getTime();
  4477. var random = Math.floor(Math.random() * 1000000000);
  4478. unique++;
  4479. return prefix + '_' + random + unique + String(time);
  4480. };
  4481. var adt$4 = Adt.generate([
  4482. { required: ['data'] },
  4483. { external: ['data'] },
  4484. { optional: ['data'] },
  4485. { group: ['data'] }
  4486. ]);
  4487. var fFactory = defaulted('factory', { sketch: identity });
  4488. var fSchema = defaulted('schema', []);
  4489. var fName = required$1('name');
  4490. var fPname = field$2('pname', 'pname', defaultedThunk(function (typeSpec) {
  4491. return '<alloy.' + generate$4(typeSpec.name) + '>';
  4492. }), anyValue());
  4493. var fGroupSchema = customField('schema', function () {
  4494. return [option('preprocess')];
  4495. });
  4496. var fDefaults = defaulted('defaults', constant$1({}));
  4497. var fOverrides = defaulted('overrides', constant$1({}));
  4498. var requiredSpec = objOf([
  4499. fFactory,
  4500. fSchema,
  4501. fName,
  4502. fPname,
  4503. fDefaults,
  4504. fOverrides
  4505. ]);
  4506. var externalSpec = objOf([
  4507. fFactory,
  4508. fSchema,
  4509. fName,
  4510. fDefaults,
  4511. fOverrides
  4512. ]);
  4513. var optionalSpec = objOf([
  4514. fFactory,
  4515. fSchema,
  4516. fName,
  4517. fPname,
  4518. fDefaults,
  4519. fOverrides
  4520. ]);
  4521. var groupSpec = objOf([
  4522. fFactory,
  4523. fGroupSchema,
  4524. fName,
  4525. required$1('unit'),
  4526. fPname,
  4527. fDefaults,
  4528. fOverrides
  4529. ]);
  4530. var asNamedPart = function (part) {
  4531. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  4532. };
  4533. var name = function (part) {
  4534. var get = function (data) {
  4535. return data.name;
  4536. };
  4537. return part.fold(get, get, get, get);
  4538. };
  4539. var convert$1 = function (adtConstructor, partSchema) {
  4540. return function (spec) {
  4541. var data = asRawOrDie$1('Converting part type', partSchema, spec);
  4542. return adtConstructor(data);
  4543. };
  4544. };
  4545. var required = convert$1(adt$4.required, requiredSpec);
  4546. convert$1(adt$4.external, externalSpec);
  4547. var optional = convert$1(adt$4.optional, optionalSpec);
  4548. var group = convert$1(adt$4.group, groupSpec);
  4549. var original = constant$1('entirety');
  4550. var combine$2 = function (detail, data, partSpec, partValidated) {
  4551. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4552. };
  4553. var subs = function (owner, detail, parts) {
  4554. var internals = {};
  4555. var externals = {};
  4556. each$1(parts, function (part) {
  4557. part.fold(function (data) {
  4558. internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) {
  4559. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  4560. });
  4561. }, function (data) {
  4562. var partSpec = detail.parts[data.name];
  4563. externals[data.name] = constant$1(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  4564. }, function (data) {
  4565. internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) {
  4566. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  4567. });
  4568. }, function (data) {
  4569. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4570. var units = detail[data.name];
  4571. return map$2(units, function (u) {
  4572. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4573. });
  4574. });
  4575. });
  4576. });
  4577. return {
  4578. internals: constant$1(internals),
  4579. externals: constant$1(externals)
  4580. };
  4581. };
  4582. var generate$3 = function (owner, parts) {
  4583. var r = {};
  4584. each$1(parts, function (part) {
  4585. asNamedPart(part).each(function (np) {
  4586. var g = doGenerateOne(owner, np.pname);
  4587. r[np.name] = function (config) {
  4588. var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4589. return __assign(__assign({}, g), {
  4590. config: config,
  4591. validated: validated
  4592. });
  4593. };
  4594. });
  4595. });
  4596. return r;
  4597. };
  4598. var doGenerateOne = function (owner, pname) {
  4599. return {
  4600. uiType: placeholder(),
  4601. owner: owner,
  4602. name: pname
  4603. };
  4604. };
  4605. var generateOne = function (owner, pname, config) {
  4606. return {
  4607. uiType: placeholder(),
  4608. owner: owner,
  4609. name: pname,
  4610. config: config,
  4611. validated: {}
  4612. };
  4613. };
  4614. var schemas = function (parts) {
  4615. return bind$3(parts, function (part) {
  4616. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  4617. return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
  4618. }).toArray();
  4619. });
  4620. };
  4621. var names = function (parts) {
  4622. return map$2(parts, name);
  4623. };
  4624. var substitutes = function (owner, detail, parts) {
  4625. return subs(owner, detail, parts);
  4626. };
  4627. var components = function (owner, detail, internals) {
  4628. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  4629. };
  4630. var getPart = function (component, detail, partKey) {
  4631. var uid = detail.partUids[partKey];
  4632. return component.getSystem().getByUid(uid).toOptional();
  4633. };
  4634. var getPartOrDie = function (component, detail, partKey) {
  4635. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4636. };
  4637. var getAllParts = function (component, detail) {
  4638. var system = component.getSystem();
  4639. return map$1(detail.partUids, function (pUid, _k) {
  4640. return constant$1(system.getByUid(pUid));
  4641. });
  4642. };
  4643. var defaultUids = function (baseUid, partTypes) {
  4644. var partNames = names(partTypes);
  4645. return wrapAll(map$2(partNames, function (pn) {
  4646. return {
  4647. key: pn,
  4648. value: baseUid + '-' + pn
  4649. };
  4650. }));
  4651. };
  4652. var defaultUidsSchema = function (partTypes) {
  4653. return field$2('partUids', 'partUids', mergeWithThunk(function (spec) {
  4654. return defaultUids(spec.uid, partTypes);
  4655. }), anyValue());
  4656. };
  4657. var premadeTag = generate$4('alloy-premade');
  4658. var premade$1 = function (comp) {
  4659. return wrap(premadeTag, comp);
  4660. };
  4661. var getPremade = function (spec) {
  4662. return get$c(spec, premadeTag);
  4663. };
  4664. var makeApi = function (f) {
  4665. return markAsSketchApi(function (component) {
  4666. var rest = [];
  4667. for (var _i = 1; _i < arguments.length; _i++) {
  4668. rest[_i - 1] = arguments[_i];
  4669. }
  4670. return f.apply(void 0, __spreadArray([
  4671. component.getApis(),
  4672. component
  4673. ], rest));
  4674. }, f);
  4675. };
  4676. var prefix$1 = constant$1('alloy-id-');
  4677. var idAttr$1 = constant$1('data-alloy-id');
  4678. var prefix = prefix$1();
  4679. var idAttr = idAttr$1();
  4680. var write = function (label, elem) {
  4681. var id = generate$4(prefix + label);
  4682. writeOnly(elem, id);
  4683. return id;
  4684. };
  4685. var writeOnly = function (elem, uid) {
  4686. Object.defineProperty(elem.dom, idAttr, {
  4687. value: uid,
  4688. writable: true
  4689. });
  4690. };
  4691. var read = function (elem) {
  4692. var id = isElement(elem) ? elem.dom[idAttr] : null;
  4693. return Optional.from(id);
  4694. };
  4695. var generate$2 = function (prefix) {
  4696. return generate$4(prefix);
  4697. };
  4698. var base = function (partSchemas, partUidsSchemas) {
  4699. var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  4700. return ps.concat([
  4701. required$1('uid'),
  4702. defaulted('dom', {}),
  4703. defaulted('components', []),
  4704. snapshot('originalSpec'),
  4705. defaulted('debug.sketcher', {})
  4706. ]).concat(partUidsSchemas);
  4707. };
  4708. var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4709. var baseS = base(partSchemas, partUidsSchemas);
  4710. return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4711. };
  4712. var single$1 = function (owner, schema, factory, spec) {
  4713. var specWithUid = supplyUid(spec);
  4714. var detail = asRawOrDie(owner, schema, specWithUid, [], []);
  4715. return factory(detail, specWithUid);
  4716. };
  4717. var composite$1 = function (owner, schema, partTypes, factory, spec) {
  4718. var specWithUid = supplyUid(spec);
  4719. var partSchemas = schemas(partTypes);
  4720. var partUidsSchema = defaultUidsSchema(partTypes);
  4721. var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4722. var subs = substitutes(owner, detail, partTypes);
  4723. var components$1 = components(owner, detail, subs.internals());
  4724. return factory(detail, components$1, specWithUid, subs.externals());
  4725. };
  4726. var hasUid = function (spec) {
  4727. return has$2(spec, 'uid');
  4728. };
  4729. var supplyUid = function (spec) {
  4730. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  4731. };
  4732. var isSketchSpec$1 = function (spec) {
  4733. return spec.uid !== undefined;
  4734. };
  4735. var singleSchema = objOfOnly([
  4736. required$1('name'),
  4737. required$1('factory'),
  4738. required$1('configFields'),
  4739. defaulted('apis', {}),
  4740. defaulted('extraApis', {})
  4741. ]);
  4742. var compositeSchema = objOfOnly([
  4743. required$1('name'),
  4744. required$1('factory'),
  4745. required$1('configFields'),
  4746. required$1('partFields'),
  4747. defaulted('apis', {}),
  4748. defaulted('extraApis', {})
  4749. ]);
  4750. var single = function (rawConfig) {
  4751. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4752. var sketch = function (spec) {
  4753. return single$1(config.name, config.configFields, config.factory, spec);
  4754. };
  4755. var apis = map$1(config.apis, makeApi);
  4756. var extraApis = map$1(config.extraApis, function (f, k) {
  4757. return markAsExtraApi(f, k);
  4758. });
  4759. return __assign(__assign({
  4760. name: config.name,
  4761. configFields: config.configFields,
  4762. sketch: sketch
  4763. }, apis), extraApis);
  4764. };
  4765. var composite = function (rawConfig) {
  4766. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4767. var sketch = function (spec) {
  4768. return composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  4769. };
  4770. var parts = generate$3(config.name, config.partFields);
  4771. var apis = map$1(config.apis, makeApi);
  4772. var extraApis = map$1(config.extraApis, function (f, k) {
  4773. return markAsExtraApi(f, k);
  4774. });
  4775. return __assign(__assign({
  4776. name: config.name,
  4777. partFields: config.partFields,
  4778. configFields: config.configFields,
  4779. sketch: sketch,
  4780. parts: parts
  4781. }, apis), extraApis);
  4782. };
  4783. var factory$5 = function (detail) {
  4784. var events = events$8(detail.action);
  4785. var tag = detail.dom.tag;
  4786. var lookupAttr = function (attr) {
  4787. return get$c(detail.dom, 'attributes').bind(function (attrs) {
  4788. return get$c(attrs, attr);
  4789. });
  4790. };
  4791. var getModAttributes = function () {
  4792. if (tag === 'button') {
  4793. var type = lookupAttr('type').getOr('button');
  4794. var roleAttrs = lookupAttr('role').map(function (role) {
  4795. return { role: role };
  4796. }).getOr({});
  4797. return __assign({ type: type }, roleAttrs);
  4798. } else {
  4799. var role = lookupAttr('role').getOr('button');
  4800. return { role: role };
  4801. }
  4802. };
  4803. return {
  4804. uid: detail.uid,
  4805. dom: detail.dom,
  4806. components: detail.components,
  4807. events: events,
  4808. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4809. Focusing.config({}),
  4810. Keying.config({
  4811. mode: 'execution',
  4812. useSpace: true,
  4813. useEnter: true
  4814. })
  4815. ]),
  4816. domModification: { attributes: getModAttributes() },
  4817. eventOrder: detail.eventOrder
  4818. };
  4819. };
  4820. var Button = single({
  4821. name: 'Button',
  4822. factory: factory$5,
  4823. configFields: [
  4824. defaulted('uid', undefined),
  4825. required$1('dom'),
  4826. defaulted('components', []),
  4827. SketchBehaviours.field('buttonBehaviours', [
  4828. Focusing,
  4829. Keying
  4830. ]),
  4831. option('action'),
  4832. option('role'),
  4833. defaulted('eventOrder', {})
  4834. ]
  4835. });
  4836. var exhibit$3 = function () {
  4837. return nu$3({
  4838. styles: {
  4839. '-webkit-user-select': 'none',
  4840. 'user-select': 'none',
  4841. '-ms-user-select': 'none',
  4842. '-moz-user-select': '-moz-none'
  4843. },
  4844. attributes: { unselectable: 'on' }
  4845. });
  4846. };
  4847. var events$6 = function () {
  4848. return derive$3([abort(selectstart(), always)]);
  4849. };
  4850. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4851. __proto__: null,
  4852. events: events$6,
  4853. exhibit: exhibit$3
  4854. });
  4855. var Unselecting = create$5({
  4856. fields: [],
  4857. name: 'unselecting',
  4858. active: ActiveUnselecting
  4859. });
  4860. var getAttrs$1 = function (elem) {
  4861. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  4862. return foldl(attributes, function (b, attr) {
  4863. var _a;
  4864. if (attr.name === 'class') {
  4865. return b;
  4866. } else {
  4867. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4868. }
  4869. }, {});
  4870. };
  4871. var getClasses = function (elem) {
  4872. return Array.prototype.slice.call(elem.dom.classList, 0);
  4873. };
  4874. var fromHtml = function (html) {
  4875. var elem = SugarElement.fromHtml(html);
  4876. var children$1 = children(elem);
  4877. var attrs = getAttrs$1(elem);
  4878. var classes = getClasses(elem);
  4879. var contents = children$1.length === 0 ? {} : { innerHtml: get$9(elem) };
  4880. return __assign({
  4881. tag: name$1(elem),
  4882. classes: classes,
  4883. attributes: attrs
  4884. }, contents);
  4885. };
  4886. var dom$1 = function (rawHtml) {
  4887. var html = supplant(rawHtml, { prefix: prefix$2 });
  4888. return fromHtml(html);
  4889. };
  4890. var spec = function (rawHtml) {
  4891. return { dom: dom$1(rawHtml) };
  4892. };
  4893. var forToolbarCommand = function (editor, command) {
  4894. return forToolbar(command, function () {
  4895. editor.execCommand(command);
  4896. }, {}, editor);
  4897. };
  4898. var getToggleBehaviours = function (command) {
  4899. return derive$2([
  4900. Toggling.config({
  4901. toggleClass: resolve('toolbar-button-selected'),
  4902. toggleOnExecute: false,
  4903. aria: { mode: 'pressed' }
  4904. }),
  4905. format(command, function (button, status) {
  4906. var toggle = status ? Toggling.on : Toggling.off;
  4907. toggle(button);
  4908. })
  4909. ]);
  4910. };
  4911. var forToolbarStateCommand = function (editor, command) {
  4912. var extraBehaviours = getToggleBehaviours(command);
  4913. return forToolbar(command, function () {
  4914. editor.execCommand(command);
  4915. }, extraBehaviours, editor);
  4916. };
  4917. var forToolbarStateAction = function (editor, clazz, command, action) {
  4918. var extraBehaviours = getToggleBehaviours(command);
  4919. return forToolbar(clazz, action, extraBehaviours, editor);
  4920. };
  4921. var getToolbarIconButton = function (clazz, editor) {
  4922. var icons = editor.ui.registry.getAll().icons;
  4923. var optOxideIcon = Optional.from(icons[clazz]);
  4924. return optOxideIcon.fold(function () {
  4925. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4926. }, function (icon) {
  4927. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4928. });
  4929. };
  4930. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4931. return Button.sketch({
  4932. dom: getToolbarIconButton(clazz, editor),
  4933. action: action,
  4934. buttonBehaviours: deepMerge(derive$2([Unselecting.config({})]), extraBehaviours)
  4935. });
  4936. };
  4937. var labelPart = optional({
  4938. schema: [required$1('dom')],
  4939. name: 'label'
  4940. });
  4941. var edgePart = function (name) {
  4942. return optional({
  4943. name: '' + name + '-edge',
  4944. overrides: function (detail) {
  4945. var action = detail.model.manager.edgeActions[name];
  4946. return action.fold(function () {
  4947. return {};
  4948. }, function (a) {
  4949. return {
  4950. events: derive$3([
  4951. runActionExtra(touchstart(), function (comp, se, d) {
  4952. return a(comp, d);
  4953. }, [detail]),
  4954. runActionExtra(mousedown(), function (comp, se, d) {
  4955. return a(comp, d);
  4956. }, [detail]),
  4957. runActionExtra(mousemove(), function (comp, se, det) {
  4958. if (det.mouseIsDown.get()) {
  4959. a(comp, det);
  4960. }
  4961. }, [detail])
  4962. ])
  4963. };
  4964. });
  4965. }
  4966. });
  4967. };
  4968. var tlEdgePart = edgePart('top-left');
  4969. var tedgePart = edgePart('top');
  4970. var trEdgePart = edgePart('top-right');
  4971. var redgePart = edgePart('right');
  4972. var brEdgePart = edgePart('bottom-right');
  4973. var bedgePart = edgePart('bottom');
  4974. var blEdgePart = edgePart('bottom-left');
  4975. var ledgePart = edgePart('left');
  4976. var thumbPart = required({
  4977. name: 'thumb',
  4978. defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  4979. overrides: function (detail) {
  4980. return {
  4981. events: derive$3([
  4982. redirectToPart(touchstart(), detail, 'spectrum'),
  4983. redirectToPart(touchmove(), detail, 'spectrum'),
  4984. redirectToPart(touchend(), detail, 'spectrum'),
  4985. redirectToPart(mousedown(), detail, 'spectrum'),
  4986. redirectToPart(mousemove(), detail, 'spectrum'),
  4987. redirectToPart(mouseup(), detail, 'spectrum')
  4988. ])
  4989. };
  4990. }
  4991. });
  4992. var spectrumPart = required({
  4993. schema: [customField('mouseIsDown', function () {
  4994. return Cell(false);
  4995. })],
  4996. name: 'spectrum',
  4997. overrides: function (detail) {
  4998. var modelDetail = detail.model;
  4999. var model = modelDetail.manager;
  5000. var setValueFrom = function (component, simulatedEvent) {
  5001. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  5002. return model.setValueFrom(component, detail, value);
  5003. });
  5004. };
  5005. return {
  5006. behaviours: derive$2([
  5007. Keying.config({
  5008. mode: 'special',
  5009. onLeft: function (spectrum) {
  5010. return model.onLeft(spectrum, detail);
  5011. },
  5012. onRight: function (spectrum) {
  5013. return model.onRight(spectrum, detail);
  5014. },
  5015. onUp: function (spectrum) {
  5016. return model.onUp(spectrum, detail);
  5017. },
  5018. onDown: function (spectrum) {
  5019. return model.onDown(spectrum, detail);
  5020. }
  5021. }),
  5022. Focusing.config({})
  5023. ]),
  5024. events: derive$3([
  5025. run(touchstart(), setValueFrom),
  5026. run(touchmove(), setValueFrom),
  5027. run(mousedown(), setValueFrom),
  5028. run(mousemove(), function (spectrum, se) {
  5029. if (detail.mouseIsDown.get()) {
  5030. setValueFrom(spectrum, se);
  5031. }
  5032. })
  5033. ])
  5034. };
  5035. }
  5036. });
  5037. var SliderParts = [
  5038. labelPart,
  5039. ledgePart,
  5040. redgePart,
  5041. tedgePart,
  5042. bedgePart,
  5043. tlEdgePart,
  5044. trEdgePart,
  5045. blEdgePart,
  5046. brEdgePart,
  5047. thumbPart,
  5048. spectrumPart
  5049. ];
  5050. var onLoad$4 = function (component, repConfig, repState) {
  5051. repConfig.store.manager.onLoad(component, repConfig, repState);
  5052. };
  5053. var onUnload$2 = function (component, repConfig, repState) {
  5054. repConfig.store.manager.onUnload(component, repConfig, repState);
  5055. };
  5056. var setValue$3 = function (component, repConfig, repState, data) {
  5057. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5058. };
  5059. var getValue$4 = function (component, repConfig, repState) {
  5060. return repConfig.store.manager.getValue(component, repConfig, repState);
  5061. };
  5062. var getState$1 = function (component, repConfig, repState) {
  5063. return repState;
  5064. };
  5065. var RepresentApis = /*#__PURE__*/Object.freeze({
  5066. __proto__: null,
  5067. onLoad: onLoad$4,
  5068. onUnload: onUnload$2,
  5069. setValue: setValue$3,
  5070. getValue: getValue$4,
  5071. getState: getState$1
  5072. });
  5073. var events$5 = function (repConfig, repState) {
  5074. var es = repConfig.resetOnDom ? [
  5075. runOnAttached(function (comp, _se) {
  5076. onLoad$4(comp, repConfig, repState);
  5077. }),
  5078. runOnDetached(function (comp, _se) {
  5079. onUnload$2(comp, repConfig, repState);
  5080. })
  5081. ] : [loadEvent(repConfig, repState, onLoad$4)];
  5082. return derive$3(es);
  5083. };
  5084. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5085. __proto__: null,
  5086. events: events$5
  5087. });
  5088. var memory = function () {
  5089. var data = Cell(null);
  5090. var readState = function () {
  5091. return {
  5092. mode: 'memory',
  5093. value: data.get()
  5094. };
  5095. };
  5096. var isNotSet = function () {
  5097. return data.get() === null;
  5098. };
  5099. var clear = function () {
  5100. data.set(null);
  5101. };
  5102. return nu$2({
  5103. set: data.set,
  5104. get: data.get,
  5105. isNotSet: isNotSet,
  5106. clear: clear,
  5107. readState: readState
  5108. });
  5109. };
  5110. var manual = function () {
  5111. var readState = noop;
  5112. return nu$2({ readState: readState });
  5113. };
  5114. var dataset = function () {
  5115. var dataByValue = Cell({});
  5116. var dataByText = Cell({});
  5117. var readState = function () {
  5118. return {
  5119. mode: 'dataset',
  5120. dataByValue: dataByValue.get(),
  5121. dataByText: dataByText.get()
  5122. };
  5123. };
  5124. var clear = function () {
  5125. dataByValue.set({});
  5126. dataByText.set({});
  5127. };
  5128. var lookup = function (itemString) {
  5129. return get$c(dataByValue.get(), itemString).orThunk(function () {
  5130. return get$c(dataByText.get(), itemString);
  5131. });
  5132. };
  5133. var update = function (items) {
  5134. var currentDataByValue = dataByValue.get();
  5135. var currentDataByText = dataByText.get();
  5136. var newDataByValue = {};
  5137. var newDataByText = {};
  5138. each$1(items, function (item) {
  5139. newDataByValue[item.value] = item;
  5140. get$c(item, 'meta').each(function (meta) {
  5141. get$c(meta, 'text').each(function (text) {
  5142. newDataByText[text] = item;
  5143. });
  5144. });
  5145. });
  5146. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5147. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5148. };
  5149. return nu$2({
  5150. readState: readState,
  5151. lookup: lookup,
  5152. update: update,
  5153. clear: clear
  5154. });
  5155. };
  5156. var init$4 = function (spec) {
  5157. return spec.store.manager.state(spec);
  5158. };
  5159. var RepresentState = /*#__PURE__*/Object.freeze({
  5160. __proto__: null,
  5161. memory: memory,
  5162. dataset: dataset,
  5163. manual: manual,
  5164. init: init$4
  5165. });
  5166. var setValue$2 = function (component, repConfig, repState, data) {
  5167. var store = repConfig.store;
  5168. repState.update([data]);
  5169. store.setValue(component, data);
  5170. repConfig.onSetValue(component, data);
  5171. };
  5172. var getValue$3 = function (component, repConfig, repState) {
  5173. var store = repConfig.store;
  5174. var key = store.getDataKey(component);
  5175. return repState.lookup(key).getOrThunk(function () {
  5176. return store.getFallbackEntry(key);
  5177. });
  5178. };
  5179. var onLoad$3 = function (component, repConfig, repState) {
  5180. var store = repConfig.store;
  5181. store.initialValue.each(function (data) {
  5182. setValue$2(component, repConfig, repState, data);
  5183. });
  5184. };
  5185. var onUnload$1 = function (component, repConfig, repState) {
  5186. repState.clear();
  5187. };
  5188. var DatasetStore = [
  5189. option('initialValue'),
  5190. required$1('getFallbackEntry'),
  5191. required$1('getDataKey'),
  5192. required$1('setValue'),
  5193. output('manager', {
  5194. setValue: setValue$2,
  5195. getValue: getValue$3,
  5196. onLoad: onLoad$3,
  5197. onUnload: onUnload$1,
  5198. state: dataset
  5199. })
  5200. ];
  5201. var getValue$2 = function (component, repConfig, _repState) {
  5202. return repConfig.store.getValue(component);
  5203. };
  5204. var setValue$1 = function (component, repConfig, _repState, data) {
  5205. repConfig.store.setValue(component, data);
  5206. repConfig.onSetValue(component, data);
  5207. };
  5208. var onLoad$2 = function (component, repConfig, _repState) {
  5209. repConfig.store.initialValue.each(function (data) {
  5210. repConfig.store.setValue(component, data);
  5211. });
  5212. };
  5213. var ManualStore = [
  5214. required$1('getValue'),
  5215. defaulted('setValue', noop),
  5216. option('initialValue'),
  5217. output('manager', {
  5218. setValue: setValue$1,
  5219. getValue: getValue$2,
  5220. onLoad: onLoad$2,
  5221. onUnload: noop,
  5222. state: NoState.init
  5223. })
  5224. ];
  5225. var setValue = function (component, repConfig, repState, data) {
  5226. repState.set(data);
  5227. repConfig.onSetValue(component, data);
  5228. };
  5229. var getValue$1 = function (component, repConfig, repState) {
  5230. return repState.get();
  5231. };
  5232. var onLoad$1 = function (component, repConfig, repState) {
  5233. repConfig.store.initialValue.each(function (initVal) {
  5234. if (repState.isNotSet()) {
  5235. repState.set(initVal);
  5236. }
  5237. });
  5238. };
  5239. var onUnload = function (component, repConfig, repState) {
  5240. repState.clear();
  5241. };
  5242. var MemoryStore = [
  5243. option('initialValue'),
  5244. output('manager', {
  5245. setValue: setValue,
  5246. getValue: getValue$1,
  5247. onLoad: onLoad$1,
  5248. onUnload: onUnload,
  5249. state: memory
  5250. })
  5251. ];
  5252. var RepresentSchema = [
  5253. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5254. memory: MemoryStore,
  5255. manual: ManualStore,
  5256. dataset: DatasetStore
  5257. })),
  5258. onHandler('onSetValue'),
  5259. defaulted('resetOnDom', false)
  5260. ];
  5261. var Representing = create$5({
  5262. fields: RepresentSchema,
  5263. name: 'representing',
  5264. active: ActiveRepresenting,
  5265. apis: RepresentApis,
  5266. extra: {
  5267. setValueFrom: function (component, source) {
  5268. var value = Representing.getValue(source);
  5269. Representing.setValue(component, value);
  5270. }
  5271. },
  5272. state: RepresentState
  5273. });
  5274. var api$1 = Dimension('width', function (element) {
  5275. return element.dom.offsetWidth;
  5276. });
  5277. var set$4 = function (element, h) {
  5278. return api$1.set(element, h);
  5279. };
  5280. var get$5 = function (element) {
  5281. return api$1.get(element);
  5282. };
  5283. var r$1 = function (left, top) {
  5284. var translate = function (x, y) {
  5285. return r$1(left + x, top + y);
  5286. };
  5287. return {
  5288. left: left,
  5289. top: top,
  5290. translate: translate
  5291. };
  5292. };
  5293. var SugarPosition = r$1;
  5294. var _sliderChangeEvent = 'slider.change.value';
  5295. var sliderChangeEvent = constant$1(_sliderChangeEvent);
  5296. var isTouchEvent = function (evt) {
  5297. return evt.type.indexOf('touch') !== -1;
  5298. };
  5299. var getEventSource = function (simulatedEvent) {
  5300. var evt = simulatedEvent.event.raw;
  5301. if (isTouchEvent(evt)) {
  5302. var touchEvent = evt;
  5303. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  5304. return SugarPosition(t.clientX, t.clientY);
  5305. }) : Optional.none();
  5306. } else {
  5307. var mouseEvent = evt;
  5308. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  5309. return SugarPosition(me.clientX, me.clientY);
  5310. }) : Optional.none();
  5311. }
  5312. };
  5313. var t = 'top', r = 'right', b = 'bottom', l = 'left';
  5314. var minX = function (detail) {
  5315. return detail.model.minX;
  5316. };
  5317. var minY = function (detail) {
  5318. return detail.model.minY;
  5319. };
  5320. var min1X = function (detail) {
  5321. return detail.model.minX - 1;
  5322. };
  5323. var min1Y = function (detail) {
  5324. return detail.model.minY - 1;
  5325. };
  5326. var maxX = function (detail) {
  5327. return detail.model.maxX;
  5328. };
  5329. var maxY = function (detail) {
  5330. return detail.model.maxY;
  5331. };
  5332. var max1X = function (detail) {
  5333. return detail.model.maxX + 1;
  5334. };
  5335. var max1Y = function (detail) {
  5336. return detail.model.maxY + 1;
  5337. };
  5338. var range$1 = function (detail, max, min) {
  5339. return max(detail) - min(detail);
  5340. };
  5341. var xRange = function (detail) {
  5342. return range$1(detail, maxX, minX);
  5343. };
  5344. var yRange = function (detail) {
  5345. return range$1(detail, maxY, minY);
  5346. };
  5347. var halfX = function (detail) {
  5348. return xRange(detail) / 2;
  5349. };
  5350. var halfY = function (detail) {
  5351. return yRange(detail) / 2;
  5352. };
  5353. var step = function (detail) {
  5354. return detail.stepSize;
  5355. };
  5356. var snap = function (detail) {
  5357. return detail.snapToGrid;
  5358. };
  5359. var snapStart = function (detail) {
  5360. return detail.snapStart;
  5361. };
  5362. var rounded = function (detail) {
  5363. return detail.rounded;
  5364. };
  5365. var hasEdge = function (detail, edgeName) {
  5366. return detail[edgeName + '-edge'] !== undefined;
  5367. };
  5368. var hasLEdge = function (detail) {
  5369. return hasEdge(detail, l);
  5370. };
  5371. var hasREdge = function (detail) {
  5372. return hasEdge(detail, r);
  5373. };
  5374. var hasTEdge = function (detail) {
  5375. return hasEdge(detail, t);
  5376. };
  5377. var hasBEdge = function (detail) {
  5378. return hasEdge(detail, b);
  5379. };
  5380. var currentValue = function (detail) {
  5381. return detail.model.value.get();
  5382. };
  5383. var xValue = function (x) {
  5384. return { x: x };
  5385. };
  5386. var yValue = function (y) {
  5387. return { y: y };
  5388. };
  5389. var xyValue = function (x, y) {
  5390. return {
  5391. x: x,
  5392. y: y
  5393. };
  5394. };
  5395. var fireSliderChange$3 = function (component, value) {
  5396. emitWith(component, sliderChangeEvent(), { value: value });
  5397. };
  5398. var setToTLEdgeXY = function (edge, detail) {
  5399. fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  5400. };
  5401. var setToTEdge = function (edge, detail) {
  5402. fireSliderChange$3(edge, yValue(min1Y(detail)));
  5403. };
  5404. var setToTEdgeXY = function (edge, detail) {
  5405. fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  5406. };
  5407. var setToTREdgeXY = function (edge, detail) {
  5408. fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  5409. };
  5410. var setToREdge = function (edge, detail) {
  5411. fireSliderChange$3(edge, xValue(max1X(detail)));
  5412. };
  5413. var setToREdgeXY = function (edge, detail) {
  5414. fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  5415. };
  5416. var setToBREdgeXY = function (edge, detail) {
  5417. fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  5418. };
  5419. var setToBEdge = function (edge, detail) {
  5420. fireSliderChange$3(edge, yValue(max1Y(detail)));
  5421. };
  5422. var setToBEdgeXY = function (edge, detail) {
  5423. fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  5424. };
  5425. var setToBLEdgeXY = function (edge, detail) {
  5426. fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  5427. };
  5428. var setToLEdge = function (edge, detail) {
  5429. fireSliderChange$3(edge, xValue(min1X(detail)));
  5430. };
  5431. var setToLEdgeXY = function (edge, detail) {
  5432. fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  5433. };
  5434. var reduceBy = function (value, min, max, step) {
  5435. if (value < min) {
  5436. return value;
  5437. } else if (value > max) {
  5438. return max;
  5439. } else if (value === min) {
  5440. return min - 1;
  5441. } else {
  5442. return Math.max(min, value - step);
  5443. }
  5444. };
  5445. var increaseBy = function (value, min, max, step) {
  5446. if (value > max) {
  5447. return value;
  5448. } else if (value < min) {
  5449. return min;
  5450. } else if (value === max) {
  5451. return max + 1;
  5452. } else {
  5453. return Math.min(max, value + step);
  5454. }
  5455. };
  5456. var capValue = function (value, min, max) {
  5457. return Math.max(min, Math.min(max, value));
  5458. };
  5459. var snapValueOf = function (value, min, max, step, snapStart) {
  5460. return snapStart.fold(function () {
  5461. var initValue = value - min;
  5462. var extraValue = Math.round(initValue / step) * step;
  5463. return capValue(min + extraValue, min - 1, max + 1);
  5464. }, function (start) {
  5465. var remainder = (value - start) % step;
  5466. var adjustment = Math.round(remainder / step);
  5467. var rawSteps = Math.floor((value - start) / step);
  5468. var maxSteps = Math.floor((max - start) / step);
  5469. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5470. var r = start + numSteps * step;
  5471. return Math.max(start, r);
  5472. });
  5473. };
  5474. var findOffsetOf = function (value, min, max) {
  5475. return Math.min(max, Math.max(value, min)) - min;
  5476. };
  5477. var findValueOf = function (args) {
  5478. var min = args.min, max = args.max, range = args.range, value = args.value, step = args.step, snap = args.snap, snapStart = args.snapStart, rounded = args.rounded, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, minBound = args.minBound, maxBound = args.maxBound, screenRange = args.screenRange;
  5479. var capMin = hasMinEdge ? min - 1 : min;
  5480. var capMax = hasMaxEdge ? max + 1 : max;
  5481. if (value < minBound) {
  5482. return capMin;
  5483. } else if (value > maxBound) {
  5484. return capMax;
  5485. } else {
  5486. var offset = findOffsetOf(value, minBound, maxBound);
  5487. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5488. if (snap && newValue >= min && newValue <= max) {
  5489. return snapValueOf(newValue, min, max, step, snapStart);
  5490. } else if (rounded) {
  5491. return Math.round(newValue);
  5492. } else {
  5493. return newValue;
  5494. }
  5495. }
  5496. };
  5497. var findOffsetOfValue$2 = function (args) {
  5498. var min = args.min, max = args.max, range = args.range, value = args.value, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, maxBound = args.maxBound, maxOffset = args.maxOffset, centerMinEdge = args.centerMinEdge, centerMaxEdge = args.centerMaxEdge;
  5499. if (value < min) {
  5500. return hasMinEdge ? 0 : centerMinEdge;
  5501. } else if (value > max) {
  5502. return hasMaxEdge ? maxBound : centerMaxEdge;
  5503. } else {
  5504. return (value - min) / range * maxOffset;
  5505. }
  5506. };
  5507. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5508. var getBounds$1 = function (component) {
  5509. return component.element.dom.getBoundingClientRect();
  5510. };
  5511. var getBoundsProperty = function (bounds, property) {
  5512. return bounds[property];
  5513. };
  5514. var getMinXBounds = function (component) {
  5515. var bounds = getBounds$1(component);
  5516. return getBoundsProperty(bounds, left);
  5517. };
  5518. var getMaxXBounds = function (component) {
  5519. var bounds = getBounds$1(component);
  5520. return getBoundsProperty(bounds, right);
  5521. };
  5522. var getMinYBounds = function (component) {
  5523. var bounds = getBounds$1(component);
  5524. return getBoundsProperty(bounds, top);
  5525. };
  5526. var getMaxYBounds = function (component) {
  5527. var bounds = getBounds$1(component);
  5528. return getBoundsProperty(bounds, bottom);
  5529. };
  5530. var getXScreenRange = function (component) {
  5531. var bounds = getBounds$1(component);
  5532. return getBoundsProperty(bounds, width);
  5533. };
  5534. var getYScreenRange = function (component) {
  5535. var bounds = getBounds$1(component);
  5536. return getBoundsProperty(bounds, height);
  5537. };
  5538. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5539. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5540. };
  5541. var getXCenterOffSetOf = function (component, spectrum) {
  5542. var componentBounds = getBounds$1(component);
  5543. var spectrumBounds = getBounds$1(spectrum);
  5544. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5545. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5546. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5547. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5548. };
  5549. var getYCenterOffSetOf = function (component, spectrum) {
  5550. var componentBounds = getBounds$1(component);
  5551. var spectrumBounds = getBounds$1(spectrum);
  5552. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5553. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5554. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5555. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5556. };
  5557. var fireSliderChange$2 = function (spectrum, value) {
  5558. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5559. };
  5560. var sliderValue$2 = function (x) {
  5561. return { x: x };
  5562. };
  5563. var findValueOfOffset$1 = function (spectrum, detail, left) {
  5564. var args = {
  5565. min: minX(detail),
  5566. max: maxX(detail),
  5567. range: xRange(detail),
  5568. value: left,
  5569. step: step(detail),
  5570. snap: snap(detail),
  5571. snapStart: snapStart(detail),
  5572. rounded: rounded(detail),
  5573. hasMinEdge: hasLEdge(detail),
  5574. hasMaxEdge: hasREdge(detail),
  5575. minBound: getMinXBounds(spectrum),
  5576. maxBound: getMaxXBounds(spectrum),
  5577. screenRange: getXScreenRange(spectrum)
  5578. };
  5579. return findValueOf(args);
  5580. };
  5581. var setValueFrom$2 = function (spectrum, detail, value) {
  5582. var xValue = findValueOfOffset$1(spectrum, detail, value);
  5583. var sliderVal = sliderValue$2(xValue);
  5584. fireSliderChange$2(spectrum, sliderVal);
  5585. return xValue;
  5586. };
  5587. var setToMin$2 = function (spectrum, detail) {
  5588. var min = minX(detail);
  5589. fireSliderChange$2(spectrum, sliderValue$2(min));
  5590. };
  5591. var setToMax$2 = function (spectrum, detail) {
  5592. var max = maxX(detail);
  5593. fireSliderChange$2(spectrum, sliderValue$2(max));
  5594. };
  5595. var moveBy$2 = function (direction, spectrum, detail) {
  5596. var f = direction > 0 ? increaseBy : reduceBy;
  5597. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5598. fireSliderChange$2(spectrum, sliderValue$2(xValue));
  5599. return Optional.some(xValue);
  5600. };
  5601. var handleMovement$2 = function (direction) {
  5602. return function (spectrum, detail) {
  5603. return moveBy$2(direction, spectrum, detail).map(always);
  5604. };
  5605. };
  5606. var getValueFromEvent$2 = function (simulatedEvent) {
  5607. var pos = getEventSource(simulatedEvent);
  5608. return pos.map(function (p) {
  5609. return p.left;
  5610. });
  5611. };
  5612. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5613. var minOffset = 0;
  5614. var maxOffset = getXScreenRange(spectrum);
  5615. var centerMinEdge = minEdge.bind(function (edge) {
  5616. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5617. }).getOr(minOffset);
  5618. var centerMaxEdge = maxEdge.bind(function (edge) {
  5619. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5620. }).getOr(maxOffset);
  5621. var args = {
  5622. min: minX(detail),
  5623. max: maxX(detail),
  5624. range: xRange(detail),
  5625. value: value,
  5626. hasMinEdge: hasLEdge(detail),
  5627. hasMaxEdge: hasREdge(detail),
  5628. minBound: getMinXBounds(spectrum),
  5629. minOffset: minOffset,
  5630. maxBound: getMaxXBounds(spectrum),
  5631. maxOffset: maxOffset,
  5632. centerMinEdge: centerMinEdge,
  5633. centerMaxEdge: centerMaxEdge
  5634. };
  5635. return findOffsetOfValue$2(args);
  5636. };
  5637. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5638. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5639. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5640. };
  5641. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5642. var value = currentValue(detail);
  5643. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5644. var thumbRadius = get$5(thumb.element) / 2;
  5645. set$5(thumb.element, 'left', pos - thumbRadius + 'px');
  5646. };
  5647. var onLeft$2 = handleMovement$2(-1);
  5648. var onRight$2 = handleMovement$2(1);
  5649. var onUp$2 = Optional.none;
  5650. var onDown$2 = Optional.none;
  5651. var edgeActions$2 = {
  5652. 'top-left': Optional.none(),
  5653. 'top': Optional.none(),
  5654. 'top-right': Optional.none(),
  5655. 'right': Optional.some(setToREdge),
  5656. 'bottom-right': Optional.none(),
  5657. 'bottom': Optional.none(),
  5658. 'bottom-left': Optional.none(),
  5659. 'left': Optional.some(setToLEdge)
  5660. };
  5661. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5662. __proto__: null,
  5663. setValueFrom: setValueFrom$2,
  5664. setToMin: setToMin$2,
  5665. setToMax: setToMax$2,
  5666. findValueOfOffset: findValueOfOffset$1,
  5667. getValueFromEvent: getValueFromEvent$2,
  5668. findPositionOfValue: findPositionOfValue$1,
  5669. setPositionFromValue: setPositionFromValue$2,
  5670. onLeft: onLeft$2,
  5671. onRight: onRight$2,
  5672. onUp: onUp$2,
  5673. onDown: onDown$2,
  5674. edgeActions: edgeActions$2
  5675. });
  5676. var fireSliderChange$1 = function (spectrum, value) {
  5677. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5678. };
  5679. var sliderValue$1 = function (y) {
  5680. return { y: y };
  5681. };
  5682. var findValueOfOffset = function (spectrum, detail, top) {
  5683. var args = {
  5684. min: minY(detail),
  5685. max: maxY(detail),
  5686. range: yRange(detail),
  5687. value: top,
  5688. step: step(detail),
  5689. snap: snap(detail),
  5690. snapStart: snapStart(detail),
  5691. rounded: rounded(detail),
  5692. hasMinEdge: hasTEdge(detail),
  5693. hasMaxEdge: hasBEdge(detail),
  5694. minBound: getMinYBounds(spectrum),
  5695. maxBound: getMaxYBounds(spectrum),
  5696. screenRange: getYScreenRange(spectrum)
  5697. };
  5698. return findValueOf(args);
  5699. };
  5700. var setValueFrom$1 = function (spectrum, detail, value) {
  5701. var yValue = findValueOfOffset(spectrum, detail, value);
  5702. var sliderVal = sliderValue$1(yValue);
  5703. fireSliderChange$1(spectrum, sliderVal);
  5704. return yValue;
  5705. };
  5706. var setToMin$1 = function (spectrum, detail) {
  5707. var min = minY(detail);
  5708. fireSliderChange$1(spectrum, sliderValue$1(min));
  5709. };
  5710. var setToMax$1 = function (spectrum, detail) {
  5711. var max = maxY(detail);
  5712. fireSliderChange$1(spectrum, sliderValue$1(max));
  5713. };
  5714. var moveBy$1 = function (direction, spectrum, detail) {
  5715. var f = direction > 0 ? increaseBy : reduceBy;
  5716. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5717. fireSliderChange$1(spectrum, sliderValue$1(yValue));
  5718. return Optional.some(yValue);
  5719. };
  5720. var handleMovement$1 = function (direction) {
  5721. return function (spectrum, detail) {
  5722. return moveBy$1(direction, spectrum, detail).map(always);
  5723. };
  5724. };
  5725. var getValueFromEvent$1 = function (simulatedEvent) {
  5726. var pos = getEventSource(simulatedEvent);
  5727. return pos.map(function (p) {
  5728. return p.top;
  5729. });
  5730. };
  5731. var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) {
  5732. var minOffset = 0;
  5733. var maxOffset = getYScreenRange(spectrum);
  5734. var centerMinEdge = minEdge.bind(function (edge) {
  5735. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5736. }).getOr(minOffset);
  5737. var centerMaxEdge = maxEdge.bind(function (edge) {
  5738. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5739. }).getOr(maxOffset);
  5740. var args = {
  5741. min: minY(detail),
  5742. max: maxY(detail),
  5743. range: yRange(detail),
  5744. value: value,
  5745. hasMinEdge: hasTEdge(detail),
  5746. hasMaxEdge: hasBEdge(detail),
  5747. minBound: getMinYBounds(spectrum),
  5748. minOffset: minOffset,
  5749. maxBound: getMaxYBounds(spectrum),
  5750. maxOffset: maxOffset,
  5751. centerMinEdge: centerMinEdge,
  5752. centerMaxEdge: centerMaxEdge
  5753. };
  5754. return findOffsetOfValue$2(args);
  5755. };
  5756. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5757. var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  5758. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5759. };
  5760. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5761. var value = currentValue(detail);
  5762. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5763. var thumbRadius = get$7(thumb.element) / 2;
  5764. set$5(thumb.element, 'top', pos - thumbRadius + 'px');
  5765. };
  5766. var onLeft$1 = Optional.none;
  5767. var onRight$1 = Optional.none;
  5768. var onUp$1 = handleMovement$1(-1);
  5769. var onDown$1 = handleMovement$1(1);
  5770. var edgeActions$1 = {
  5771. 'top-left': Optional.none(),
  5772. 'top': Optional.some(setToTEdge),
  5773. 'top-right': Optional.none(),
  5774. 'right': Optional.none(),
  5775. 'bottom-right': Optional.none(),
  5776. 'bottom': Optional.some(setToBEdge),
  5777. 'bottom-left': Optional.none(),
  5778. 'left': Optional.none()
  5779. };
  5780. var VerticalModel = /*#__PURE__*/Object.freeze({
  5781. __proto__: null,
  5782. setValueFrom: setValueFrom$1,
  5783. setToMin: setToMin$1,
  5784. setToMax: setToMax$1,
  5785. findValueOfOffset: findValueOfOffset,
  5786. getValueFromEvent: getValueFromEvent$1,
  5787. findPositionOfValue: findPositionOfValue,
  5788. setPositionFromValue: setPositionFromValue$1,
  5789. onLeft: onLeft$1,
  5790. onRight: onRight$1,
  5791. onUp: onUp$1,
  5792. onDown: onDown$1,
  5793. edgeActions: edgeActions$1
  5794. });
  5795. var fireSliderChange = function (spectrum, value) {
  5796. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5797. };
  5798. var sliderValue = function (x, y) {
  5799. return {
  5800. x: x,
  5801. y: y
  5802. };
  5803. };
  5804. var setValueFrom = function (spectrum, detail, value) {
  5805. var xValue = findValueOfOffset$1(spectrum, detail, value.left);
  5806. var yValue = findValueOfOffset(spectrum, detail, value.top);
  5807. var val = sliderValue(xValue, yValue);
  5808. fireSliderChange(spectrum, val);
  5809. return val;
  5810. };
  5811. var moveBy = function (direction, isVerticalMovement, spectrum, detail) {
  5812. var f = direction > 0 ? increaseBy : reduceBy;
  5813. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5814. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5815. fireSliderChange(spectrum, sliderValue(xValue, yValue));
  5816. return Optional.some(xValue);
  5817. };
  5818. var handleMovement = function (direction, isVerticalMovement) {
  5819. return function (spectrum, detail) {
  5820. return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  5821. };
  5822. };
  5823. var setToMin = function (spectrum, detail) {
  5824. var mX = minX(detail);
  5825. var mY = minY(detail);
  5826. fireSliderChange(spectrum, sliderValue(mX, mY));
  5827. };
  5828. var setToMax = function (spectrum, detail) {
  5829. var mX = maxX(detail);
  5830. var mY = maxY(detail);
  5831. fireSliderChange(spectrum, sliderValue(mX, mY));
  5832. };
  5833. var getValueFromEvent = function (simulatedEvent) {
  5834. return getEventSource(simulatedEvent);
  5835. };
  5836. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5837. var value = currentValue(detail);
  5838. var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5839. var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5840. var thumbXRadius = get$5(thumb.element) / 2;
  5841. var thumbYRadius = get$7(thumb.element) / 2;
  5842. set$5(thumb.element, 'left', xPos - thumbXRadius + 'px');
  5843. set$5(thumb.element, 'top', yPos - thumbYRadius + 'px');
  5844. };
  5845. var onLeft = handleMovement(-1, false);
  5846. var onRight = handleMovement(1, false);
  5847. var onUp = handleMovement(-1, true);
  5848. var onDown = handleMovement(1, true);
  5849. var edgeActions = {
  5850. 'top-left': Optional.some(setToTLEdgeXY),
  5851. 'top': Optional.some(setToTEdgeXY),
  5852. 'top-right': Optional.some(setToTREdgeXY),
  5853. 'right': Optional.some(setToREdgeXY),
  5854. 'bottom-right': Optional.some(setToBREdgeXY),
  5855. 'bottom': Optional.some(setToBEdgeXY),
  5856. 'bottom-left': Optional.some(setToBLEdgeXY),
  5857. 'left': Optional.some(setToLEdgeXY)
  5858. };
  5859. var TwoDModel = /*#__PURE__*/Object.freeze({
  5860. __proto__: null,
  5861. setValueFrom: setValueFrom,
  5862. setToMin: setToMin,
  5863. setToMax: setToMax,
  5864. getValueFromEvent: getValueFromEvent,
  5865. setPositionFromValue: setPositionFromValue,
  5866. onLeft: onLeft,
  5867. onRight: onRight,
  5868. onUp: onUp,
  5869. onDown: onDown,
  5870. edgeActions: edgeActions
  5871. });
  5872. var SliderSchema = [
  5873. defaulted('stepSize', 1),
  5874. defaulted('onChange', noop),
  5875. defaulted('onChoose', noop),
  5876. defaulted('onInit', noop),
  5877. defaulted('onDragStart', noop),
  5878. defaulted('onDragEnd', noop),
  5879. defaulted('snapToGrid', false),
  5880. defaulted('rounded', true),
  5881. option('snapStart'),
  5882. requiredOf('model', choose$1('mode', {
  5883. x: [
  5884. defaulted('minX', 0),
  5885. defaulted('maxX', 100),
  5886. customField('value', function (spec) {
  5887. return Cell(spec.mode.minX);
  5888. }),
  5889. required$1('getInitialValue'),
  5890. output('manager', HorizontalModel)
  5891. ],
  5892. y: [
  5893. defaulted('minY', 0),
  5894. defaulted('maxY', 100),
  5895. customField('value', function (spec) {
  5896. return Cell(spec.mode.minY);
  5897. }),
  5898. required$1('getInitialValue'),
  5899. output('manager', VerticalModel)
  5900. ],
  5901. xy: [
  5902. defaulted('minX', 0),
  5903. defaulted('maxX', 100),
  5904. defaulted('minY', 0),
  5905. defaulted('maxY', 100),
  5906. customField('value', function (spec) {
  5907. return Cell({
  5908. x: spec.mode.minX,
  5909. y: spec.mode.minY
  5910. });
  5911. }),
  5912. required$1('getInitialValue'),
  5913. output('manager', TwoDModel)
  5914. ]
  5915. })),
  5916. field$1('sliderBehaviours', [
  5917. Keying,
  5918. Representing
  5919. ]),
  5920. customField('mouseIsDown', function () {
  5921. return Cell(false);
  5922. })
  5923. ];
  5924. var mouseReleased = constant$1('mouse.released');
  5925. var sketch$9 = function (detail, components, _spec, _externals) {
  5926. var _a;
  5927. var getThumb = function (component) {
  5928. return getPartOrDie(component, detail, 'thumb');
  5929. };
  5930. var getSpectrum = function (component) {
  5931. return getPartOrDie(component, detail, 'spectrum');
  5932. };
  5933. var getLeftEdge = function (component) {
  5934. return getPart(component, detail, 'left-edge');
  5935. };
  5936. var getRightEdge = function (component) {
  5937. return getPart(component, detail, 'right-edge');
  5938. };
  5939. var getTopEdge = function (component) {
  5940. return getPart(component, detail, 'top-edge');
  5941. };
  5942. var getBottomEdge = function (component) {
  5943. return getPart(component, detail, 'bottom-edge');
  5944. };
  5945. var modelDetail = detail.model;
  5946. var model = modelDetail.manager;
  5947. var refresh = function (slider, thumb) {
  5948. model.setPositionFromValue(slider, thumb, detail, {
  5949. getLeftEdge: getLeftEdge,
  5950. getRightEdge: getRightEdge,
  5951. getTopEdge: getTopEdge,
  5952. getBottomEdge: getBottomEdge,
  5953. getSpectrum: getSpectrum
  5954. });
  5955. };
  5956. var setValue = function (slider, newValue) {
  5957. modelDetail.value.set(newValue);
  5958. var thumb = getThumb(slider);
  5959. refresh(slider, thumb);
  5960. };
  5961. var changeValue = function (slider, newValue) {
  5962. setValue(slider, newValue);
  5963. var thumb = getThumb(slider);
  5964. detail.onChange(slider, thumb, newValue);
  5965. return Optional.some(true);
  5966. };
  5967. var resetToMin = function (slider) {
  5968. model.setToMin(slider, detail);
  5969. };
  5970. var resetToMax = function (slider) {
  5971. model.setToMax(slider, detail);
  5972. };
  5973. var choose = function (slider) {
  5974. var fireOnChoose = function () {
  5975. getPart(slider, detail, 'thumb').each(function (thumb) {
  5976. var value = modelDetail.value.get();
  5977. detail.onChoose(slider, thumb, value);
  5978. });
  5979. };
  5980. var wasDown = detail.mouseIsDown.get();
  5981. detail.mouseIsDown.set(false);
  5982. if (wasDown) {
  5983. fireOnChoose();
  5984. }
  5985. };
  5986. var onDragStart = function (slider, simulatedEvent) {
  5987. simulatedEvent.stop();
  5988. detail.mouseIsDown.set(true);
  5989. detail.onDragStart(slider, getThumb(slider));
  5990. };
  5991. var onDragEnd = function (slider, simulatedEvent) {
  5992. simulatedEvent.stop();
  5993. detail.onDragEnd(slider, getThumb(slider));
  5994. choose(slider);
  5995. };
  5996. return {
  5997. uid: detail.uid,
  5998. dom: detail.dom,
  5999. components: components,
  6000. behaviours: augment(detail.sliderBehaviours, [
  6001. Keying.config({
  6002. mode: 'special',
  6003. focusIn: function (slider) {
  6004. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  6005. }
  6006. }),
  6007. Representing.config({
  6008. store: {
  6009. mode: 'manual',
  6010. getValue: function (_) {
  6011. return modelDetail.value.get();
  6012. }
  6013. }
  6014. }),
  6015. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  6016. ]),
  6017. events: derive$3([
  6018. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  6019. changeValue(slider, simulatedEvent.event.value);
  6020. }),
  6021. runOnAttached(function (slider, _simulatedEvent) {
  6022. var getInitial = modelDetail.getInitialValue();
  6023. modelDetail.value.set(getInitial);
  6024. var thumb = getThumb(slider);
  6025. refresh(slider, thumb);
  6026. var spectrum = getSpectrum(slider);
  6027. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  6028. }),
  6029. run(touchstart(), onDragStart),
  6030. run(touchend(), onDragEnd),
  6031. run(mousedown(), onDragStart),
  6032. run(mouseup(), onDragEnd)
  6033. ]),
  6034. apis: {
  6035. resetToMin: resetToMin,
  6036. resetToMax: resetToMax,
  6037. setValue: setValue,
  6038. refresh: refresh
  6039. },
  6040. domModification: { styles: { position: 'relative' } }
  6041. };
  6042. };
  6043. var Slider = composite({
  6044. name: 'Slider',
  6045. configFields: SliderSchema,
  6046. partFields: SliderParts,
  6047. factory: sketch$9,
  6048. apis: {
  6049. setValue: function (apis, slider, value) {
  6050. apis.setValue(slider, value);
  6051. },
  6052. resetToMin: function (apis, slider) {
  6053. apis.resetToMin(slider);
  6054. },
  6055. resetToMax: function (apis, slider) {
  6056. apis.resetToMax(slider);
  6057. },
  6058. refresh: function (apis, slider) {
  6059. apis.refresh(slider);
  6060. }
  6061. }
  6062. });
  6063. var button = function (realm, clazz, makeItems, editor) {
  6064. return forToolbar(clazz, function () {
  6065. var items = makeItems();
  6066. realm.setContextToolbar([{
  6067. label: clazz + ' group',
  6068. items: items
  6069. }]);
  6070. }, {}, editor);
  6071. };
  6072. var BLACK = -1;
  6073. var makeSlider$1 = function (spec$1) {
  6074. var getColor = function (hue) {
  6075. if (hue < 0) {
  6076. return 'black';
  6077. } else if (hue > 360) {
  6078. return 'white';
  6079. } else {
  6080. return 'hsl(' + hue + ', 100%, 50%)';
  6081. }
  6082. };
  6083. var onInit = function (slider, thumb, spectrum, value) {
  6084. var color = getColor(value.x());
  6085. set$5(thumb.element, 'background-color', color);
  6086. };
  6087. var onChange = function (slider, thumb, value) {
  6088. var color = getColor(value.x());
  6089. set$5(thumb.element, 'background-color', color);
  6090. spec$1.onChange(slider, thumb, color);
  6091. };
  6092. return Slider.sketch({
  6093. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  6094. components: [
  6095. Slider.parts['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  6096. Slider.parts.spectrum({
  6097. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  6098. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  6099. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6100. }),
  6101. Slider.parts['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  6102. Slider.parts.thumb({
  6103. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6104. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6105. })
  6106. ],
  6107. onChange: onChange,
  6108. onDragStart: function (slider, thumb) {
  6109. Toggling.on(thumb);
  6110. },
  6111. onDragEnd: function (slider, thumb) {
  6112. Toggling.off(thumb);
  6113. },
  6114. onInit: onInit,
  6115. stepSize: 10,
  6116. model: {
  6117. mode: 'x',
  6118. minX: 0,
  6119. maxX: 360,
  6120. getInitialValue: function () {
  6121. return { x: spec$1.getInitialValue() };
  6122. }
  6123. },
  6124. sliderBehaviours: derive$2([orientation(Slider.refresh)])
  6125. });
  6126. };
  6127. var makeItems$1 = function (spec) {
  6128. return [makeSlider$1(spec)];
  6129. };
  6130. var sketch$8 = function (realm, editor) {
  6131. var spec = {
  6132. onChange: function (slider, thumb, color) {
  6133. editor.undoManager.transact(function () {
  6134. editor.formatter.apply('forecolor', { value: color });
  6135. editor.nodeChanged();
  6136. });
  6137. },
  6138. getInitialValue: constant$1(BLACK)
  6139. };
  6140. return button(realm, 'color-levels', function () {
  6141. return makeItems$1(spec);
  6142. }, editor);
  6143. };
  6144. var candidatesArray = [
  6145. '9px',
  6146. '10px',
  6147. '11px',
  6148. '12px',
  6149. '14px',
  6150. '16px',
  6151. '18px',
  6152. '20px',
  6153. '24px',
  6154. '32px',
  6155. '36px'
  6156. ];
  6157. var defaultSize = 'medium';
  6158. var defaultIndex = 2;
  6159. var indexToSize = function (index) {
  6160. return Optional.from(candidatesArray[index]);
  6161. };
  6162. var sizeToIndex = function (size) {
  6163. return findIndex$1(candidatesArray, function (v) {
  6164. return v === size;
  6165. });
  6166. };
  6167. var getRawOrComputed = function (isRoot, rawStart) {
  6168. var optStart = isElement(rawStart) ? Optional.some(rawStart) : parent(rawStart).filter(isElement);
  6169. return optStart.map(function (start) {
  6170. var inline = closest$2(start, function (elem) {
  6171. return getRaw(elem, 'font-size').isSome();
  6172. }, isRoot).bind(function (elem) {
  6173. return getRaw(elem, 'font-size');
  6174. });
  6175. return inline.getOrThunk(function () {
  6176. return get$8(start, 'font-size');
  6177. });
  6178. }).getOr('');
  6179. };
  6180. var getSize = function (editor) {
  6181. var node = editor.selection.getStart();
  6182. var elem = SugarElement.fromDom(node);
  6183. var root = SugarElement.fromDom(editor.getBody());
  6184. var isRoot = function (e) {
  6185. return eq(root, e);
  6186. };
  6187. var elemSize = getRawOrComputed(isRoot, elem);
  6188. return find$2(candidatesArray, function (size) {
  6189. return elemSize === size;
  6190. }).getOr(defaultSize);
  6191. };
  6192. var applySize = function (editor, value) {
  6193. var currentValue = getSize(editor);
  6194. if (currentValue !== value) {
  6195. editor.execCommand('fontSize', false, value);
  6196. }
  6197. };
  6198. var get$4 = function (editor) {
  6199. var size = getSize(editor);
  6200. return sizeToIndex(size).getOr(defaultIndex);
  6201. };
  6202. var apply = function (editor, index) {
  6203. indexToSize(index).each(function (size) {
  6204. applySize(editor, size);
  6205. });
  6206. };
  6207. var candidates = constant$1(candidatesArray);
  6208. var schema$9 = objOfOnly([
  6209. required$1('getInitialValue'),
  6210. required$1('onChange'),
  6211. required$1('category'),
  6212. required$1('sizes')
  6213. ]);
  6214. var sketch$7 = function (rawSpec) {
  6215. var spec$1 = asRawOrDie$1('SizeSlider', schema$9, rawSpec);
  6216. var isValidValue = function (valueIndex) {
  6217. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6218. };
  6219. var onChange = function (slider, thumb, valueIndex) {
  6220. var index = valueIndex.x();
  6221. if (isValidValue(index)) {
  6222. spec$1.onChange(index);
  6223. }
  6224. };
  6225. return Slider.sketch({
  6226. dom: {
  6227. tag: 'div',
  6228. classes: [
  6229. resolve('slider-' + spec$1.category + '-size-container'),
  6230. resolve('slider'),
  6231. resolve('slider-size-container')
  6232. ]
  6233. },
  6234. onChange: onChange,
  6235. onDragStart: function (slider, thumb) {
  6236. Toggling.on(thumb);
  6237. },
  6238. onDragEnd: function (slider, thumb) {
  6239. Toggling.off(thumb);
  6240. },
  6241. model: {
  6242. mode: 'x',
  6243. minX: 0,
  6244. maxX: spec$1.sizes.length - 1,
  6245. getInitialValue: function () {
  6246. return { x: spec$1.getInitialValue() };
  6247. }
  6248. },
  6249. stepSize: 1,
  6250. snapToGrid: true,
  6251. sliderBehaviours: derive$2([orientation(Slider.refresh)]),
  6252. components: [
  6253. Slider.parts.spectrum({
  6254. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6255. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  6256. }),
  6257. Slider.parts.thumb({
  6258. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6259. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6260. })
  6261. ]
  6262. });
  6263. };
  6264. var sizes = candidates();
  6265. var makeSlider = function (spec) {
  6266. return sketch$7({
  6267. onChange: spec.onChange,
  6268. sizes: sizes,
  6269. category: 'font',
  6270. getInitialValue: spec.getInitialValue
  6271. });
  6272. };
  6273. var makeItems = function (spec$1) {
  6274. return [
  6275. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6276. makeSlider(spec$1),
  6277. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6278. ];
  6279. };
  6280. var sketch$6 = function (realm, editor) {
  6281. var spec = {
  6282. onChange: function (value) {
  6283. apply(editor, value);
  6284. },
  6285. getInitialValue: function () {
  6286. return get$4(editor);
  6287. }
  6288. };
  6289. return button(realm, 'font-size', function () {
  6290. return makeItems(spec);
  6291. }, editor);
  6292. };
  6293. var record = function (spec) {
  6294. var uid = isSketchSpec$1(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento');
  6295. var get = function (anyInSystem) {
  6296. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6297. };
  6298. var getOpt = function (anyInSystem) {
  6299. return anyInSystem.getSystem().getByUid(uid).toOptional();
  6300. };
  6301. var asSpec = function () {
  6302. return __assign(__assign({}, spec), { uid: uid });
  6303. };
  6304. return {
  6305. get: get,
  6306. getOpt: getOpt,
  6307. asSpec: asSpec
  6308. };
  6309. };
  6310. var promise = function () {
  6311. var Promise = function (fn) {
  6312. if (typeof this !== 'object') {
  6313. throw new TypeError('Promises must be constructed via new');
  6314. }
  6315. if (typeof fn !== 'function') {
  6316. throw new TypeError('not a function');
  6317. }
  6318. this._state = null;
  6319. this._value = null;
  6320. this._deferreds = [];
  6321. doResolve(fn, bind(resolve, this), bind(reject, this));
  6322. };
  6323. var anyWindow = window;
  6324. var asap = Promise.immediateFn || typeof anyWindow.setImmediate === 'function' && anyWindow.setImmediate || function (fn) {
  6325. return setTimeout(fn, 1);
  6326. };
  6327. var bind = function (fn, thisArg) {
  6328. return function () {
  6329. var args = [];
  6330. for (var _i = 0; _i < arguments.length; _i++) {
  6331. args[_i] = arguments[_i];
  6332. }
  6333. return fn.apply(thisArg, args);
  6334. };
  6335. };
  6336. var isArray = Array.isArray || function (value) {
  6337. return Object.prototype.toString.call(value) === '[object Array]';
  6338. };
  6339. function handle(deferred) {
  6340. var me = this;
  6341. if (this._state === null) {
  6342. this._deferreds.push(deferred);
  6343. return;
  6344. }
  6345. asap(function () {
  6346. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  6347. if (cb === null) {
  6348. (me._state ? deferred.resolve : deferred.reject)(me._value);
  6349. return;
  6350. }
  6351. var ret;
  6352. try {
  6353. ret = cb(me._value);
  6354. } catch (e) {
  6355. deferred.reject(e);
  6356. return;
  6357. }
  6358. deferred.resolve(ret);
  6359. });
  6360. }
  6361. function resolve(newValue) {
  6362. try {
  6363. if (newValue === this) {
  6364. throw new TypeError('A promise cannot be resolved with itself.');
  6365. }
  6366. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6367. var then = newValue.then;
  6368. if (typeof then === 'function') {
  6369. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  6370. return;
  6371. }
  6372. }
  6373. this._state = true;
  6374. this._value = newValue;
  6375. finale.call(this);
  6376. } catch (e) {
  6377. reject.call(this, e);
  6378. }
  6379. }
  6380. function reject(newValue) {
  6381. this._state = false;
  6382. this._value = newValue;
  6383. finale.call(this);
  6384. }
  6385. function finale() {
  6386. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  6387. var deferred = _a[_i];
  6388. handle.call(this, deferred);
  6389. }
  6390. this._deferreds = [];
  6391. }
  6392. function Handler(onFulfilled, onRejected, resolve, reject) {
  6393. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6394. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6395. this.resolve = resolve;
  6396. this.reject = reject;
  6397. }
  6398. var doResolve = function (fn, onFulfilled, onRejected) {
  6399. var done = false;
  6400. try {
  6401. fn(function (value) {
  6402. if (done) {
  6403. return;
  6404. }
  6405. done = true;
  6406. onFulfilled(value);
  6407. }, function (reason) {
  6408. if (done) {
  6409. return;
  6410. }
  6411. done = true;
  6412. onRejected(reason);
  6413. });
  6414. } catch (ex) {
  6415. if (done) {
  6416. return;
  6417. }
  6418. done = true;
  6419. onRejected(ex);
  6420. }
  6421. };
  6422. Promise.prototype.catch = function (onRejected) {
  6423. return this.then(null, onRejected);
  6424. };
  6425. Promise.prototype.then = function (onFulfilled, onRejected) {
  6426. var me = this;
  6427. return new Promise(function (resolve, reject) {
  6428. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  6429. });
  6430. };
  6431. Promise.all = function () {
  6432. var values = [];
  6433. for (var _i = 0; _i < arguments.length; _i++) {
  6434. values[_i] = arguments[_i];
  6435. }
  6436. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  6437. return new Promise(function (resolve, reject) {
  6438. if (args.length === 0) {
  6439. return resolve([]);
  6440. }
  6441. var remaining = args.length;
  6442. var res = function (i, val) {
  6443. try {
  6444. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6445. var then = val.then;
  6446. if (typeof then === 'function') {
  6447. then.call(val, function (val) {
  6448. res(i, val);
  6449. }, reject);
  6450. return;
  6451. }
  6452. }
  6453. args[i] = val;
  6454. if (--remaining === 0) {
  6455. resolve(args);
  6456. }
  6457. } catch (ex) {
  6458. reject(ex);
  6459. }
  6460. };
  6461. for (var i = 0; i < args.length; i++) {
  6462. res(i, args[i]);
  6463. }
  6464. });
  6465. };
  6466. Promise.resolve = function (value) {
  6467. if (value && typeof value === 'object' && value.constructor === Promise) {
  6468. return value;
  6469. }
  6470. return new Promise(function (resolve) {
  6471. resolve(value);
  6472. });
  6473. };
  6474. Promise.reject = function (reason) {
  6475. return new Promise(function (resolve, reject) {
  6476. reject(reason);
  6477. });
  6478. };
  6479. Promise.race = function (values) {
  6480. return new Promise(function (resolve, reject) {
  6481. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  6482. var value = values_1[_i];
  6483. value.then(resolve, reject);
  6484. }
  6485. });
  6486. };
  6487. return Promise;
  6488. };
  6489. var Promise$2 = window.Promise ? window.Promise : promise();
  6490. var blobToDataUri = function (blob) {
  6491. return new Promise$2(function (resolve) {
  6492. var reader = new FileReader();
  6493. reader.onloadend = function () {
  6494. resolve(reader.result);
  6495. };
  6496. reader.readAsDataURL(blob);
  6497. });
  6498. };
  6499. var blobToBase64$1 = function (blob) {
  6500. return blobToDataUri(blob).then(function (dataUri) {
  6501. return dataUri.split(',')[1];
  6502. });
  6503. };
  6504. var blobToBase64 = function (blob) {
  6505. return blobToBase64$1(blob);
  6506. };
  6507. var addImage = function (editor, blob) {
  6508. blobToBase64(blob).then(function (base64) {
  6509. editor.undoManager.transact(function () {
  6510. var cache = editor.editorUpload.blobCache;
  6511. var info = cache.create(generate$4('mceu'), blob, base64);
  6512. cache.add(info);
  6513. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6514. editor.insertContent(img);
  6515. });
  6516. });
  6517. };
  6518. var extractBlob = function (simulatedEvent) {
  6519. var event = simulatedEvent.event.raw;
  6520. var files = event.target.files || event.dataTransfer.files;
  6521. return Optional.from(files[0]);
  6522. };
  6523. var sketch$5 = function (editor) {
  6524. var pickerDom = {
  6525. tag: 'input',
  6526. attributes: {
  6527. accept: 'image/*',
  6528. type: 'file',
  6529. title: ''
  6530. },
  6531. styles: {
  6532. visibility: 'hidden',
  6533. position: 'absolute'
  6534. }
  6535. };
  6536. var memPicker = record({
  6537. dom: pickerDom,
  6538. events: derive$3([
  6539. cutter(click()),
  6540. run(change(), function (picker, simulatedEvent) {
  6541. extractBlob(simulatedEvent).each(function (blob) {
  6542. addImage(editor, blob);
  6543. });
  6544. })
  6545. ])
  6546. });
  6547. return Button.sketch({
  6548. dom: getToolbarIconButton('image', editor),
  6549. components: [memPicker.asSpec()],
  6550. action: function (button) {
  6551. var picker = memPicker.get(button);
  6552. picker.element.dom.click();
  6553. }
  6554. });
  6555. };
  6556. var get$3 = function (element) {
  6557. return element.dom.textContent;
  6558. };
  6559. var set$3 = function (element, value) {
  6560. element.dom.textContent = value;
  6561. };
  6562. var isNotEmpty = function (val) {
  6563. return val.length > 0;
  6564. };
  6565. var defaultToEmpty = function (str) {
  6566. return str === undefined || str === null ? '' : str;
  6567. };
  6568. var noLink = function (editor) {
  6569. var text = editor.selection.getContent({ format: 'text' });
  6570. return {
  6571. url: '',
  6572. text: text,
  6573. title: '',
  6574. target: '',
  6575. link: Optional.none()
  6576. };
  6577. };
  6578. var fromLink = function (link) {
  6579. var text = get$3(link);
  6580. var url = get$b(link, 'href');
  6581. var title = get$b(link, 'title');
  6582. var target = get$b(link, 'target');
  6583. return {
  6584. url: defaultToEmpty(url),
  6585. text: text !== url ? defaultToEmpty(text) : '',
  6586. title: defaultToEmpty(title),
  6587. target: defaultToEmpty(target),
  6588. link: Optional.some(link)
  6589. };
  6590. };
  6591. var getInfo = function (editor) {
  6592. return query(editor).fold(function () {
  6593. return noLink(editor);
  6594. }, function (link) {
  6595. return fromLink(link);
  6596. });
  6597. };
  6598. var wasSimple = function (link) {
  6599. var prevHref = get$b(link, 'href');
  6600. var prevText = get$3(link);
  6601. return prevHref === prevText;
  6602. };
  6603. var getTextToApply = function (link, url, info) {
  6604. return info.text.toOptional().filter(isNotEmpty).fold(function () {
  6605. return wasSimple(link) ? Optional.some(url) : Optional.none();
  6606. }, Optional.some);
  6607. };
  6608. var unlinkIfRequired = function (editor, info) {
  6609. var activeLink = info.link.bind(identity);
  6610. activeLink.each(function (_link) {
  6611. editor.execCommand('unlink');
  6612. });
  6613. };
  6614. var getAttrs = function (url, info) {
  6615. var attrs = {};
  6616. attrs.href = url;
  6617. info.title.toOptional().filter(isNotEmpty).each(function (title) {
  6618. attrs.title = title;
  6619. });
  6620. info.target.toOptional().filter(isNotEmpty).each(function (target) {
  6621. attrs.target = target;
  6622. });
  6623. return attrs;
  6624. };
  6625. var applyInfo = function (editor, info) {
  6626. info.url.toOptional().filter(isNotEmpty).fold(function () {
  6627. unlinkIfRequired(editor, info);
  6628. }, function (url) {
  6629. var attrs = getAttrs(url, info);
  6630. var activeLink = info.link.bind(identity);
  6631. activeLink.fold(function () {
  6632. var text = info.text.toOptional().filter(isNotEmpty).getOr(url);
  6633. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6634. }, function (link) {
  6635. var text = getTextToApply(link, url, info);
  6636. setAll$1(link, attrs);
  6637. text.each(function (newText) {
  6638. set$3(link, newText);
  6639. });
  6640. });
  6641. });
  6642. };
  6643. var query = function (editor) {
  6644. var start = SugarElement.fromDom(editor.selection.getStart());
  6645. return closest$1(start, 'a');
  6646. };
  6647. var platform = detect$1();
  6648. var preserve$1 = function (f, editor) {
  6649. var rng = editor.selection.getRng();
  6650. f();
  6651. editor.selection.setRng(rng);
  6652. };
  6653. var forAndroid = function (editor, f) {
  6654. var wrapper = platform.os.isAndroid() ? preserve$1 : apply$1;
  6655. wrapper(f, editor);
  6656. };
  6657. var events$4 = function (name, eventHandlers) {
  6658. var events = derive$3(eventHandlers);
  6659. return create$5({
  6660. fields: [required$1('enabled')],
  6661. name: name,
  6662. active: { events: constant$1(events) }
  6663. });
  6664. };
  6665. var config = function (name, eventHandlers) {
  6666. var me = events$4(name, eventHandlers);
  6667. return {
  6668. key: name,
  6669. value: {
  6670. config: {},
  6671. me: me,
  6672. configAsRaw: constant$1({}),
  6673. initialConfig: {},
  6674. state: NoState
  6675. }
  6676. };
  6677. };
  6678. var getCurrent = function (component, composeConfig, _composeState) {
  6679. return composeConfig.find(component);
  6680. };
  6681. var ComposeApis = /*#__PURE__*/Object.freeze({
  6682. __proto__: null,
  6683. getCurrent: getCurrent
  6684. });
  6685. var ComposeSchema = [required$1('find')];
  6686. var Composing = create$5({
  6687. fields: ComposeSchema,
  6688. name: 'composing',
  6689. apis: ComposeApis
  6690. });
  6691. var factory$4 = function (detail) {
  6692. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6693. return {
  6694. uid: detail.uid,
  6695. dom: __assign({
  6696. tag: 'div',
  6697. attributes: __assign({ role: 'presentation' }, attributes)
  6698. }, domWithoutAttributes),
  6699. components: detail.components,
  6700. behaviours: get$6(detail.containerBehaviours),
  6701. events: detail.events,
  6702. domModification: detail.domModification,
  6703. eventOrder: detail.eventOrder
  6704. };
  6705. };
  6706. var Container = single({
  6707. name: 'Container',
  6708. factory: factory$4,
  6709. configFields: [
  6710. defaulted('components', []),
  6711. field$1('containerBehaviours', []),
  6712. defaulted('events', {}),
  6713. defaulted('domModification', {}),
  6714. defaulted('eventOrder', {})
  6715. ]
  6716. });
  6717. var factory$3 = function (detail) {
  6718. return {
  6719. uid: detail.uid,
  6720. dom: detail.dom,
  6721. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6722. Representing.config({
  6723. store: {
  6724. mode: 'memory',
  6725. initialValue: detail.getInitialValue()
  6726. }
  6727. }),
  6728. Composing.config({ find: Optional.some })
  6729. ]),
  6730. events: derive$3([runOnAttached(function (component, _simulatedEvent) {
  6731. Representing.setValue(component, detail.getInitialValue());
  6732. })])
  6733. };
  6734. };
  6735. var DataField = single({
  6736. name: 'DataField',
  6737. factory: factory$3,
  6738. configFields: [
  6739. required$1('uid'),
  6740. required$1('dom'),
  6741. required$1('getInitialValue'),
  6742. SketchBehaviours.field('dataBehaviours', [
  6743. Representing,
  6744. Composing
  6745. ])
  6746. ]
  6747. });
  6748. var get$2 = function (element) {
  6749. return element.dom.value;
  6750. };
  6751. var set$2 = function (element, value) {
  6752. if (value === undefined) {
  6753. throw new Error('Value.set was undefined');
  6754. }
  6755. element.dom.value = value;
  6756. };
  6757. var schema$8 = constant$1([
  6758. option('data'),
  6759. defaulted('inputAttributes', {}),
  6760. defaulted('inputStyles', {}),
  6761. defaulted('tag', 'input'),
  6762. defaulted('inputClasses', []),
  6763. onHandler('onSetValue'),
  6764. defaulted('styles', {}),
  6765. defaulted('eventOrder', {}),
  6766. field$1('inputBehaviours', [
  6767. Representing,
  6768. Focusing
  6769. ]),
  6770. defaulted('selectOnFocus', true)
  6771. ]);
  6772. var focusBehaviours = function (detail) {
  6773. return derive$2([Focusing.config({
  6774. onFocus: !detail.selectOnFocus ? noop : function (component) {
  6775. var input = component.element;
  6776. var value = get$2(input);
  6777. input.dom.setSelectionRange(0, value.length);
  6778. }
  6779. })]);
  6780. };
  6781. var behaviours = function (detail) {
  6782. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6783. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  6784. return { initialValue: data };
  6785. }).getOr({})), {
  6786. getValue: function (input) {
  6787. return get$2(input.element);
  6788. },
  6789. setValue: function (input, data) {
  6790. var current = get$2(input.element);
  6791. if (current !== data) {
  6792. set$2(input.element, data);
  6793. }
  6794. }
  6795. }),
  6796. onSetValue: detail.onSetValue
  6797. })]));
  6798. };
  6799. var dom = function (detail) {
  6800. return {
  6801. tag: detail.tag,
  6802. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6803. styles: detail.inputStyles,
  6804. classes: detail.inputClasses
  6805. };
  6806. };
  6807. var factory$2 = function (detail, _spec) {
  6808. return {
  6809. uid: detail.uid,
  6810. dom: dom(detail),
  6811. components: [],
  6812. behaviours: behaviours(detail),
  6813. eventOrder: detail.eventOrder
  6814. };
  6815. };
  6816. var Input = single({
  6817. name: 'Input',
  6818. configFields: schema$8(),
  6819. factory: factory$2
  6820. });
  6821. var exhibit$2 = function (base, tabConfig) {
  6822. return nu$3({
  6823. attributes: wrapAll([{
  6824. key: tabConfig.tabAttr,
  6825. value: 'true'
  6826. }])
  6827. });
  6828. };
  6829. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6830. __proto__: null,
  6831. exhibit: exhibit$2
  6832. });
  6833. var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  6834. var Tabstopping = create$5({
  6835. fields: TabstopSchema,
  6836. name: 'tabstopping',
  6837. active: ActiveTabstopping
  6838. });
  6839. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6840. var clearInputBehaviour = 'input-clearing';
  6841. var field = function (name, placeholder) {
  6842. var inputSpec = record(Input.sketch({
  6843. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6844. onSetValue: function (input, _data) {
  6845. emit(input, input$1());
  6846. },
  6847. inputBehaviours: derive$2([
  6848. Composing.config({ find: Optional.some }),
  6849. Tabstopping.config({}),
  6850. Keying.config({ mode: 'execution' })
  6851. ]),
  6852. selectOnFocus: false
  6853. }));
  6854. var buttonSpec = record(Button.sketch({
  6855. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6856. action: function (button) {
  6857. var input = inputSpec.get(button);
  6858. Representing.setValue(input, '');
  6859. }
  6860. }));
  6861. return {
  6862. name: name,
  6863. spec: Container.sketch({
  6864. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6865. components: [
  6866. inputSpec.asSpec(),
  6867. buttonSpec.asSpec()
  6868. ],
  6869. containerBehaviours: derive$2([
  6870. Toggling.config({ toggleClass: resolve('input-container-empty') }),
  6871. Composing.config({
  6872. find: function (comp) {
  6873. return Optional.some(inputSpec.get(comp));
  6874. }
  6875. }),
  6876. config(clearInputBehaviour, [run(input$1(), function (iContainer) {
  6877. var input = inputSpec.get(iContainer);
  6878. var val = Representing.getValue(input);
  6879. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6880. f(iContainer);
  6881. })])
  6882. ])
  6883. })
  6884. };
  6885. };
  6886. var hidden = function (name) {
  6887. return {
  6888. name: name,
  6889. spec: DataField.sketch({
  6890. dom: {
  6891. tag: 'span',
  6892. styles: { display: 'none' }
  6893. },
  6894. getInitialValue: function () {
  6895. return Optional.none();
  6896. }
  6897. })
  6898. };
  6899. };
  6900. var nativeDisabled = [
  6901. 'input',
  6902. 'button',
  6903. 'textarea',
  6904. 'select'
  6905. ];
  6906. var onLoad = function (component, disableConfig, disableState) {
  6907. var f = disableConfig.disabled() ? disable : enable;
  6908. f(component, disableConfig);
  6909. };
  6910. var hasNative = function (component, config) {
  6911. return config.useNative === true && contains$1(nativeDisabled, name$1(component.element));
  6912. };
  6913. var nativeIsDisabled = function (component) {
  6914. return has$1(component.element, 'disabled');
  6915. };
  6916. var nativeDisable = function (component) {
  6917. set$8(component.element, 'disabled', 'disabled');
  6918. };
  6919. var nativeEnable = function (component) {
  6920. remove$6(component.element, 'disabled');
  6921. };
  6922. var ariaIsDisabled = function (component) {
  6923. return get$b(component.element, 'aria-disabled') === 'true';
  6924. };
  6925. var ariaDisable = function (component) {
  6926. set$8(component.element, 'aria-disabled', 'true');
  6927. };
  6928. var ariaEnable = function (component) {
  6929. set$8(component.element, 'aria-disabled', 'false');
  6930. };
  6931. var disable = function (component, disableConfig, _disableState) {
  6932. disableConfig.disableClass.each(function (disableClass) {
  6933. add$1(component.element, disableClass);
  6934. });
  6935. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6936. f(component);
  6937. disableConfig.onDisabled(component);
  6938. };
  6939. var enable = function (component, disableConfig, _disableState) {
  6940. disableConfig.disableClass.each(function (disableClass) {
  6941. remove$3(component.element, disableClass);
  6942. });
  6943. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6944. f(component);
  6945. disableConfig.onEnabled(component);
  6946. };
  6947. var isDisabled = function (component, disableConfig) {
  6948. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6949. };
  6950. var set$1 = function (component, disableConfig, disableState, disabled) {
  6951. var f = disabled ? disable : enable;
  6952. f(component, disableConfig);
  6953. };
  6954. var DisableApis = /*#__PURE__*/Object.freeze({
  6955. __proto__: null,
  6956. enable: enable,
  6957. disable: disable,
  6958. isDisabled: isDisabled,
  6959. onLoad: onLoad,
  6960. set: set$1
  6961. });
  6962. var exhibit$1 = function (base, disableConfig) {
  6963. return nu$3({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6964. };
  6965. var events$3 = function (disableConfig, disableState) {
  6966. return derive$3([
  6967. abort(execute$5(), function (component, _simulatedEvent) {
  6968. return isDisabled(component, disableConfig);
  6969. }),
  6970. loadEvent(disableConfig, disableState, onLoad)
  6971. ]);
  6972. };
  6973. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6974. __proto__: null,
  6975. exhibit: exhibit$1,
  6976. events: events$3
  6977. });
  6978. var DisableSchema = [
  6979. defaultedFunction('disabled', never),
  6980. defaulted('useNative', true),
  6981. option('disableClass'),
  6982. onHandler('onDisabled'),
  6983. onHandler('onEnabled')
  6984. ];
  6985. var Disabling = create$5({
  6986. fields: DisableSchema,
  6987. name: 'disabling',
  6988. active: ActiveDisable,
  6989. apis: DisableApis
  6990. });
  6991. var owner$1 = 'form';
  6992. var schema$7 = [field$1('formBehaviours', [Representing])];
  6993. var getPartName = function (name) {
  6994. return '<alloy.field.' + name + '>';
  6995. };
  6996. var sketch$4 = function (fSpec) {
  6997. var parts = function () {
  6998. var record = [];
  6999. var field = function (name, config) {
  7000. record.push(name);
  7001. return generateOne(owner$1, getPartName(name), config);
  7002. };
  7003. return {
  7004. field: field,
  7005. record: constant$1(record)
  7006. };
  7007. }();
  7008. var spec = fSpec(parts);
  7009. var partNames = parts.record();
  7010. var fieldParts = map$2(partNames, function (n) {
  7011. return required({
  7012. name: n,
  7013. pname: getPartName(n)
  7014. });
  7015. });
  7016. return composite$1(owner$1, schema$7, fieldParts, make$4, spec);
  7017. };
  7018. var toResult = function (o, e) {
  7019. return o.fold(function () {
  7020. return Result.error(e);
  7021. }, Result.value);
  7022. };
  7023. var make$4 = function (detail, components) {
  7024. return {
  7025. uid: detail.uid,
  7026. dom: detail.dom,
  7027. components: components,
  7028. behaviours: augment(detail.formBehaviours, [Representing.config({
  7029. store: {
  7030. mode: 'manual',
  7031. getValue: function (form) {
  7032. var resPs = getAllParts(form, detail);
  7033. return map$1(resPs, function (resPThunk, pName) {
  7034. return resPThunk().bind(function (v) {
  7035. var opt = Composing.getCurrent(v);
  7036. return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  7037. }).map(Representing.getValue);
  7038. });
  7039. },
  7040. setValue: function (form, values) {
  7041. each(values, function (newValue, key) {
  7042. getPart(form, detail, key).each(function (wrapper) {
  7043. Composing.getCurrent(wrapper).each(function (field) {
  7044. Representing.setValue(field, newValue);
  7045. });
  7046. });
  7047. });
  7048. }
  7049. }
  7050. })]),
  7051. apis: {
  7052. getField: function (form, key) {
  7053. return getPart(form, detail, key).bind(Composing.getCurrent);
  7054. }
  7055. }
  7056. };
  7057. };
  7058. var Form = {
  7059. getField: makeApi(function (apis, component, key) {
  7060. return apis.getField(component, key);
  7061. }),
  7062. sketch: sketch$4
  7063. };
  7064. var SWIPING_LEFT = 1;
  7065. var SWIPING_RIGHT = -1;
  7066. var SWIPING_NONE = 0;
  7067. var init$3 = function (xValue) {
  7068. return {
  7069. xValue: xValue,
  7070. points: []
  7071. };
  7072. };
  7073. var move = function (model, xValue) {
  7074. if (xValue === model.xValue) {
  7075. return model;
  7076. }
  7077. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7078. var newPoint = {
  7079. direction: currentDirection,
  7080. xValue: xValue
  7081. };
  7082. var priorPoints = function () {
  7083. if (model.points.length === 0) {
  7084. return [];
  7085. } else {
  7086. var prev = model.points[model.points.length - 1];
  7087. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7088. }
  7089. }();
  7090. return {
  7091. xValue: xValue,
  7092. points: priorPoints.concat([newPoint])
  7093. };
  7094. };
  7095. var complete = function (model) {
  7096. if (model.points.length === 0) {
  7097. return SWIPING_NONE;
  7098. } else {
  7099. var firstDirection = model.points[0].direction;
  7100. var lastDirection = model.points[model.points.length - 1].direction;
  7101. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7102. }
  7103. };
  7104. var sketch$3 = function (rawSpec) {
  7105. var navigateEvent = 'navigateEvent';
  7106. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7107. var formAdhocEvents = 'form-events';
  7108. var schema = objOf([
  7109. required$1('fields'),
  7110. defaulted('maxFieldIndex', rawSpec.fields.length - 1),
  7111. required$1('onExecute'),
  7112. required$1('getInitialValue'),
  7113. customField('state', function () {
  7114. return {
  7115. dialogSwipeState: value(),
  7116. currentScreen: Cell(0)
  7117. };
  7118. })
  7119. ]);
  7120. var spec$1 = asRawOrDie$1('SerialisedDialog', schema, rawSpec);
  7121. var navigationButton = function (direction, directionName, enabled) {
  7122. return Button.sketch({
  7123. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7124. action: function (button) {
  7125. emitWith(button, navigateEvent, { direction: direction });
  7126. },
  7127. buttonBehaviours: derive$2([Disabling.config({
  7128. disableClass: resolve('toolbar-navigation-disabled'),
  7129. disabled: function () {
  7130. return !enabled;
  7131. }
  7132. })])
  7133. });
  7134. };
  7135. var reposition = function (dialog, message) {
  7136. descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7137. set$5(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  7138. });
  7139. };
  7140. var navigate = function (dialog, direction) {
  7141. var screens = descendants(dialog.element, '.' + resolve('serialised-dialog-screen'));
  7142. descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7143. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  7144. getRaw(parent, 'left').each(function (left) {
  7145. var currentLeft = parseInt(left, 10);
  7146. var w = get$5(screens[0]);
  7147. set$5(parent, 'left', currentLeft - direction * w + 'px');
  7148. });
  7149. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  7150. }
  7151. });
  7152. };
  7153. var focusInput = function (dialog) {
  7154. var inputs = descendants(dialog.element, 'input');
  7155. var optInput = Optional.from(inputs[spec$1.state.currentScreen.get()]);
  7156. optInput.each(function (input) {
  7157. dialog.getSystem().getByDom(input).each(function (inputComp) {
  7158. dispatchFocus(dialog, inputComp.element);
  7159. });
  7160. });
  7161. var dotitems = memDots.get(dialog);
  7162. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  7163. };
  7164. var resetState = function () {
  7165. spec$1.state.currentScreen.set(0);
  7166. spec$1.state.dialogSwipeState.clear();
  7167. };
  7168. var memForm = record(Form.sketch(function (parts) {
  7169. return {
  7170. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  7171. components: [Container.sketch({
  7172. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  7173. components: map$2(spec$1.fields, function (field, i) {
  7174. return i <= spec$1.maxFieldIndex ? Container.sketch({
  7175. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  7176. components: [
  7177. navigationButton(-1, 'previous', i > 0),
  7178. parts.field(field.name, field.spec),
  7179. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  7180. ]
  7181. }) : parts.field(field.name, field.spec);
  7182. })
  7183. })],
  7184. formBehaviours: derive$2([
  7185. orientation(function (dialog, message) {
  7186. reposition(dialog, message);
  7187. }),
  7188. Keying.config({
  7189. mode: 'special',
  7190. focusIn: function (dialog, _specialInfo) {
  7191. focusInput(dialog);
  7192. },
  7193. onTab: function (dialog, _specialInfo) {
  7194. navigate(dialog, +1);
  7195. return Optional.some(true);
  7196. },
  7197. onShiftTab: function (dialog, _specialInfo) {
  7198. navigate(dialog, -1);
  7199. return Optional.some(true);
  7200. }
  7201. }),
  7202. config(formAdhocEvents, [
  7203. runOnAttached(function (dialog, _simulatedEvent) {
  7204. resetState();
  7205. var dotitems = memDots.get(dialog);
  7206. Highlighting.highlightFirst(dotitems);
  7207. spec$1.getInitialValue(dialog).each(function (v) {
  7208. Representing.setValue(dialog, v);
  7209. });
  7210. }),
  7211. runOnExecute(spec$1.onExecute),
  7212. run(transitionend(), function (dialog, simulatedEvent) {
  7213. var event = simulatedEvent.event;
  7214. if (event.raw.propertyName === 'left') {
  7215. focusInput(dialog);
  7216. }
  7217. }),
  7218. run(navigateEvent, function (dialog, simulatedEvent) {
  7219. var event = simulatedEvent.event;
  7220. var direction = event.direction;
  7221. navigate(dialog, direction);
  7222. })
  7223. ])
  7224. ])
  7225. };
  7226. }));
  7227. var memDots = record({
  7228. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7229. behaviours: derive$2([Highlighting.config({
  7230. highlightClass: resolve('dot-active'),
  7231. itemClass: resolve('dot-item')
  7232. })]),
  7233. components: bind$3(spec$1.fields, function (_f, i) {
  7234. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7235. })
  7236. });
  7237. return {
  7238. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7239. components: [
  7240. memForm.asSpec(),
  7241. memDots.asSpec()
  7242. ],
  7243. behaviours: derive$2([
  7244. Keying.config({
  7245. mode: 'special',
  7246. focusIn: function (wrapper) {
  7247. var form = memForm.get(wrapper);
  7248. Keying.focusIn(form);
  7249. }
  7250. }),
  7251. config(wrapperAdhocEvents, [
  7252. run(touchstart(), function (_wrapper, simulatedEvent) {
  7253. var event = simulatedEvent.event;
  7254. spec$1.state.dialogSwipeState.set(init$3(event.raw.touches[0].clientX));
  7255. }),
  7256. run(touchmove(), function (_wrapper, simulatedEvent) {
  7257. var event = simulatedEvent.event;
  7258. spec$1.state.dialogSwipeState.on(function (state) {
  7259. simulatedEvent.event.prevent();
  7260. spec$1.state.dialogSwipeState.set(move(state, event.raw.touches[0].clientX));
  7261. });
  7262. }),
  7263. run(touchend(), function (wrapper, _simulatedEvent) {
  7264. spec$1.state.dialogSwipeState.on(function (state) {
  7265. var dialog = memForm.get(wrapper);
  7266. var direction = -1 * complete(state);
  7267. navigate(dialog, direction);
  7268. });
  7269. })
  7270. ])
  7271. ])
  7272. };
  7273. };
  7274. var getGroups = cached(function (realm, editor) {
  7275. return [{
  7276. label: 'the link group',
  7277. items: [sketch$3({
  7278. fields: [
  7279. field('url', 'Type or paste URL'),
  7280. field('text', 'Link text'),
  7281. field('title', 'Link title'),
  7282. field('target', 'Link target'),
  7283. hidden('link')
  7284. ],
  7285. maxFieldIndex: [
  7286. 'url',
  7287. 'text',
  7288. 'title',
  7289. 'target'
  7290. ].length - 1,
  7291. getInitialValue: function () {
  7292. return Optional.some(getInfo(editor));
  7293. },
  7294. onExecute: function (dialog, _simulatedEvent) {
  7295. var info = Representing.getValue(dialog);
  7296. applyInfo(editor, info);
  7297. realm.restoreToolbar();
  7298. editor.focus();
  7299. }
  7300. })]
  7301. }];
  7302. });
  7303. var sketch$2 = function (realm, editor) {
  7304. return forToolbarStateAction(editor, 'link', 'link', function () {
  7305. var groups = getGroups(realm, editor);
  7306. realm.setContextToolbar(groups);
  7307. forAndroid(editor, function () {
  7308. realm.focusToolbar();
  7309. });
  7310. query(editor).each(function (link) {
  7311. editor.selection.select(link.dom);
  7312. });
  7313. });
  7314. };
  7315. var isRecursive = function (component, originator, target) {
  7316. return eq(originator, component.element) && !eq(originator, target);
  7317. };
  7318. var events$2 = derive$3([can(focus$4(), function (component, simulatedEvent) {
  7319. var event = simulatedEvent.event;
  7320. var originator = event.originator;
  7321. var target = event.target;
  7322. if (isRecursive(component, originator, target)) {
  7323. console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  7324. return false;
  7325. } else {
  7326. return true;
  7327. }
  7328. })]);
  7329. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7330. __proto__: null,
  7331. events: events$2
  7332. });
  7333. var make$3 = identity;
  7334. var NoContextApi = function (getComp) {
  7335. var getMessage = function (event) {
  7336. return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  7337. };
  7338. var fail = function (event) {
  7339. return function () {
  7340. throw new Error(getMessage(event));
  7341. };
  7342. };
  7343. var warn = function (event) {
  7344. return function () {
  7345. console.warn(getMessage(event));
  7346. };
  7347. };
  7348. return {
  7349. debugInfo: constant$1('fake'),
  7350. triggerEvent: warn('triggerEvent'),
  7351. triggerFocus: warn('triggerFocus'),
  7352. triggerEscape: warn('triggerEscape'),
  7353. broadcast: warn('broadcast'),
  7354. broadcastOn: warn('broadcastOn'),
  7355. broadcastEvent: warn('broadcastEvent'),
  7356. build: fail('build'),
  7357. addToWorld: fail('addToWorld'),
  7358. removeFromWorld: fail('removeFromWorld'),
  7359. addToGui: fail('addToGui'),
  7360. removeFromGui: fail('removeFromGui'),
  7361. getByUid: fail('getByUid'),
  7362. getByDom: fail('getByDom'),
  7363. isConnected: never
  7364. };
  7365. };
  7366. var singleton = NoContextApi();
  7367. var generateFrom$1 = function (spec, all) {
  7368. var schema = map$2(all, function (a) {
  7369. return optionObjOf(a.name(), [
  7370. required$1('config'),
  7371. defaulted('state', NoState)
  7372. ]);
  7373. });
  7374. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7375. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7376. }, identity);
  7377. return {
  7378. list: all,
  7379. data: map$1(validated, function (optBlobThunk) {
  7380. var output = optBlobThunk.map(function (blob) {
  7381. return {
  7382. config: blob.config,
  7383. state: blob.state.init(blob.config)
  7384. };
  7385. });
  7386. return constant$1(output);
  7387. })
  7388. };
  7389. };
  7390. var getBehaviours$1 = function (bData) {
  7391. return bData.list;
  7392. };
  7393. var getData = function (bData) {
  7394. return bData.data;
  7395. };
  7396. var byInnerKey = function (data, tuple) {
  7397. var r = {};
  7398. each(data, function (detail, key) {
  7399. each(detail, function (value, indexKey) {
  7400. var chain = get$c(r, indexKey).getOr([]);
  7401. r[indexKey] = chain.concat([tuple(key, value)]);
  7402. });
  7403. });
  7404. return r;
  7405. };
  7406. var combine$1 = function (info, baseMod, behaviours, base) {
  7407. var modsByBehaviour = __assign({}, baseMod);
  7408. each$1(behaviours, function (behaviour) {
  7409. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7410. });
  7411. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  7412. return {
  7413. name: name,
  7414. modification: modification
  7415. };
  7416. });
  7417. var combineObjects = function (objects) {
  7418. return foldr(objects, function (b, a) {
  7419. return __assign(__assign({}, a.modification), b);
  7420. }, {});
  7421. };
  7422. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7423. return a.modification.concat(b);
  7424. }, []);
  7425. var combinedAttributes = combineObjects(byAspect.attributes);
  7426. var combinedStyles = combineObjects(byAspect.styles);
  7427. return nu$3({
  7428. classes: combinedClasses,
  7429. attributes: combinedAttributes,
  7430. styles: combinedStyles
  7431. });
  7432. };
  7433. var sortKeys = function (label, keyName, array, order) {
  7434. try {
  7435. var sorted = sort(array, function (a, b) {
  7436. var aKey = a[keyName];
  7437. var bKey = b[keyName];
  7438. var aIndex = order.indexOf(aKey);
  7439. var bIndex = order.indexOf(bKey);
  7440. if (aIndex === -1) {
  7441. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7442. }
  7443. if (bIndex === -1) {
  7444. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7445. }
  7446. if (aIndex < bIndex) {
  7447. return -1;
  7448. } else if (bIndex < aIndex) {
  7449. return 1;
  7450. } else {
  7451. return 0;
  7452. }
  7453. });
  7454. return Result.value(sorted);
  7455. } catch (err) {
  7456. return Result.error([err]);
  7457. }
  7458. };
  7459. var uncurried = function (handler, purpose) {
  7460. return {
  7461. handler: handler,
  7462. purpose: purpose
  7463. };
  7464. };
  7465. var curried = function (handler, purpose) {
  7466. return {
  7467. cHandler: handler,
  7468. purpose: purpose
  7469. };
  7470. };
  7471. var curryArgs = function (descHandler, extraArgs) {
  7472. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  7473. };
  7474. var getCurried = function (descHandler) {
  7475. return descHandler.cHandler;
  7476. };
  7477. var behaviourTuple = function (name, handler) {
  7478. return {
  7479. name: name,
  7480. handler: handler
  7481. };
  7482. };
  7483. var nameToHandlers = function (behaviours, info) {
  7484. var r = {};
  7485. each$1(behaviours, function (behaviour) {
  7486. r[behaviour.name()] = behaviour.handlers(info);
  7487. });
  7488. return r;
  7489. };
  7490. var groupByEvents = function (info, behaviours, base) {
  7491. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7492. return byInnerKey(behaviourEvents, behaviourTuple);
  7493. };
  7494. var combine = function (info, eventOrder, behaviours, base) {
  7495. var byEventName = groupByEvents(info, behaviours, base);
  7496. return combineGroups(byEventName, eventOrder);
  7497. };
  7498. var assemble = function (rawHandler) {
  7499. var handler = read$1(rawHandler);
  7500. return function (component, simulatedEvent) {
  7501. var rest = [];
  7502. for (var _i = 2; _i < arguments.length; _i++) {
  7503. rest[_i - 2] = arguments[_i];
  7504. }
  7505. var args = [
  7506. component,
  7507. simulatedEvent
  7508. ].concat(rest);
  7509. if (handler.abort.apply(undefined, args)) {
  7510. simulatedEvent.stop();
  7511. } else if (handler.can.apply(undefined, args)) {
  7512. handler.run.apply(undefined, args);
  7513. }
  7514. };
  7515. };
  7516. var missingOrderError = function (eventName, tuples) {
  7517. return Result.error(['The event (' + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must ' + 'specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that ' + 'can trigger it are: ' + JSON.stringify(map$2(tuples, function (c) {
  7518. return c.name;
  7519. }), null, 2)]);
  7520. };
  7521. var fuse = function (tuples, eventOrder, eventName) {
  7522. var order = eventOrder[eventName];
  7523. if (!order) {
  7524. return missingOrderError(eventName, tuples);
  7525. } else {
  7526. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7527. var handlers = map$2(sortedTuples, function (tuple) {
  7528. return tuple.handler;
  7529. });
  7530. return fuse$1(handlers);
  7531. });
  7532. }
  7533. };
  7534. var combineGroups = function (byEventName, eventOrder) {
  7535. var r = mapToArray(byEventName, function (tuples, eventName) {
  7536. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  7537. return combined.map(function (handler) {
  7538. var assembled = assemble(handler);
  7539. var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) {
  7540. return exists(tuples, function (t) {
  7541. return t.name === o;
  7542. });
  7543. }).join(' > ') : tuples[0].name;
  7544. return wrap(eventName, uncurried(assembled, purpose));
  7545. });
  7546. });
  7547. return consolidate(r, {});
  7548. };
  7549. var _a;
  7550. var baseBehaviour = 'alloy.base.behaviour';
  7551. var schema$6 = objOf([
  7552. field$2('dom', 'dom', required$2(), objOf([
  7553. required$1('tag'),
  7554. defaulted('styles', {}),
  7555. defaulted('classes', []),
  7556. defaulted('attributes', {}),
  7557. option('value'),
  7558. option('innerHtml')
  7559. ])),
  7560. required$1('components'),
  7561. required$1('uid'),
  7562. defaulted('events', {}),
  7563. defaulted('apis', {}),
  7564. field$2('eventOrder', 'eventOrder', mergeWith((_a = {}, _a[execute$5()] = [
  7565. 'disabling',
  7566. baseBehaviour,
  7567. 'toggling',
  7568. 'typeaheadevents'
  7569. ], _a[focus$4()] = [
  7570. baseBehaviour,
  7571. 'focusing',
  7572. 'keying'
  7573. ], _a[systemInit()] = [
  7574. baseBehaviour,
  7575. 'disabling',
  7576. 'toggling',
  7577. 'representing'
  7578. ], _a[input$1()] = [
  7579. baseBehaviour,
  7580. 'representing',
  7581. 'streaming',
  7582. 'invalidating'
  7583. ], _a[detachedFromDom()] = [
  7584. baseBehaviour,
  7585. 'representing',
  7586. 'item-events',
  7587. 'tooltipping'
  7588. ], _a[mousedown()] = [
  7589. 'focusing',
  7590. baseBehaviour,
  7591. 'item-type-events'
  7592. ], _a[touchstart()] = [
  7593. 'focusing',
  7594. baseBehaviour,
  7595. 'item-type-events'
  7596. ], _a[mouseover()] = [
  7597. 'item-type-events',
  7598. 'tooltipping'
  7599. ], _a[receive$1()] = [
  7600. 'receiving',
  7601. 'reflecting',
  7602. 'tooltipping'
  7603. ], _a)), anyValue()),
  7604. option('domModification')
  7605. ]);
  7606. var toInfo = function (spec) {
  7607. return asRaw('custom.definition', schema$6, spec);
  7608. };
  7609. var toDefinition = function (detail) {
  7610. return __assign(__assign({}, detail.dom), {
  7611. uid: detail.uid,
  7612. domChildren: map$2(detail.components, function (comp) {
  7613. return comp.element;
  7614. })
  7615. });
  7616. };
  7617. var toModification = function (detail) {
  7618. return detail.domModification.fold(function () {
  7619. return nu$3({});
  7620. }, nu$3);
  7621. };
  7622. var toEvents = function (info) {
  7623. return info.events;
  7624. };
  7625. var add = function (element, classes) {
  7626. each$1(classes, function (x) {
  7627. add$1(element, x);
  7628. });
  7629. };
  7630. var remove$1 = function (element, classes) {
  7631. each$1(classes, function (x) {
  7632. remove$3(element, x);
  7633. });
  7634. };
  7635. var renderToDom = function (definition) {
  7636. var subject = SugarElement.fromTag(definition.tag);
  7637. setAll$1(subject, definition.attributes);
  7638. add(subject, definition.classes);
  7639. setAll(subject, definition.styles);
  7640. definition.innerHtml.each(function (html) {
  7641. return set$7(subject, html);
  7642. });
  7643. var children = definition.domChildren;
  7644. append$1(subject, children);
  7645. definition.value.each(function (value) {
  7646. set$2(subject, value);
  7647. });
  7648. if (!definition.uid) {
  7649. debugger;
  7650. }
  7651. writeOnly(subject, definition.uid);
  7652. return subject;
  7653. };
  7654. var getBehaviours = function (spec) {
  7655. var behaviours = get$c(spec, 'behaviours').getOr({});
  7656. var keys$1 = filter$2(keys(behaviours), function (k) {
  7657. return behaviours[k] !== undefined;
  7658. });
  7659. return map$2(keys$1, function (k) {
  7660. return behaviours[k].me;
  7661. });
  7662. };
  7663. var generateFrom = function (spec, all) {
  7664. return generateFrom$1(spec, all);
  7665. };
  7666. var generate$1 = function (spec) {
  7667. var all = getBehaviours(spec);
  7668. return generateFrom(spec, all);
  7669. };
  7670. var getDomDefinition = function (info, bList, bData) {
  7671. var definition = toDefinition(info);
  7672. var infoModification = toModification(info);
  7673. var baseModification = { 'alloy.base.modification': infoModification };
  7674. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7675. return merge(definition, modification);
  7676. };
  7677. var getEvents = function (info, bList, bData) {
  7678. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7679. return combine(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7680. };
  7681. var build$2 = function (spec) {
  7682. var getMe = function () {
  7683. return me;
  7684. };
  7685. var systemApi = Cell(singleton);
  7686. var info = getOrDie(toInfo(spec));
  7687. var bBlob = generate$1(spec);
  7688. var bList = getBehaviours$1(bBlob);
  7689. var bData = getData(bBlob);
  7690. var modDefinition = getDomDefinition(info, bList, bData);
  7691. var item = renderToDom(modDefinition);
  7692. var events = getEvents(info, bList, bData);
  7693. var subcomponents = Cell(info.components);
  7694. var connect = function (newApi) {
  7695. systemApi.set(newApi);
  7696. };
  7697. var disconnect = function () {
  7698. systemApi.set(NoContextApi(getMe));
  7699. };
  7700. var syncComponents = function () {
  7701. var children$1 = children(item);
  7702. var subs = bind$3(children$1, function (child) {
  7703. return systemApi.get().getByDom(child).fold(function () {
  7704. return [];
  7705. }, pure$2);
  7706. });
  7707. subcomponents.set(subs);
  7708. };
  7709. var config = function (behaviour) {
  7710. var b = bData;
  7711. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7712. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7713. };
  7714. return f();
  7715. };
  7716. var hasConfigured = function (behaviour) {
  7717. return isFunction(bData[behaviour.name()]);
  7718. };
  7719. var getApis = function () {
  7720. return info.apis;
  7721. };
  7722. var readState = function (behaviourName) {
  7723. return bData[behaviourName]().map(function (b) {
  7724. return b.state.readState();
  7725. }).getOr('not enabled');
  7726. };
  7727. var me = {
  7728. uid: spec.uid,
  7729. getSystem: systemApi.get,
  7730. config: config,
  7731. hasConfigured: hasConfigured,
  7732. spec: spec,
  7733. readState: readState,
  7734. getApis: getApis,
  7735. connect: connect,
  7736. disconnect: disconnect,
  7737. element: item,
  7738. syncComponents: syncComponents,
  7739. components: subcomponents.get,
  7740. events: events
  7741. };
  7742. return me;
  7743. };
  7744. var buildSubcomponents = function (spec) {
  7745. var components = get$c(spec, 'components').getOr([]);
  7746. return map$2(components, build$1);
  7747. };
  7748. var buildFromSpec = function (userSpec) {
  7749. var _a = make$3(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7750. var components = buildSubcomponents(spec);
  7751. var completeSpec = __assign(__assign({}, spec), {
  7752. events: __assign(__assign({}, DefaultEvents), specEvents),
  7753. components: components
  7754. });
  7755. return Result.value(build$2(completeSpec));
  7756. };
  7757. var text = function (textContent) {
  7758. var element = SugarElement.fromText(textContent);
  7759. return external({ element: element });
  7760. };
  7761. var external = function (spec) {
  7762. var extSpec = asRawOrDie$1('external.component', objOfOnly([
  7763. required$1('element'),
  7764. option('uid')
  7765. ]), spec);
  7766. var systemApi = Cell(NoContextApi());
  7767. var connect = function (newApi) {
  7768. systemApi.set(newApi);
  7769. };
  7770. var disconnect = function () {
  7771. systemApi.set(NoContextApi(function () {
  7772. return me;
  7773. }));
  7774. };
  7775. var uid = extSpec.uid.getOrThunk(function () {
  7776. return generate$2('external');
  7777. });
  7778. writeOnly(extSpec.element, uid);
  7779. var me = {
  7780. uid: uid,
  7781. getSystem: systemApi.get,
  7782. config: Optional.none,
  7783. hasConfigured: never,
  7784. connect: connect,
  7785. disconnect: disconnect,
  7786. getApis: function () {
  7787. return {};
  7788. },
  7789. element: extSpec.element,
  7790. spec: spec,
  7791. readState: constant$1('No state'),
  7792. syncComponents: noop,
  7793. components: constant$1([]),
  7794. events: {}
  7795. };
  7796. return premade$1(me);
  7797. };
  7798. var uids = generate$2;
  7799. var isSketchSpec = function (spec) {
  7800. return has$2(spec, 'uid');
  7801. };
  7802. var build$1 = function (spec) {
  7803. return getPremade(spec).getOrThunk(function () {
  7804. var userSpecWithUid = isSketchSpec(spec) ? spec : __assign({ uid: uids('') }, spec);
  7805. return buildFromSpec(userSpecWithUid).getOrDie();
  7806. });
  7807. };
  7808. var premade = premade$1;
  7809. var hoverEvent = 'alloy.item-hover';
  7810. var focusEvent = 'alloy.item-focus';
  7811. var onHover = function (item) {
  7812. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7813. if (!Focusing.isFocused(item)) {
  7814. Focusing.focus(item);
  7815. }
  7816. emitWith(item, hoverEvent, { item: item });
  7817. }
  7818. };
  7819. var onFocus = function (item) {
  7820. emitWith(item, focusEvent, { item: item });
  7821. };
  7822. var hover = constant$1(hoverEvent);
  7823. var focus$1 = constant$1(focusEvent);
  7824. var builder$2 = function (detail) {
  7825. return {
  7826. dom: detail.dom,
  7827. domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem' }, detail.domModification.attributes), { 'aria-haspopup': detail.hasSubmenu }), detail.hasSubmenu ? { 'aria-expanded': false } : {}) }),
  7828. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7829. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7830. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7831. }),
  7832. Focusing.config({
  7833. ignore: detail.ignoreFocus,
  7834. stopMousedown: detail.ignoreFocus,
  7835. onFocus: function (component) {
  7836. onFocus(component);
  7837. }
  7838. }),
  7839. Keying.config({ mode: 'execution' }),
  7840. Representing.config({
  7841. store: {
  7842. mode: 'memory',
  7843. initialValue: detail.data
  7844. }
  7845. }),
  7846. config('item-type-events', __spreadArray(__spreadArray([], pointerEvents()), [
  7847. run(mouseover(), onHover),
  7848. run(focusItem(), Focusing.focus)
  7849. ]))
  7850. ]),
  7851. components: detail.components,
  7852. eventOrder: detail.eventOrder
  7853. };
  7854. };
  7855. var schema$5 = [
  7856. required$1('data'),
  7857. required$1('components'),
  7858. required$1('dom'),
  7859. defaulted('hasSubmenu', false),
  7860. option('toggling'),
  7861. SketchBehaviours.field('itemBehaviours', [
  7862. Toggling,
  7863. Focusing,
  7864. Keying,
  7865. Representing
  7866. ]),
  7867. defaulted('ignoreFocus', false),
  7868. defaulted('domModification', {}),
  7869. output('builder', builder$2),
  7870. defaulted('eventOrder', {})
  7871. ];
  7872. var builder$1 = function (detail) {
  7873. return {
  7874. dom: detail.dom,
  7875. components: detail.components,
  7876. events: derive$3([stopper(focusItem())])
  7877. };
  7878. };
  7879. var schema$4 = [
  7880. required$1('dom'),
  7881. required$1('components'),
  7882. output('builder', builder$1)
  7883. ];
  7884. var owner = constant$1('item-widget');
  7885. var parts$3 = constant$1([required({
  7886. name: 'widget',
  7887. overrides: function (detail) {
  7888. return {
  7889. behaviours: derive$2([Representing.config({
  7890. store: {
  7891. mode: 'manual',
  7892. getValue: function (_component) {
  7893. return detail.data;
  7894. },
  7895. setValue: noop
  7896. }
  7897. })])
  7898. };
  7899. }
  7900. })]);
  7901. var builder = function (detail) {
  7902. var subs = substitutes(owner(), detail, parts$3());
  7903. var components$1 = components(owner(), detail, subs.internals());
  7904. var focusWidget = function (component) {
  7905. return getPart(component, detail, 'widget').map(function (widget) {
  7906. Keying.focusIn(widget);
  7907. return widget;
  7908. });
  7909. };
  7910. var onHorizontalArrow = function (component, simulatedEvent) {
  7911. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  7912. if (detail.autofocus) {
  7913. simulatedEvent.setSource(component.element);
  7914. return Optional.none();
  7915. } else {
  7916. return Optional.none();
  7917. }
  7918. }();
  7919. };
  7920. return {
  7921. dom: detail.dom,
  7922. components: components$1,
  7923. domModification: detail.domModification,
  7924. events: derive$3([
  7925. runOnExecute(function (component, simulatedEvent) {
  7926. focusWidget(component).each(function (_widget) {
  7927. simulatedEvent.stop();
  7928. });
  7929. }),
  7930. run(mouseover(), onHover),
  7931. run(focusItem(), function (component, _simulatedEvent) {
  7932. if (detail.autofocus) {
  7933. focusWidget(component);
  7934. } else {
  7935. Focusing.focus(component);
  7936. }
  7937. })
  7938. ]),
  7939. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7940. Representing.config({
  7941. store: {
  7942. mode: 'memory',
  7943. initialValue: detail.data
  7944. }
  7945. }),
  7946. Focusing.config({
  7947. ignore: detail.ignoreFocus,
  7948. onFocus: function (component) {
  7949. onFocus(component);
  7950. }
  7951. }),
  7952. Keying.config({
  7953. mode: 'special',
  7954. focusIn: detail.autofocus ? function (component) {
  7955. focusWidget(component);
  7956. } : revoke(),
  7957. onLeft: onHorizontalArrow,
  7958. onRight: onHorizontalArrow,
  7959. onEscape: function (component, simulatedEvent) {
  7960. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7961. Focusing.focus(component);
  7962. return Optional.some(true);
  7963. } else if (detail.autofocus) {
  7964. simulatedEvent.setSource(component.element);
  7965. return Optional.none();
  7966. } else {
  7967. return Optional.none();
  7968. }
  7969. }
  7970. })
  7971. ])
  7972. };
  7973. };
  7974. var schema$3 = [
  7975. required$1('uid'),
  7976. required$1('data'),
  7977. required$1('components'),
  7978. required$1('dom'),
  7979. defaulted('autofocus', false),
  7980. defaulted('ignoreFocus', false),
  7981. SketchBehaviours.field('widgetBehaviours', [
  7982. Representing,
  7983. Focusing,
  7984. Keying
  7985. ]),
  7986. defaulted('domModification', {}),
  7987. defaultUidsSchema(parts$3()),
  7988. output('builder', builder)
  7989. ];
  7990. var itemSchema = choose$1('type', {
  7991. widget: schema$3,
  7992. item: schema$5,
  7993. separator: schema$4
  7994. });
  7995. var configureGrid = function (detail, movementInfo) {
  7996. return {
  7997. mode: 'flatgrid',
  7998. selector: '.' + detail.markers.item,
  7999. initSize: {
  8000. numColumns: movementInfo.initSize.numColumns,
  8001. numRows: movementInfo.initSize.numRows
  8002. },
  8003. focusManager: detail.focusManager
  8004. };
  8005. };
  8006. var configureMatrix = function (detail, movementInfo) {
  8007. return {
  8008. mode: 'matrix',
  8009. selectors: {
  8010. row: movementInfo.rowSelector,
  8011. cell: '.' + detail.markers.item
  8012. },
  8013. focusManager: detail.focusManager
  8014. };
  8015. };
  8016. var configureMenu = function (detail, movementInfo) {
  8017. return {
  8018. mode: 'menu',
  8019. selector: '.' + detail.markers.item,
  8020. moveOnTab: movementInfo.moveOnTab,
  8021. focusManager: detail.focusManager
  8022. };
  8023. };
  8024. var parts$2 = constant$1([group({
  8025. factory: {
  8026. sketch: function (spec) {
  8027. var itemInfo = asRawOrDie$1('menu.spec item', itemSchema, spec);
  8028. return itemInfo.builder(itemInfo);
  8029. }
  8030. },
  8031. name: 'items',
  8032. unit: 'item',
  8033. defaults: function (detail, u) {
  8034. return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  8035. },
  8036. overrides: function (detail, u) {
  8037. return {
  8038. type: u.type,
  8039. ignoreFocus: detail.fakeFocus,
  8040. domModification: { classes: [detail.markers.item] }
  8041. };
  8042. }
  8043. })]);
  8044. var schema$2 = constant$1([
  8045. required$1('value'),
  8046. required$1('items'),
  8047. required$1('dom'),
  8048. required$1('components'),
  8049. defaulted('eventOrder', {}),
  8050. field$1('menuBehaviours', [
  8051. Highlighting,
  8052. Representing,
  8053. Composing,
  8054. Keying
  8055. ]),
  8056. defaultedOf('movement', {
  8057. mode: 'menu',
  8058. moveOnTab: true
  8059. }, choose$1('mode', {
  8060. grid: [
  8061. initSize(),
  8062. output('config', configureGrid)
  8063. ],
  8064. matrix: [
  8065. output('config', configureMatrix),
  8066. required$1('rowSelector')
  8067. ],
  8068. menu: [
  8069. defaulted('moveOnTab', true),
  8070. output('config', configureMenu)
  8071. ]
  8072. })),
  8073. itemMarkers(),
  8074. defaulted('fakeFocus', false),
  8075. defaulted('focusManager', dom$2()),
  8076. onHandler('onHighlight')
  8077. ]);
  8078. var focus = constant$1('alloy.menu-focus');
  8079. var make$2 = function (detail, components, _spec, _externals) {
  8080. return {
  8081. uid: detail.uid,
  8082. dom: detail.dom,
  8083. markers: detail.markers,
  8084. behaviours: augment(detail.menuBehaviours, [
  8085. Highlighting.config({
  8086. highlightClass: detail.markers.selectedItem,
  8087. itemClass: detail.markers.item,
  8088. onHighlight: detail.onHighlight
  8089. }),
  8090. Representing.config({
  8091. store: {
  8092. mode: 'memory',
  8093. initialValue: detail.value
  8094. }
  8095. }),
  8096. Composing.config({ find: Optional.some }),
  8097. Keying.config(detail.movement.config(detail, detail.movement))
  8098. ]),
  8099. events: derive$3([
  8100. run(focus$1(), function (menu, simulatedEvent) {
  8101. var event = simulatedEvent.event;
  8102. menu.getSystem().getByDom(event.target).each(function (item) {
  8103. Highlighting.highlight(menu, item);
  8104. simulatedEvent.stop();
  8105. emitWith(menu, focus(), {
  8106. menu: menu,
  8107. item: item
  8108. });
  8109. });
  8110. }),
  8111. run(hover(), function (menu, simulatedEvent) {
  8112. var item = simulatedEvent.event.item;
  8113. Highlighting.highlight(menu, item);
  8114. })
  8115. ]),
  8116. components: components,
  8117. eventOrder: detail.eventOrder,
  8118. domModification: { attributes: { role: 'menu' } }
  8119. };
  8120. };
  8121. var Menu = composite({
  8122. name: 'Menu',
  8123. configFields: schema$2(),
  8124. partFields: parts$2(),
  8125. factory: make$2
  8126. });
  8127. var preserve = function (f, container) {
  8128. var dos = getRootNode(container);
  8129. var refocus = active(dos).bind(function (focused) {
  8130. var hasFocus = function (elem) {
  8131. return eq(focused, elem);
  8132. };
  8133. return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  8134. });
  8135. var result = f(container);
  8136. refocus.each(function (oldFocus) {
  8137. active(dos).filter(function (newFocus) {
  8138. return eq(newFocus, oldFocus);
  8139. }).fold(function () {
  8140. focus$3(oldFocus);
  8141. }, noop);
  8142. });
  8143. return result;
  8144. };
  8145. var set = function (component, replaceConfig, replaceState, data) {
  8146. preserve(function () {
  8147. var newChildren = map$2(data, component.getSystem().build);
  8148. replaceChildren(component, newChildren);
  8149. }, component.element);
  8150. };
  8151. var insert = function (component, replaceConfig, insertion, childSpec) {
  8152. var child = component.getSystem().build(childSpec);
  8153. attachWith(component, child, insertion);
  8154. };
  8155. var append = function (component, replaceConfig, replaceState, appendee) {
  8156. insert(component, replaceConfig, append$2, appendee);
  8157. };
  8158. var prepend = function (component, replaceConfig, replaceState, prependee) {
  8159. insert(component, replaceConfig, prepend$1, prependee);
  8160. };
  8161. var remove = function (component, replaceConfig, replaceState, removee) {
  8162. var children = contents(component);
  8163. var foundChild = find$2(children, function (child) {
  8164. return eq(removee.element, child.element);
  8165. });
  8166. foundChild.each(detach);
  8167. };
  8168. var contents = function (component, _replaceConfig) {
  8169. return component.components();
  8170. };
  8171. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8172. var children = contents(component);
  8173. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  8174. remove(component, replaceConfig, replaceState, replacee);
  8175. replacer.each(function (r) {
  8176. insert(component, replaceConfig, function (p, c) {
  8177. appendAt(p, c, replaceeIndex);
  8178. }, r);
  8179. });
  8180. return replacee;
  8181. });
  8182. };
  8183. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8184. var children = contents(component);
  8185. return findIndex$1(children, replaceePred).bind(function (replaceeIndex) {
  8186. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8187. });
  8188. };
  8189. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8190. __proto__: null,
  8191. append: append,
  8192. prepend: prepend,
  8193. remove: remove,
  8194. replaceAt: replaceAt,
  8195. replaceBy: replaceBy,
  8196. set: set,
  8197. contents: contents
  8198. });
  8199. var Replacing = create$5({
  8200. fields: [],
  8201. name: 'replacing',
  8202. apis: ReplaceApis
  8203. });
  8204. var transpose = function (obj) {
  8205. return tupleMap(obj, function (v, k) {
  8206. return {
  8207. k: v,
  8208. v: k
  8209. };
  8210. });
  8211. };
  8212. var trace = function (items, byItem, byMenu, finish) {
  8213. return get$c(byMenu, finish).bind(function (triggerItem) {
  8214. return get$c(items, triggerItem).bind(function (triggerMenu) {
  8215. var rest = trace(items, byItem, byMenu, triggerMenu);
  8216. return Optional.some([triggerMenu].concat(rest));
  8217. });
  8218. }).getOr([]);
  8219. };
  8220. var generate = function (menus, expansions) {
  8221. var items = {};
  8222. each(menus, function (menuItems, menu) {
  8223. each$1(menuItems, function (item) {
  8224. items[item] = menu;
  8225. });
  8226. });
  8227. var byItem = expansions;
  8228. var byMenu = transpose(expansions);
  8229. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  8230. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8231. });
  8232. return map$1(items, function (menu) {
  8233. return get$c(menuPaths, menu).getOr([menu]);
  8234. });
  8235. };
  8236. var init$2 = function () {
  8237. var expansions = Cell({});
  8238. var menus = Cell({});
  8239. var paths = Cell({});
  8240. var primary = value();
  8241. var directory = Cell({});
  8242. var clear = function () {
  8243. expansions.set({});
  8244. menus.set({});
  8245. paths.set({});
  8246. primary.clear();
  8247. };
  8248. var isClear = function () {
  8249. return primary.get().isNone();
  8250. };
  8251. var setMenuBuilt = function (menuName, built) {
  8252. var _a;
  8253. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8254. type: 'prepared',
  8255. menu: built
  8256. }, _a)));
  8257. };
  8258. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8259. primary.set(sPrimary);
  8260. expansions.set(sExpansions);
  8261. menus.set(sMenus);
  8262. directory.set(dir);
  8263. var sPaths = generate(dir, sExpansions);
  8264. paths.set(sPaths);
  8265. };
  8266. var getTriggeringItem = function (menuValue) {
  8267. return find(expansions.get(), function (v, _k) {
  8268. return v === menuValue;
  8269. });
  8270. };
  8271. var getTriggerData = function (menuValue, getItemByValue, path) {
  8272. return getPreparedMenu(menuValue).bind(function (menu) {
  8273. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8274. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8275. return {
  8276. triggeredMenu: menu,
  8277. triggeringItem: triggeredItem,
  8278. triggeringPath: path
  8279. };
  8280. });
  8281. });
  8282. });
  8283. };
  8284. var getTriggeringPath = function (itemValue, getItemByValue) {
  8285. var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) {
  8286. return getPreparedMenu(menuValue).isSome();
  8287. });
  8288. return get$c(paths.get(), itemValue).bind(function (path) {
  8289. var revPath = reverse(extraPath.concat(path));
  8290. var triggers = bind$3(revPath, function (menuValue, menuIndex) {
  8291. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8292. return is(primary.get(), menuValue) ? [] : [Optional.none()];
  8293. }, function (data) {
  8294. return [Optional.some(data)];
  8295. });
  8296. });
  8297. return sequence(triggers);
  8298. });
  8299. };
  8300. var expand = function (itemValue) {
  8301. return get$c(expansions.get(), itemValue).map(function (menu) {
  8302. var current = get$c(paths.get(), itemValue).getOr([]);
  8303. return [menu].concat(current);
  8304. });
  8305. };
  8306. var collapse = function (itemValue) {
  8307. return get$c(paths.get(), itemValue).bind(function (path) {
  8308. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8309. });
  8310. };
  8311. var refresh = function (itemValue) {
  8312. return get$c(paths.get(), itemValue);
  8313. };
  8314. var getPreparedMenu = function (menuValue) {
  8315. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8316. };
  8317. var lookupMenu = function (menuValue) {
  8318. return get$c(menus.get(), menuValue);
  8319. };
  8320. var lookupItem = function (itemValue) {
  8321. return get$c(expansions.get(), itemValue);
  8322. };
  8323. var otherMenus = function (path) {
  8324. var menuValues = directory.get();
  8325. return difference(keys(menuValues), path);
  8326. };
  8327. var getPrimary = function () {
  8328. return primary.get().bind(getPreparedMenu);
  8329. };
  8330. var getMenus = function () {
  8331. return menus.get();
  8332. };
  8333. return {
  8334. setMenuBuilt: setMenuBuilt,
  8335. setContents: setContents,
  8336. expand: expand,
  8337. refresh: refresh,
  8338. collapse: collapse,
  8339. lookupMenu: lookupMenu,
  8340. lookupItem: lookupItem,
  8341. otherMenus: otherMenus,
  8342. getPrimary: getPrimary,
  8343. getMenus: getMenus,
  8344. clear: clear,
  8345. isClear: isClear,
  8346. getTriggeringPath: getTriggeringPath
  8347. };
  8348. };
  8349. var extractPreparedMenu = function (prep) {
  8350. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8351. };
  8352. var LayeredState = {
  8353. init: init$2,
  8354. extractPreparedMenu: extractPreparedMenu
  8355. };
  8356. var make$1 = function (detail, _rawUiSpec) {
  8357. var submenuParentItems = value();
  8358. var buildMenus = function (container, primaryName, menus) {
  8359. return map$1(menus, function (spec, name) {
  8360. var makeSketch = function () {
  8361. return Menu.sketch(__assign(__assign({}, spec), {
  8362. value: name,
  8363. markers: detail.markers,
  8364. fakeFocus: detail.fakeFocus,
  8365. onHighlight: detail.onHighlight,
  8366. focusManager: detail.fakeFocus ? highlights() : dom$2()
  8367. }));
  8368. };
  8369. return name === primaryName ? {
  8370. type: 'prepared',
  8371. menu: container.getSystem().build(makeSketch())
  8372. } : {
  8373. type: 'notbuilt',
  8374. nbMenu: makeSketch
  8375. };
  8376. });
  8377. };
  8378. var layeredState = LayeredState.init();
  8379. var setup = function (container) {
  8380. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8381. var directory = toDirectory();
  8382. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8383. return layeredState.getPrimary();
  8384. };
  8385. var getItemValue = function (item) {
  8386. return Representing.getValue(item).value;
  8387. };
  8388. var getItemByValue = function (_container, menus, itemValue) {
  8389. return findMap(menus, function (menu) {
  8390. if (!menu.getSystem().isConnected()) {
  8391. return Optional.none();
  8392. }
  8393. var candidates = Highlighting.getCandidates(menu);
  8394. return find$2(candidates, function (c) {
  8395. return getItemValue(c) === itemValue;
  8396. });
  8397. });
  8398. };
  8399. var toDirectory = function (_container) {
  8400. return map$1(detail.data.menus, function (data, _menuName) {
  8401. return bind$3(data.items, function (item) {
  8402. return item.type === 'separator' ? [] : [item.data.value];
  8403. });
  8404. });
  8405. };
  8406. var setActiveMenu = function (container, menu) {
  8407. Highlighting.highlight(container, menu);
  8408. Highlighting.getHighlighted(menu).orThunk(function () {
  8409. return Highlighting.getFirst(menu);
  8410. }).each(function (item) {
  8411. dispatch(container, item.element, focusItem());
  8412. });
  8413. };
  8414. var getMenus = function (state, menuValues) {
  8415. return cat(map$2(menuValues, function (mv) {
  8416. return state.lookupMenu(mv).bind(function (prep) {
  8417. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8418. });
  8419. }));
  8420. };
  8421. var closeOthers = function (container, state, path) {
  8422. var others = getMenus(state, state.otherMenus(path));
  8423. each$1(others, function (o) {
  8424. remove$1(o.element, [detail.markers.backgroundMenu]);
  8425. if (!detail.stayInDom) {
  8426. Replacing.remove(container, o);
  8427. }
  8428. });
  8429. };
  8430. var getSubmenuParents = function (container) {
  8431. return submenuParentItems.get().getOrThunk(function () {
  8432. var r = {};
  8433. var items = descendants(container.element, '.' + detail.markers.item);
  8434. var parentItems = filter$2(items, function (i) {
  8435. return get$b(i, 'aria-haspopup') === 'true';
  8436. });
  8437. each$1(parentItems, function (i) {
  8438. container.getSystem().getByDom(i).each(function (itemComp) {
  8439. var key = getItemValue(itemComp);
  8440. r[key] = itemComp;
  8441. });
  8442. });
  8443. submenuParentItems.set(r);
  8444. return r;
  8445. });
  8446. };
  8447. var updateAriaExpansions = function (container, path) {
  8448. var parentItems = getSubmenuParents(container);
  8449. each(parentItems, function (v, k) {
  8450. var expanded = contains$1(path, k);
  8451. set$8(v.element, 'aria-expanded', expanded);
  8452. });
  8453. };
  8454. var updateMenuPath = function (container, state, path) {
  8455. return Optional.from(path[0]).bind(function (latestMenuName) {
  8456. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8457. if (menuPrep.type === 'notbuilt') {
  8458. return Optional.none();
  8459. } else {
  8460. var activeMenu = menuPrep.menu;
  8461. var rest = getMenus(state, path.slice(1));
  8462. each$1(rest, function (r) {
  8463. add$1(r.element, detail.markers.backgroundMenu);
  8464. });
  8465. if (!inBody(activeMenu.element)) {
  8466. Replacing.append(container, premade(activeMenu));
  8467. }
  8468. remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
  8469. setActiveMenu(container, activeMenu);
  8470. closeOthers(container, state, path);
  8471. return Optional.some(activeMenu);
  8472. }
  8473. });
  8474. });
  8475. };
  8476. var ExpandHighlightDecision;
  8477. (function (ExpandHighlightDecision) {
  8478. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8479. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8480. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8481. var buildIfRequired = function (container, menuName, menuPrep) {
  8482. if (menuPrep.type === 'notbuilt') {
  8483. var menu = container.getSystem().build(menuPrep.nbMenu());
  8484. layeredState.setMenuBuilt(menuName, menu);
  8485. return menu;
  8486. } else {
  8487. return menuPrep.menu;
  8488. }
  8489. };
  8490. var expandRight = function (container, item, decision) {
  8491. if (decision === void 0) {
  8492. decision = ExpandHighlightDecision.HighlightSubmenu;
  8493. }
  8494. if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  8495. return Optional.some(item);
  8496. } else {
  8497. var value = getItemValue(item);
  8498. return layeredState.expand(value).bind(function (path) {
  8499. updateAriaExpansions(container, path);
  8500. return Optional.from(path[0]).bind(function (menuName) {
  8501. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8502. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8503. if (!inBody(activeMenu.element)) {
  8504. Replacing.append(container, premade(activeMenu));
  8505. }
  8506. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8507. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8508. Highlighting.highlightFirst(activeMenu);
  8509. return updateMenuPath(container, layeredState, path);
  8510. } else {
  8511. Highlighting.dehighlightAll(activeMenu);
  8512. return Optional.some(item);
  8513. }
  8514. });
  8515. });
  8516. });
  8517. }
  8518. };
  8519. var collapseLeft = function (container, item) {
  8520. var value = getItemValue(item);
  8521. return layeredState.collapse(value).bind(function (path) {
  8522. updateAriaExpansions(container, path);
  8523. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8524. detail.onCollapseMenu(container, item, activeMenu);
  8525. return activeMenu;
  8526. });
  8527. });
  8528. };
  8529. var updateView = function (container, item) {
  8530. var value = getItemValue(item);
  8531. return layeredState.refresh(value).bind(function (path) {
  8532. updateAriaExpansions(container, path);
  8533. return updateMenuPath(container, layeredState, path);
  8534. });
  8535. };
  8536. var onRight = function (container, item) {
  8537. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8538. };
  8539. var onLeft = function (container, item) {
  8540. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8541. };
  8542. var onEscape = function (container, item) {
  8543. return collapseLeft(container, item).orThunk(function () {
  8544. return detail.onEscape(container, item).map(function () {
  8545. return container;
  8546. });
  8547. });
  8548. };
  8549. var keyOnItem = function (f) {
  8550. return function (container, simulatedEvent) {
  8551. return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8552. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8553. return f(container, item).map(always);
  8554. });
  8555. });
  8556. };
  8557. };
  8558. var events = derive$3([
  8559. run(focus(), function (sandbox, simulatedEvent) {
  8560. var item = simulatedEvent.event.item;
  8561. layeredState.lookupItem(getItemValue(item)).each(function () {
  8562. var menu = simulatedEvent.event.menu;
  8563. Highlighting.highlight(sandbox, menu);
  8564. var value = getItemValue(simulatedEvent.event.item);
  8565. layeredState.refresh(value).each(function (path) {
  8566. return closeOthers(sandbox, layeredState, path);
  8567. });
  8568. });
  8569. }),
  8570. runOnExecute(function (component, simulatedEvent) {
  8571. var target = simulatedEvent.event.target;
  8572. component.getSystem().getByDom(target).each(function (item) {
  8573. var itemValue = getItemValue(item);
  8574. if (itemValue.indexOf('collapse-item') === 0) {
  8575. collapseLeft(component, item);
  8576. }
  8577. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8578. detail.onExecute(component, item);
  8579. }, noop);
  8580. });
  8581. }),
  8582. runOnAttached(function (container, _simulatedEvent) {
  8583. setup(container).each(function (primary) {
  8584. Replacing.append(container, premade(primary));
  8585. detail.onOpenMenu(container, primary);
  8586. if (detail.highlightImmediately) {
  8587. setActiveMenu(container, primary);
  8588. }
  8589. });
  8590. })
  8591. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8592. var item = simulatedEvent.event.item;
  8593. updateView(sandbox, item);
  8594. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8595. detail.onHover(sandbox, item);
  8596. })] : []));
  8597. var getActiveItem = function (container) {
  8598. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8599. };
  8600. var collapseMenuApi = function (container) {
  8601. getActiveItem(container).each(function (currentItem) {
  8602. collapseLeft(container, currentItem);
  8603. });
  8604. };
  8605. var highlightPrimary = function (container) {
  8606. layeredState.getPrimary().each(function (primary) {
  8607. setActiveMenu(container, primary);
  8608. });
  8609. };
  8610. var extractMenuFromContainer = function (container) {
  8611. return Optional.from(container.components()[0]).filter(function (comp) {
  8612. return get$b(comp.element, 'role') === 'menu';
  8613. });
  8614. };
  8615. var repositionMenus = function (container) {
  8616. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8617. return getActiveItem(container).bind(function (currentItem) {
  8618. var itemValue = getItemValue(currentItem);
  8619. var allMenus = values(layeredState.getMenus());
  8620. var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  8621. return layeredState.getTriggeringPath(itemValue, function (v) {
  8622. return getItemByValue(container, preparedMenus, v);
  8623. });
  8624. }).map(function (triggeringPath) {
  8625. return {
  8626. primary: primary,
  8627. triggeringPath: triggeringPath
  8628. };
  8629. });
  8630. });
  8631. maybeActivePrimary.fold(function () {
  8632. extractMenuFromContainer(container).each(function (primaryMenu) {
  8633. detail.onRepositionMenu(container, primaryMenu, []);
  8634. });
  8635. }, function (_a) {
  8636. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8637. detail.onRepositionMenu(container, primary, triggeringPath);
  8638. });
  8639. };
  8640. var apis = {
  8641. collapseMenu: collapseMenuApi,
  8642. highlightPrimary: highlightPrimary,
  8643. repositionMenus: repositionMenus
  8644. };
  8645. return {
  8646. uid: detail.uid,
  8647. dom: detail.dom,
  8648. markers: detail.markers,
  8649. behaviours: augment(detail.tmenuBehaviours, [
  8650. Keying.config({
  8651. mode: 'special',
  8652. onRight: keyOnItem(onRight),
  8653. onLeft: keyOnItem(onLeft),
  8654. onEscape: keyOnItem(onEscape),
  8655. focusIn: function (container, _keyInfo) {
  8656. layeredState.getPrimary().each(function (primary) {
  8657. dispatch(container, primary.element, focusItem());
  8658. });
  8659. }
  8660. }),
  8661. Highlighting.config({
  8662. highlightClass: detail.markers.selectedMenu,
  8663. itemClass: detail.markers.menu
  8664. }),
  8665. Composing.config({
  8666. find: function (container) {
  8667. return Highlighting.getHighlighted(container);
  8668. }
  8669. }),
  8670. Replacing.config({})
  8671. ]),
  8672. eventOrder: detail.eventOrder,
  8673. apis: apis,
  8674. events: events
  8675. };
  8676. };
  8677. var collapseItem$1 = constant$1('collapse-item');
  8678. var tieredData = function (primary, menus, expansions) {
  8679. return {
  8680. primary: primary,
  8681. menus: menus,
  8682. expansions: expansions
  8683. };
  8684. };
  8685. var singleData = function (name, menu) {
  8686. return {
  8687. primary: name,
  8688. menus: wrap(name, menu),
  8689. expansions: {}
  8690. };
  8691. };
  8692. var collapseItem = function (text) {
  8693. return {
  8694. value: generate$4(collapseItem$1()),
  8695. meta: { text: text }
  8696. };
  8697. };
  8698. var tieredMenu = single({
  8699. name: 'TieredMenu',
  8700. configFields: [
  8701. onStrictKeyboardHandler('onExecute'),
  8702. onStrictKeyboardHandler('onEscape'),
  8703. onStrictHandler('onOpenMenu'),
  8704. onStrictHandler('onOpenSubmenu'),
  8705. onHandler('onRepositionMenu'),
  8706. onHandler('onCollapseMenu'),
  8707. defaulted('highlightImmediately', true),
  8708. requiredObjOf('data', [
  8709. required$1('primary'),
  8710. required$1('menus'),
  8711. required$1('expansions')
  8712. ]),
  8713. defaulted('fakeFocus', false),
  8714. onHandler('onHighlight'),
  8715. onHandler('onHover'),
  8716. tieredMenuMarkers(),
  8717. required$1('dom'),
  8718. defaulted('navigateOnHover', true),
  8719. defaulted('stayInDom', false),
  8720. field$1('tmenuBehaviours', [
  8721. Keying,
  8722. Highlighting,
  8723. Composing,
  8724. Replacing
  8725. ]),
  8726. defaulted('eventOrder', {})
  8727. ],
  8728. apis: {
  8729. collapseMenu: function (apis, tmenu) {
  8730. apis.collapseMenu(tmenu);
  8731. },
  8732. highlightPrimary: function (apis, tmenu) {
  8733. apis.highlightPrimary(tmenu);
  8734. },
  8735. repositionMenus: function (apis, tmenu) {
  8736. apis.repositionMenus(tmenu);
  8737. }
  8738. },
  8739. factory: make$1,
  8740. extraApis: {
  8741. tieredData: tieredData,
  8742. singleData: singleData,
  8743. collapseItem: collapseItem
  8744. }
  8745. });
  8746. var findRoute = function (component, transConfig, transState, route) {
  8747. return get$c(transConfig.routes, route.start).bind(function (sConfig) {
  8748. return get$c(sConfig, route.destination);
  8749. });
  8750. };
  8751. var getTransition = function (comp, transConfig, transState) {
  8752. var route = getCurrentRoute(comp, transConfig);
  8753. return route.bind(function (r) {
  8754. return getTransitionOf(comp, transConfig, transState, r);
  8755. });
  8756. };
  8757. var getTransitionOf = function (comp, transConfig, transState, route) {
  8758. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8759. return r.transition.map(function (t) {
  8760. return {
  8761. transition: t,
  8762. route: r
  8763. };
  8764. });
  8765. });
  8766. };
  8767. var disableTransition = function (comp, transConfig, transState) {
  8768. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8769. var t = routeTransition.transition;
  8770. remove$3(comp.element, t.transitionClass);
  8771. remove$6(comp.element, transConfig.destinationAttr);
  8772. });
  8773. };
  8774. var getNewRoute = function (comp, transConfig, transState, destination) {
  8775. return {
  8776. start: get$b(comp.element, transConfig.stateAttr),
  8777. destination: destination
  8778. };
  8779. };
  8780. var getCurrentRoute = function (comp, transConfig, _transState) {
  8781. var el = comp.element;
  8782. return getOpt(el, transConfig.destinationAttr).map(function (destination) {
  8783. return {
  8784. start: get$b(comp.element, transConfig.stateAttr),
  8785. destination: destination
  8786. };
  8787. });
  8788. };
  8789. var jumpTo = function (comp, transConfig, transState, destination) {
  8790. disableTransition(comp, transConfig, transState);
  8791. if (has$1(comp.element, transConfig.stateAttr) && get$b(comp.element, transConfig.stateAttr) !== destination) {
  8792. transConfig.onFinish(comp, destination);
  8793. }
  8794. set$8(comp.element, transConfig.stateAttr, destination);
  8795. };
  8796. var fasttrack = function (comp, transConfig, _transState, _destination) {
  8797. if (has$1(comp.element, transConfig.destinationAttr)) {
  8798. getOpt(comp.element, transConfig.destinationAttr).each(function (destination) {
  8799. set$8(comp.element, transConfig.stateAttr, destination);
  8800. });
  8801. remove$6(comp.element, transConfig.destinationAttr);
  8802. }
  8803. };
  8804. var progressTo = function (comp, transConfig, transState, destination) {
  8805. fasttrack(comp, transConfig);
  8806. var route = getNewRoute(comp, transConfig, transState, destination);
  8807. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8808. jumpTo(comp, transConfig, transState, destination);
  8809. }, function (routeTransition) {
  8810. disableTransition(comp, transConfig, transState);
  8811. var t = routeTransition.transition;
  8812. add$1(comp.element, t.transitionClass);
  8813. set$8(comp.element, transConfig.destinationAttr, destination);
  8814. });
  8815. };
  8816. var getState = function (comp, transConfig, _transState) {
  8817. return getOpt(comp.element, transConfig.stateAttr);
  8818. };
  8819. var TransitionApis = /*#__PURE__*/Object.freeze({
  8820. __proto__: null,
  8821. findRoute: findRoute,
  8822. disableTransition: disableTransition,
  8823. getCurrentRoute: getCurrentRoute,
  8824. jumpTo: jumpTo,
  8825. progressTo: progressTo,
  8826. getState: getState
  8827. });
  8828. var events$1 = function (transConfig, transState) {
  8829. return derive$3([
  8830. run(transitionend(), function (component, simulatedEvent) {
  8831. var raw = simulatedEvent.event.raw;
  8832. getCurrentRoute(component, transConfig).each(function (route) {
  8833. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8834. rInfo.transition.each(function (rTransition) {
  8835. if (raw.propertyName === rTransition.property) {
  8836. jumpTo(component, transConfig, transState, route.destination);
  8837. transConfig.onTransition(component, route);
  8838. }
  8839. });
  8840. });
  8841. });
  8842. }),
  8843. runOnAttached(function (comp, _se) {
  8844. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8845. })
  8846. ]);
  8847. };
  8848. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8849. __proto__: null,
  8850. events: events$1
  8851. });
  8852. var TransitionSchema = [
  8853. defaulted('destinationAttr', 'data-transitioning-destination'),
  8854. defaulted('stateAttr', 'data-transitioning-state'),
  8855. required$1('initialState'),
  8856. onHandler('onTransition'),
  8857. onHandler('onFinish'),
  8858. requiredOf('routes', setOf(Result.value, setOf(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8859. required$1('property'),
  8860. required$1('transitionClass')
  8861. ])]))))
  8862. ];
  8863. var createRoutes = function (routes) {
  8864. var r = {};
  8865. each(routes, function (v, k) {
  8866. var waypoints = k.split('<->');
  8867. r[waypoints[0]] = wrap(waypoints[1], v);
  8868. r[waypoints[1]] = wrap(waypoints[0], v);
  8869. });
  8870. return r;
  8871. };
  8872. var createBistate = function (first, second, transitions) {
  8873. return wrapAll([
  8874. {
  8875. key: first,
  8876. value: wrap(second, transitions)
  8877. },
  8878. {
  8879. key: second,
  8880. value: wrap(first, transitions)
  8881. }
  8882. ]);
  8883. };
  8884. var createTristate = function (first, second, third, transitions) {
  8885. return wrapAll([
  8886. {
  8887. key: first,
  8888. value: wrapAll([
  8889. {
  8890. key: second,
  8891. value: transitions
  8892. },
  8893. {
  8894. key: third,
  8895. value: transitions
  8896. }
  8897. ])
  8898. },
  8899. {
  8900. key: second,
  8901. value: wrapAll([
  8902. {
  8903. key: first,
  8904. value: transitions
  8905. },
  8906. {
  8907. key: third,
  8908. value: transitions
  8909. }
  8910. ])
  8911. },
  8912. {
  8913. key: third,
  8914. value: wrapAll([
  8915. {
  8916. key: first,
  8917. value: transitions
  8918. },
  8919. {
  8920. key: second,
  8921. value: transitions
  8922. }
  8923. ])
  8924. }
  8925. ]);
  8926. };
  8927. var Transitioning = create$5({
  8928. fields: TransitionSchema,
  8929. name: 'transitioning',
  8930. active: ActiveTransitioning,
  8931. apis: TransitionApis,
  8932. extra: {
  8933. createRoutes: createRoutes,
  8934. createBistate: createBistate,
  8935. createTristate: createTristate
  8936. }
  8937. });
  8938. var scrollableStyle = resolve('scrollable');
  8939. var register$2 = function (element) {
  8940. add$1(element, scrollableStyle);
  8941. };
  8942. var deregister = function (element) {
  8943. remove$3(element, scrollableStyle);
  8944. };
  8945. var scrollable = scrollableStyle;
  8946. var getValue = function (item) {
  8947. return get$c(item, 'format').getOr(item.title);
  8948. };
  8949. var convert = function (formats, memMenuThunk) {
  8950. var mainMenu = makeMenu('Styles', [].concat(map$2(formats.items, function (k) {
  8951. return makeItem(getValue(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue(k)));
  8952. })), memMenuThunk, false);
  8953. var submenus = map$1(formats.menus, function (menuItems, menuName) {
  8954. var items = map$2(menuItems, function (item) {
  8955. return makeItem(getValue(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue(item)));
  8956. });
  8957. return makeMenu(menuName, items, memMenuThunk, true);
  8958. });
  8959. var menus = deepMerge(submenus, wrap('styles', mainMenu));
  8960. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  8961. return { tmenu: tmenu };
  8962. };
  8963. var makeItem = function (value, text, selected, preview, isMenu) {
  8964. return {
  8965. data: {
  8966. value: value,
  8967. text: text
  8968. },
  8969. type: 'item',
  8970. dom: {
  8971. tag: 'div',
  8972. classes: isMenu ? [resolve('styles-item-is-menu')] : []
  8973. },
  8974. toggling: {
  8975. toggleOnExecute: false,
  8976. toggleClass: resolve('format-matches'),
  8977. selected: selected
  8978. },
  8979. itemBehaviours: derive$2(isMenu ? [] : [format(value, function (comp, status) {
  8980. var toggle = status ? Toggling.on : Toggling.off;
  8981. toggle(comp);
  8982. })]),
  8983. components: [{
  8984. dom: {
  8985. tag: 'div',
  8986. attributes: { style: preview },
  8987. innerHtml: text
  8988. }
  8989. }]
  8990. };
  8991. };
  8992. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  8993. return {
  8994. value: value,
  8995. dom: { tag: 'div' },
  8996. components: [
  8997. Button.sketch({
  8998. dom: {
  8999. tag: 'div',
  9000. classes: [resolve('styles-collapser')]
  9001. },
  9002. components: collapsable ? [
  9003. {
  9004. dom: {
  9005. tag: 'span',
  9006. classes: [resolve('styles-collapse-icon')]
  9007. }
  9008. },
  9009. text(value)
  9010. ] : [text(value)],
  9011. action: function (item) {
  9012. if (collapsable) {
  9013. var comp = memMenuThunk().get(item);
  9014. tieredMenu.collapseMenu(comp);
  9015. }
  9016. }
  9017. }),
  9018. {
  9019. dom: {
  9020. tag: 'div',
  9021. classes: [resolve('styles-menu-items-container')]
  9022. },
  9023. components: [Menu.parts.items({})],
  9024. behaviours: derive$2([config('adhoc-scrollable-menu', [
  9025. runOnAttached(function (component, _simulatedEvent) {
  9026. set$5(component.element, 'overflow-y', 'auto');
  9027. set$5(component.element, '-webkit-overflow-scrolling', 'touch');
  9028. register$2(component.element);
  9029. }),
  9030. runOnDetached(function (component) {
  9031. remove$2(component.element, 'overflow-y');
  9032. remove$2(component.element, '-webkit-overflow-scrolling');
  9033. deregister(component.element);
  9034. })
  9035. ])])
  9036. }
  9037. ],
  9038. items: items,
  9039. menuBehaviours: derive$2([Transitioning.config({
  9040. initialState: 'after',
  9041. routes: Transitioning.createTristate('before', 'current', 'after', {
  9042. transition: {
  9043. property: 'transform',
  9044. transitionClass: 'transitioning'
  9045. }
  9046. })
  9047. })])
  9048. };
  9049. };
  9050. var sketch$1 = function (settings) {
  9051. var dataset = convert(settings.formats, function () {
  9052. return memMenu;
  9053. });
  9054. var memMenu = record(tieredMenu.sketch({
  9055. dom: {
  9056. tag: 'div',
  9057. classes: [resolve('styles-menu')]
  9058. },
  9059. components: [],
  9060. fakeFocus: true,
  9061. stayInDom: true,
  9062. onExecute: function (_tmenu, item) {
  9063. var v = Representing.getValue(item);
  9064. settings.handle(item, v.value);
  9065. return Optional.none();
  9066. },
  9067. onEscape: function () {
  9068. return Optional.none();
  9069. },
  9070. onOpenMenu: function (container, menu) {
  9071. var w = get$5(container.element);
  9072. set$4(menu.element, w);
  9073. Transitioning.jumpTo(menu, 'current');
  9074. },
  9075. onOpenSubmenu: function (container, item, submenu) {
  9076. var w = get$5(container.element);
  9077. var menu = ancestor(item.element, '[role="menu"]').getOrDie('hacky');
  9078. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9079. set$4(submenu.element, w);
  9080. Transitioning.progressTo(menuComp, 'before');
  9081. Transitioning.jumpTo(submenu, 'after');
  9082. Transitioning.progressTo(submenu, 'current');
  9083. },
  9084. onCollapseMenu: function (container, item, menu) {
  9085. var submenu = ancestor(item.element, '[role="menu"]').getOrDie('hacky');
  9086. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9087. Transitioning.progressTo(submenuComp, 'after');
  9088. Transitioning.progressTo(menu, 'current');
  9089. },
  9090. navigateOnHover: false,
  9091. highlightImmediately: true,
  9092. data: dataset.tmenu,
  9093. markers: {
  9094. backgroundMenu: resolve('styles-background-menu'),
  9095. menu: resolve('styles-menu'),
  9096. selectedMenu: resolve('styles-selected-menu'),
  9097. item: resolve('styles-item'),
  9098. selectedItem: resolve('styles-selected-item')
  9099. }
  9100. }));
  9101. return memMenu.asSpec();
  9102. };
  9103. var getFromExpandingItem = function (item) {
  9104. var newItem = deepMerge(exclude(item, ['items']), { menu: true });
  9105. var rest = expand(item.items);
  9106. var newMenus = deepMerge(rest.menus, wrap(item.title, rest.items));
  9107. var newExpansions = deepMerge(rest.expansions, wrap(item.title, item.title));
  9108. return {
  9109. item: newItem,
  9110. menus: newMenus,
  9111. expansions: newExpansions
  9112. };
  9113. };
  9114. var getFromItem = function (item) {
  9115. return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : {
  9116. item: item,
  9117. menus: {},
  9118. expansions: {}
  9119. };
  9120. };
  9121. var expand = function (items) {
  9122. return foldr(items, function (acc, item) {
  9123. var newData = getFromItem(item);
  9124. return {
  9125. menus: deepMerge(acc.menus, newData.menus),
  9126. items: [newData.item].concat(acc.items),
  9127. expansions: deepMerge(acc.expansions, newData.expansions)
  9128. };
  9129. }, {
  9130. menus: {},
  9131. expansions: {},
  9132. items: []
  9133. });
  9134. };
  9135. var register$1 = function (editor) {
  9136. var isSelectedFor = function (format) {
  9137. return function () {
  9138. return editor.formatter.match(format);
  9139. };
  9140. };
  9141. var getPreview = function (format) {
  9142. return function () {
  9143. return editor.formatter.getCssText(format);
  9144. };
  9145. };
  9146. var enrichSupported = function (item) {
  9147. return deepMerge(item, {
  9148. isSelected: isSelectedFor(item.format),
  9149. getPreview: getPreview(item.format)
  9150. });
  9151. };
  9152. var enrichMenu = function (item) {
  9153. return deepMerge(item, {
  9154. isSelected: never,
  9155. getPreview: constant$1('')
  9156. });
  9157. };
  9158. var enrichCustom = function (item) {
  9159. var formatName = generate$4(item.title);
  9160. var newItem = deepMerge(item, {
  9161. format: formatName,
  9162. isSelected: isSelectedFor(formatName),
  9163. getPreview: getPreview(formatName)
  9164. });
  9165. editor.formatter.register(formatName, newItem);
  9166. return newItem;
  9167. };
  9168. var doEnrich = function (items) {
  9169. return map$2(items, function (item) {
  9170. if (hasNonNullableKey(item, 'items')) {
  9171. var newItems = doEnrich(item.items);
  9172. return deepMerge(enrichMenu(item), { items: newItems });
  9173. } else if (hasNonNullableKey(item, 'format')) {
  9174. return enrichSupported(item);
  9175. } else {
  9176. return enrichCustom(item);
  9177. }
  9178. });
  9179. };
  9180. return doEnrich(getStyleFormats(editor));
  9181. };
  9182. var prune = function (editor, formats) {
  9183. var doPrune = function (items) {
  9184. return bind$3(items, function (item) {
  9185. if (item.items !== undefined) {
  9186. var newItems = doPrune(item.items);
  9187. return newItems.length > 0 ? [item] : [];
  9188. } else {
  9189. var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9190. return keep ? [item] : [];
  9191. }
  9192. });
  9193. };
  9194. var prunedItems = doPrune(formats);
  9195. return expand(prunedItems);
  9196. };
  9197. var ui = function (editor, formats, onDone) {
  9198. var pruned = prune(editor, formats);
  9199. return sketch$1({
  9200. formats: pruned,
  9201. handle: function (item, value) {
  9202. editor.undoManager.transact(function () {
  9203. if (Toggling.isOn(item)) {
  9204. editor.formatter.remove(value);
  9205. } else {
  9206. editor.formatter.apply(value);
  9207. }
  9208. });
  9209. onDone();
  9210. }
  9211. });
  9212. };
  9213. var extract = function (rawToolbar) {
  9214. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9215. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9216. };
  9217. var identifyFromArray = function (toolbar) {
  9218. return bind$3(toolbar, function (item) {
  9219. return isArray(item) ? identifyFromArray(item) : extract(item);
  9220. });
  9221. };
  9222. var identify = function (editor) {
  9223. var toolbar = getToolbar(editor);
  9224. return isArray(toolbar) ? identifyFromArray(toolbar) : extract(toolbar);
  9225. };
  9226. var setup$3 = function (realm, editor) {
  9227. var commandSketch = function (name) {
  9228. return function () {
  9229. return forToolbarCommand(editor, name);
  9230. };
  9231. };
  9232. var stateCommandSketch = function (name) {
  9233. return function () {
  9234. return forToolbarStateCommand(editor, name);
  9235. };
  9236. };
  9237. var actionSketch = function (name, query, action) {
  9238. return function () {
  9239. return forToolbarStateAction(editor, name, query, action);
  9240. };
  9241. };
  9242. var undo = commandSketch('undo');
  9243. var redo = commandSketch('redo');
  9244. var bold = stateCommandSketch('bold');
  9245. var italic = stateCommandSketch('italic');
  9246. var underline = stateCommandSketch('underline');
  9247. var removeformat = commandSketch('removeformat');
  9248. var link = function () {
  9249. return sketch$2(realm, editor);
  9250. };
  9251. var unlink = actionSketch('unlink', 'link', function () {
  9252. editor.execCommand('unlink', null, false);
  9253. });
  9254. var image = function () {
  9255. return sketch$5(editor);
  9256. };
  9257. var bullist = actionSketch('unordered-list', 'ul', function () {
  9258. editor.execCommand('InsertUnorderedList', null, false);
  9259. });
  9260. var numlist = actionSketch('ordered-list', 'ol', function () {
  9261. editor.execCommand('InsertOrderedList', null, false);
  9262. });
  9263. var fontsizeselect = function () {
  9264. return sketch$6(realm, editor);
  9265. };
  9266. var forecolor = function () {
  9267. return sketch$8(realm, editor);
  9268. };
  9269. var styleFormats = register$1(editor);
  9270. var styleFormatsMenu = function () {
  9271. return ui(editor, styleFormats, function () {
  9272. editor.fire('scrollIntoView');
  9273. });
  9274. };
  9275. var styleselect = function () {
  9276. return forToolbar('style-formats', function (button) {
  9277. editor.fire('toReading');
  9278. realm.dropup.appear(styleFormatsMenu, Toggling.on, button);
  9279. }, derive$2([
  9280. Toggling.config({
  9281. toggleClass: resolve('toolbar-button-selected'),
  9282. toggleOnExecute: false,
  9283. aria: { mode: 'pressed' }
  9284. }),
  9285. Receiving.config({
  9286. channels: wrapAll([
  9287. receive(orientationChanged, Toggling.off),
  9288. receive(dropupDismissed, Toggling.off)
  9289. ])
  9290. })
  9291. ]), editor);
  9292. };
  9293. var feature = function (prereq, sketch) {
  9294. return {
  9295. isSupported: function () {
  9296. var buttons = editor.ui.registry.getAll().buttons;
  9297. return prereq.forall(function (p) {
  9298. return hasNonNullableKey(buttons, p);
  9299. });
  9300. },
  9301. sketch: sketch
  9302. };
  9303. };
  9304. return {
  9305. undo: feature(Optional.none(), undo),
  9306. redo: feature(Optional.none(), redo),
  9307. bold: feature(Optional.none(), bold),
  9308. italic: feature(Optional.none(), italic),
  9309. underline: feature(Optional.none(), underline),
  9310. removeformat: feature(Optional.none(), removeformat),
  9311. link: feature(Optional.none(), link),
  9312. unlink: feature(Optional.none(), unlink),
  9313. image: feature(Optional.none(), image),
  9314. bullist: feature(Optional.some('bullist'), bullist),
  9315. numlist: feature(Optional.some('numlist'), numlist),
  9316. fontsizeselect: feature(Optional.none(), fontsizeselect),
  9317. forecolor: feature(Optional.none(), forecolor),
  9318. styleselect: feature(Optional.none(), styleselect)
  9319. };
  9320. };
  9321. var detect = function (editor, features) {
  9322. var itemNames = identify(editor);
  9323. var present = {};
  9324. return bind$3(itemNames, function (iName) {
  9325. var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9326. present[iName] = true;
  9327. return r;
  9328. });
  9329. };
  9330. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9331. return {
  9332. target: target,
  9333. x: x,
  9334. y: y,
  9335. stop: stop,
  9336. prevent: prevent,
  9337. kill: kill,
  9338. raw: raw
  9339. };
  9340. };
  9341. var fromRawEvent = function (rawEvent) {
  9342. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  9343. var stop = function () {
  9344. return rawEvent.stopPropagation();
  9345. };
  9346. var prevent = function () {
  9347. return rawEvent.preventDefault();
  9348. };
  9349. var kill = compose(prevent, stop);
  9350. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9351. };
  9352. var handle = function (filter, handler) {
  9353. return function (rawEvent) {
  9354. if (filter(rawEvent)) {
  9355. handler(fromRawEvent(rawEvent));
  9356. }
  9357. };
  9358. };
  9359. var binder = function (element, event, filter, handler, useCapture) {
  9360. var wrapped = handle(filter, handler);
  9361. element.dom.addEventListener(event, wrapped, useCapture);
  9362. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9363. };
  9364. var bind$1 = function (element, event, filter, handler) {
  9365. return binder(element, event, filter, handler, false);
  9366. };
  9367. var capture$1 = function (element, event, filter, handler) {
  9368. return binder(element, event, filter, handler, true);
  9369. };
  9370. var unbind = function (element, event, handler, useCapture) {
  9371. element.dom.removeEventListener(event, handler, useCapture);
  9372. };
  9373. var filter = always;
  9374. var bind = function (element, event, handler) {
  9375. return bind$1(element, event, filter, handler);
  9376. };
  9377. var capture = function (element, event, handler) {
  9378. return capture$1(element, event, filter, handler);
  9379. };
  9380. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9381. var INTERVAL = 50;
  9382. var INSURANCE = 1000 / INTERVAL;
  9383. var get$1 = function (outerWindow) {
  9384. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9385. return { isPortrait: constant$1(isPortrait) };
  9386. };
  9387. var getActualWidth = function (outerWindow) {
  9388. var isIos = detect$1().os.isiOS();
  9389. var isPortrait = get$1(outerWindow).isPortrait();
  9390. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9391. };
  9392. var onChange = function (outerWindow, listeners) {
  9393. var win = SugarElement.fromDom(outerWindow);
  9394. var poller = null;
  9395. var change = function () {
  9396. global$2.clearInterval(poller);
  9397. var orientation = get$1(outerWindow);
  9398. listeners.onChange(orientation);
  9399. onAdjustment(function () {
  9400. listeners.onReady(orientation);
  9401. });
  9402. };
  9403. var orientationHandle = bind(win, 'orientationchange', change);
  9404. var onAdjustment = function (f) {
  9405. global$2.clearInterval(poller);
  9406. var flag = outerWindow.innerHeight;
  9407. var insurance = 0;
  9408. poller = global$2.setInterval(function () {
  9409. if (flag !== outerWindow.innerHeight) {
  9410. global$2.clearInterval(poller);
  9411. f(Optional.some(outerWindow.innerHeight));
  9412. } else if (insurance > INSURANCE) {
  9413. global$2.clearInterval(poller);
  9414. f(Optional.none());
  9415. }
  9416. insurance++;
  9417. }, INTERVAL);
  9418. };
  9419. var destroy = function () {
  9420. orientationHandle.unbind();
  9421. };
  9422. return {
  9423. onAdjustment: onAdjustment,
  9424. destroy: destroy
  9425. };
  9426. };
  9427. var setStart = function (rng, situ) {
  9428. situ.fold(function (e) {
  9429. rng.setStartBefore(e.dom);
  9430. }, function (e, o) {
  9431. rng.setStart(e.dom, o);
  9432. }, function (e) {
  9433. rng.setStartAfter(e.dom);
  9434. });
  9435. };
  9436. var setFinish = function (rng, situ) {
  9437. situ.fold(function (e) {
  9438. rng.setEndBefore(e.dom);
  9439. }, function (e, o) {
  9440. rng.setEnd(e.dom, o);
  9441. }, function (e) {
  9442. rng.setEndAfter(e.dom);
  9443. });
  9444. };
  9445. var relativeToNative = function (win, startSitu, finishSitu) {
  9446. var range = win.document.createRange();
  9447. setStart(range, startSitu);
  9448. setFinish(range, finishSitu);
  9449. return range;
  9450. };
  9451. var exactToNative = function (win, start, soffset, finish, foffset) {
  9452. var rng = win.document.createRange();
  9453. rng.setStart(start.dom, soffset);
  9454. rng.setEnd(finish.dom, foffset);
  9455. return rng;
  9456. };
  9457. var toRect$1 = function (rect) {
  9458. return {
  9459. left: rect.left,
  9460. top: rect.top,
  9461. right: rect.right,
  9462. bottom: rect.bottom,
  9463. width: rect.width,
  9464. height: rect.height
  9465. };
  9466. };
  9467. var getFirstRect$1 = function (rng) {
  9468. var rects = rng.getClientRects();
  9469. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9470. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect$1) : Optional.none();
  9471. };
  9472. var adt$3 = Adt.generate([
  9473. {
  9474. ltr: [
  9475. 'start',
  9476. 'soffset',
  9477. 'finish',
  9478. 'foffset'
  9479. ]
  9480. },
  9481. {
  9482. rtl: [
  9483. 'start',
  9484. 'soffset',
  9485. 'finish',
  9486. 'foffset'
  9487. ]
  9488. }
  9489. ]);
  9490. var fromRange = function (win, type, range) {
  9491. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  9492. };
  9493. var getRanges = function (win, selection) {
  9494. return selection.match({
  9495. domRange: function (rng) {
  9496. return {
  9497. ltr: constant$1(rng),
  9498. rtl: Optional.none
  9499. };
  9500. },
  9501. relative: function (startSitu, finishSitu) {
  9502. return {
  9503. ltr: cached(function () {
  9504. return relativeToNative(win, startSitu, finishSitu);
  9505. }),
  9506. rtl: cached(function () {
  9507. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  9508. })
  9509. };
  9510. },
  9511. exact: function (start, soffset, finish, foffset) {
  9512. return {
  9513. ltr: cached(function () {
  9514. return exactToNative(win, start, soffset, finish, foffset);
  9515. }),
  9516. rtl: cached(function () {
  9517. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  9518. })
  9519. };
  9520. }
  9521. });
  9522. };
  9523. var doDiagnose = function (win, ranges) {
  9524. var rng = ranges.ltr();
  9525. if (rng.collapsed) {
  9526. var reversed = ranges.rtl().filter(function (rev) {
  9527. return rev.collapsed === false;
  9528. });
  9529. return reversed.map(function (rev) {
  9530. return adt$3.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  9531. }).getOrThunk(function () {
  9532. return fromRange(win, adt$3.ltr, rng);
  9533. });
  9534. } else {
  9535. return fromRange(win, adt$3.ltr, rng);
  9536. }
  9537. };
  9538. var diagnose = function (win, selection) {
  9539. var ranges = getRanges(win, selection);
  9540. return doDiagnose(win, ranges);
  9541. };
  9542. var asLtrRange = function (win, selection) {
  9543. var diagnosis = diagnose(win, selection);
  9544. return diagnosis.match({
  9545. ltr: function (start, soffset, finish, foffset) {
  9546. var rng = win.document.createRange();
  9547. rng.setStart(start.dom, soffset);
  9548. rng.setEnd(finish.dom, foffset);
  9549. return rng;
  9550. },
  9551. rtl: function (start, soffset, finish, foffset) {
  9552. var rng = win.document.createRange();
  9553. rng.setStart(finish.dom, foffset);
  9554. rng.setEnd(start.dom, soffset);
  9555. return rng;
  9556. }
  9557. });
  9558. };
  9559. adt$3.ltr;
  9560. adt$3.rtl;
  9561. var create$3 = function (start, soffset, finish, foffset) {
  9562. return {
  9563. start: start,
  9564. soffset: soffset,
  9565. finish: finish,
  9566. foffset: foffset
  9567. };
  9568. };
  9569. var SimRange = { create: create$3 };
  9570. var NodeValue = function (is, name) {
  9571. var get = function (element) {
  9572. if (!is(element)) {
  9573. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9574. }
  9575. return getOption(element).getOr('');
  9576. };
  9577. var getOption = function (element) {
  9578. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  9579. };
  9580. var set = function (element, value) {
  9581. if (!is(element)) {
  9582. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9583. }
  9584. element.dom.nodeValue = value;
  9585. };
  9586. return {
  9587. get: get,
  9588. getOption: getOption,
  9589. set: set
  9590. };
  9591. };
  9592. var api = NodeValue(isText, 'text');
  9593. var getOption = function (element) {
  9594. return api.getOption(element);
  9595. };
  9596. var getEnd = function (element) {
  9597. return name$1(element) === 'img' ? 1 : getOption(element).fold(function () {
  9598. return children(element).length;
  9599. }, function (v) {
  9600. return v.length;
  9601. });
  9602. };
  9603. var adt$2 = Adt.generate([
  9604. { before: ['element'] },
  9605. {
  9606. on: [
  9607. 'element',
  9608. 'offset'
  9609. ]
  9610. },
  9611. { after: ['element'] }
  9612. ]);
  9613. var cata = function (subject, onBefore, onOn, onAfter) {
  9614. return subject.fold(onBefore, onOn, onAfter);
  9615. };
  9616. var getStart$1 = function (situ) {
  9617. return situ.fold(identity, identity, identity);
  9618. };
  9619. var before = adt$2.before;
  9620. var on = adt$2.on;
  9621. var after$1 = adt$2.after;
  9622. var Situ = {
  9623. before: before,
  9624. on: on,
  9625. after: after$1,
  9626. cata: cata,
  9627. getStart: getStart$1
  9628. };
  9629. var adt$1 = Adt.generate([
  9630. { domRange: ['rng'] },
  9631. {
  9632. relative: [
  9633. 'startSitu',
  9634. 'finishSitu'
  9635. ]
  9636. },
  9637. {
  9638. exact: [
  9639. 'start',
  9640. 'soffset',
  9641. 'finish',
  9642. 'foffset'
  9643. ]
  9644. }
  9645. ]);
  9646. var exactFromRange = function (simRange) {
  9647. return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9648. };
  9649. var getStart = function (selection) {
  9650. return selection.match({
  9651. domRange: function (rng) {
  9652. return SugarElement.fromDom(rng.startContainer);
  9653. },
  9654. relative: function (startSitu, _finishSitu) {
  9655. return Situ.getStart(startSitu);
  9656. },
  9657. exact: function (start, _soffset, _finish, _foffset) {
  9658. return start;
  9659. }
  9660. });
  9661. };
  9662. var domRange = adt$1.domRange;
  9663. var relative = adt$1.relative;
  9664. var exact = adt$1.exact;
  9665. var getWin$1 = function (selection) {
  9666. var start = getStart(selection);
  9667. return defaultView(start);
  9668. };
  9669. var range = SimRange.create;
  9670. var SimSelection = {
  9671. domRange: domRange,
  9672. relative: relative,
  9673. exact: exact,
  9674. exactFromRange: exactFromRange,
  9675. getWin: getWin$1,
  9676. range: range
  9677. };
  9678. var beforeSpecial = function (element, offset) {
  9679. var name = name$1(element);
  9680. if ('input' === name) {
  9681. return Situ.after(element);
  9682. } else if (!contains$1([
  9683. 'br',
  9684. 'img'
  9685. ], name)) {
  9686. return Situ.on(element, offset);
  9687. } else {
  9688. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9689. }
  9690. };
  9691. var preprocessExact = function (start, soffset, finish, foffset) {
  9692. var startSitu = beforeSpecial(start, soffset);
  9693. var finishSitu = beforeSpecial(finish, foffset);
  9694. return SimSelection.relative(startSitu, finishSitu);
  9695. };
  9696. var makeRange = function (start, soffset, finish, foffset) {
  9697. var doc = owner$2(start);
  9698. var rng = doc.dom.createRange();
  9699. rng.setStart(start.dom, soffset);
  9700. rng.setEnd(finish.dom, foffset);
  9701. return rng;
  9702. };
  9703. var after = function (start, soffset, finish, foffset) {
  9704. var r = makeRange(start, soffset, finish, foffset);
  9705. var same = eq(start, finish) && soffset === foffset;
  9706. return r.collapsed && !same;
  9707. };
  9708. var getNativeSelection = function (win) {
  9709. return Optional.from(win.getSelection());
  9710. };
  9711. var doSetNativeRange = function (win, rng) {
  9712. getNativeSelection(win).each(function (selection) {
  9713. selection.removeAllRanges();
  9714. selection.addRange(rng);
  9715. });
  9716. };
  9717. var doSetRange = function (win, start, soffset, finish, foffset) {
  9718. var rng = exactToNative(win, start, soffset, finish, foffset);
  9719. doSetNativeRange(win, rng);
  9720. };
  9721. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9722. selection.collapse(start.dom, soffset);
  9723. selection.extend(finish.dom, foffset);
  9724. };
  9725. var setRangeFromRelative = function (win, relative) {
  9726. return diagnose(win, relative).match({
  9727. ltr: function (start, soffset, finish, foffset) {
  9728. doSetRange(win, start, soffset, finish, foffset);
  9729. },
  9730. rtl: function (start, soffset, finish, foffset) {
  9731. getNativeSelection(win).each(function (selection) {
  9732. if (selection.setBaseAndExtent) {
  9733. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9734. } else if (selection.extend) {
  9735. try {
  9736. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9737. } catch (e) {
  9738. doSetRange(win, finish, foffset, start, soffset);
  9739. }
  9740. } else {
  9741. doSetRange(win, finish, foffset, start, soffset);
  9742. }
  9743. });
  9744. }
  9745. });
  9746. };
  9747. var setExact = function (win, start, soffset, finish, foffset) {
  9748. var relative = preprocessExact(start, soffset, finish, foffset);
  9749. setRangeFromRelative(win, relative);
  9750. };
  9751. var readRange = function (selection) {
  9752. if (selection.rangeCount > 0) {
  9753. var firstRng = selection.getRangeAt(0);
  9754. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9755. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9756. } else {
  9757. return Optional.none();
  9758. }
  9759. };
  9760. var doGetExact = function (selection) {
  9761. if (selection.anchorNode === null || selection.focusNode === null) {
  9762. return readRange(selection);
  9763. } else {
  9764. var anchor = SugarElement.fromDom(selection.anchorNode);
  9765. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9766. return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9767. }
  9768. };
  9769. var getExact = function (win) {
  9770. return getNativeSelection(win).filter(function (sel) {
  9771. return sel.rangeCount > 0;
  9772. }).bind(doGetExact);
  9773. };
  9774. var get = function (win) {
  9775. return getExact(win).map(function (range) {
  9776. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9777. });
  9778. };
  9779. var getFirstRect = function (win, selection) {
  9780. var rng = asLtrRange(win, selection);
  9781. return getFirstRect$1(rng);
  9782. };
  9783. var clear = function (win) {
  9784. getNativeSelection(win).each(function (selection) {
  9785. return selection.removeAllRanges();
  9786. });
  9787. };
  9788. var getBodyFromFrame = function (frame) {
  9789. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document.body));
  9790. };
  9791. var getDocFromFrame = function (frame) {
  9792. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document));
  9793. };
  9794. var getWinFromFrame = function (frame) {
  9795. return Optional.from(frame.dom.contentWindow);
  9796. };
  9797. var getSelectionFromFrame = function (frame) {
  9798. var optWin = getWinFromFrame(frame);
  9799. return optWin.bind(getExact);
  9800. };
  9801. var getFrame = function (editor) {
  9802. return editor.getFrame();
  9803. };
  9804. var getOrDerive = function (name, f) {
  9805. return function (editor) {
  9806. var g = editor[name].getOrThunk(function () {
  9807. var frame = getFrame(editor);
  9808. return function () {
  9809. return f(frame);
  9810. };
  9811. });
  9812. return g();
  9813. };
  9814. };
  9815. var getOrListen = function (editor, doc, name, type) {
  9816. return editor[name].getOrThunk(function () {
  9817. return function (handler) {
  9818. return bind(doc, type, handler);
  9819. };
  9820. });
  9821. };
  9822. var getActiveApi = function (editor) {
  9823. var frame = getFrame(editor);
  9824. var tryFallbackBox = function (win) {
  9825. var isCollapsed = function (sel) {
  9826. return eq(sel.start, sel.finish) && sel.soffset === sel.foffset;
  9827. };
  9828. var toStartRect = function (sel) {
  9829. var rect = sel.start.dom.getBoundingClientRect();
  9830. return rect.width > 0 || rect.height > 0 ? Optional.some(rect) : Optional.none();
  9831. };
  9832. return getExact(win).filter(isCollapsed).bind(toStartRect);
  9833. };
  9834. return getBodyFromFrame(frame).bind(function (body) {
  9835. return getDocFromFrame(frame).bind(function (doc) {
  9836. return getWinFromFrame(frame).map(function (win) {
  9837. var html = SugarElement.fromDom(doc.dom.documentElement);
  9838. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  9839. return function () {
  9840. return get(win).bind(function (sel) {
  9841. return getFirstRect(win, sel).orThunk(function () {
  9842. return tryFallbackBox(win);
  9843. });
  9844. });
  9845. };
  9846. });
  9847. var setSelection = editor.setSelection.getOrThunk(function () {
  9848. return function (start, soffset, finish, foffset) {
  9849. setExact(win, start, soffset, finish, foffset);
  9850. };
  9851. });
  9852. var clearSelection = editor.clearSelection.getOrThunk(function () {
  9853. return function () {
  9854. clear(win);
  9855. };
  9856. });
  9857. return {
  9858. body: body,
  9859. doc: doc,
  9860. win: win,
  9861. html: html,
  9862. getSelection: curry(getSelectionFromFrame, frame),
  9863. setSelection: setSelection,
  9864. clearSelection: clearSelection,
  9865. frame: frame,
  9866. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  9867. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  9868. onDomChanged: editor.onDomChanged,
  9869. onScrollToCursor: editor.onScrollToCursor,
  9870. onScrollToElement: editor.onScrollToElement,
  9871. onToReading: editor.onToReading,
  9872. onToEditing: editor.onToEditing,
  9873. onToolbarScrollStart: editor.onToolbarScrollStart,
  9874. onTouchContent: editor.onTouchContent,
  9875. onTapContent: editor.onTapContent,
  9876. onTouchToolstrip: editor.onTouchToolstrip,
  9877. getCursorBox: getCursorBox
  9878. };
  9879. });
  9880. });
  9881. });
  9882. };
  9883. var getWin = getOrDerive('getWin', getWinFromFrame);
  9884. var tag = function () {
  9885. var head = first$1('head').getOrDie();
  9886. var nu = function () {
  9887. var meta = SugarElement.fromTag('meta');
  9888. set$8(meta, 'name', 'viewport');
  9889. append$2(head, meta);
  9890. return meta;
  9891. };
  9892. var element = first$1('meta[name="viewport"]').getOrThunk(nu);
  9893. var backup = get$b(element, 'content');
  9894. var maximize = function () {
  9895. set$8(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  9896. };
  9897. var restore = function () {
  9898. if (backup !== undefined && backup !== null && backup.length > 0) {
  9899. set$8(element, 'content', backup);
  9900. } else {
  9901. set$8(element, 'content', 'user-scalable=yes');
  9902. }
  9903. };
  9904. return {
  9905. maximize: maximize,
  9906. restore: restore
  9907. };
  9908. };
  9909. var attr = 'data-ephox-mobile-fullscreen-style';
  9910. var siblingStyles = 'display:none!important;';
  9911. var ancestorPosition = 'position:absolute!important;';
  9912. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  9913. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  9914. var isAndroid = detect$1().os.isAndroid();
  9915. var matchColor = function (editorBody) {
  9916. var color = get$8(editorBody, 'background-color');
  9917. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  9918. };
  9919. var clobberStyles = function (container, editorBody) {
  9920. var gatherSiblings = function (element) {
  9921. return siblings(element, '*');
  9922. };
  9923. var clobber = function (clobberStyle) {
  9924. return function (element) {
  9925. var styles = get$b(element, 'style');
  9926. var backup = styles === undefined ? 'no-styles' : styles.trim();
  9927. if (backup === clobberStyle) {
  9928. return;
  9929. } else {
  9930. set$8(element, attr, backup);
  9931. set$8(element, 'style', clobberStyle);
  9932. }
  9933. };
  9934. };
  9935. var ancestors$1 = ancestors(container, '*');
  9936. var siblings$1 = bind$3(ancestors$1, gatherSiblings);
  9937. var bgColor = matchColor(editorBody);
  9938. each$1(siblings$1, clobber(siblingStyles));
  9939. each$1(ancestors$1, clobber(ancestorPosition + ancestorStyles + bgColor));
  9940. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  9941. clobber(containerStyles + ancestorStyles + bgColor)(container);
  9942. };
  9943. var restoreStyles = function () {
  9944. var clobberedEls = all('[' + attr + ']');
  9945. each$1(clobberedEls, function (element) {
  9946. var restore = get$b(element, attr);
  9947. if (restore !== 'no-styles') {
  9948. set$8(element, 'style', restore);
  9949. } else {
  9950. remove$6(element, 'style');
  9951. }
  9952. remove$6(element, attr);
  9953. });
  9954. };
  9955. var DelayedFunction = function (fun, delay) {
  9956. var ref = null;
  9957. var schedule = function () {
  9958. var args = [];
  9959. for (var _i = 0; _i < arguments.length; _i++) {
  9960. args[_i] = arguments[_i];
  9961. }
  9962. ref = setTimeout(function () {
  9963. fun.apply(null, args);
  9964. ref = null;
  9965. }, delay);
  9966. };
  9967. var cancel = function () {
  9968. if (ref !== null) {
  9969. clearTimeout(ref);
  9970. ref = null;
  9971. }
  9972. };
  9973. return {
  9974. cancel: cancel,
  9975. schedule: schedule
  9976. };
  9977. };
  9978. var SIGNIFICANT_MOVE = 5;
  9979. var LONGPRESS_DELAY = 400;
  9980. var getTouch = function (event) {
  9981. var raw = event.raw;
  9982. if (raw.touches === undefined || raw.touches.length !== 1) {
  9983. return Optional.none();
  9984. }
  9985. return Optional.some(raw.touches[0]);
  9986. };
  9987. var isFarEnough = function (touch, data) {
  9988. var distX = Math.abs(touch.clientX - data.x);
  9989. var distY = Math.abs(touch.clientY - data.y);
  9990. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  9991. };
  9992. var monitor$1 = function (settings) {
  9993. var startData = value();
  9994. var longpressFired = Cell(false);
  9995. var longpress$1 = DelayedFunction(function (event) {
  9996. settings.triggerEvent(longpress(), event);
  9997. longpressFired.set(true);
  9998. }, LONGPRESS_DELAY);
  9999. var handleTouchstart = function (event) {
  10000. getTouch(event).each(function (touch) {
  10001. longpress$1.cancel();
  10002. var data = {
  10003. x: touch.clientX,
  10004. y: touch.clientY,
  10005. target: event.target
  10006. };
  10007. longpress$1.schedule(event);
  10008. longpressFired.set(false);
  10009. startData.set(data);
  10010. });
  10011. return Optional.none();
  10012. };
  10013. var handleTouchmove = function (event) {
  10014. longpress$1.cancel();
  10015. getTouch(event).each(function (touch) {
  10016. startData.on(function (data) {
  10017. if (isFarEnough(touch, data)) {
  10018. startData.clear();
  10019. }
  10020. });
  10021. });
  10022. return Optional.none();
  10023. };
  10024. var handleTouchend = function (event) {
  10025. longpress$1.cancel();
  10026. var isSame = function (data) {
  10027. return eq(data.target, event.target);
  10028. };
  10029. return startData.get().filter(isSame).map(function (_data) {
  10030. if (longpressFired.get()) {
  10031. event.prevent();
  10032. return false;
  10033. } else {
  10034. return settings.triggerEvent(tap(), event);
  10035. }
  10036. });
  10037. };
  10038. var handlers = wrapAll([
  10039. {
  10040. key: touchstart(),
  10041. value: handleTouchstart
  10042. },
  10043. {
  10044. key: touchmove(),
  10045. value: handleTouchmove
  10046. },
  10047. {
  10048. key: touchend(),
  10049. value: handleTouchend
  10050. }
  10051. ]);
  10052. var fireIfReady = function (event, type) {
  10053. return get$c(handlers, type).bind(function (handler) {
  10054. return handler(event);
  10055. });
  10056. };
  10057. return { fireIfReady: fireIfReady };
  10058. };
  10059. var monitor = function (editorApi) {
  10060. var tapEvent = monitor$1({
  10061. triggerEvent: function (type, evt) {
  10062. editorApi.onTapContent(evt);
  10063. }
  10064. });
  10065. var onTouchend = function () {
  10066. return bind(editorApi.body, 'touchend', function (evt) {
  10067. tapEvent.fireIfReady(evt, 'touchend');
  10068. });
  10069. };
  10070. var onTouchmove = function () {
  10071. return bind(editorApi.body, 'touchmove', function (evt) {
  10072. tapEvent.fireIfReady(evt, 'touchmove');
  10073. });
  10074. };
  10075. var fireTouchstart = function (evt) {
  10076. tapEvent.fireIfReady(evt, 'touchstart');
  10077. };
  10078. return {
  10079. fireTouchstart: fireTouchstart,
  10080. onTouchend: onTouchend,
  10081. onTouchmove: onTouchmove
  10082. };
  10083. };
  10084. var isAndroid6 = detect$1().os.version.major >= 6;
  10085. var initEvents$1 = function (editorApi, toolstrip, alloy) {
  10086. var tapping = monitor(editorApi);
  10087. var outerDoc = owner$2(toolstrip);
  10088. var isRanged = function (sel) {
  10089. return !eq(sel.start, sel.finish) || sel.soffset !== sel.foffset;
  10090. };
  10091. var hasRangeInUi = function () {
  10092. return active(outerDoc).filter(function (input) {
  10093. return name$1(input) === 'input';
  10094. }).exists(function (input) {
  10095. return input.dom.selectionStart !== input.dom.selectionEnd;
  10096. });
  10097. };
  10098. var updateMargin = function () {
  10099. var rangeInContent = editorApi.doc.dom.hasFocus() && editorApi.getSelection().exists(isRanged);
  10100. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  10101. };
  10102. var listeners = [
  10103. bind(editorApi.body, 'touchstart', function (evt) {
  10104. editorApi.onTouchContent();
  10105. tapping.fireTouchstart(evt);
  10106. }),
  10107. tapping.onTouchmove(),
  10108. tapping.onTouchend(),
  10109. bind(toolstrip, 'touchstart', function (_evt) {
  10110. editorApi.onTouchToolstrip();
  10111. }),
  10112. editorApi.onToReading(function () {
  10113. blur$1(editorApi.body);
  10114. }),
  10115. editorApi.onToEditing(noop),
  10116. editorApi.onScrollToCursor(function (tinyEvent) {
  10117. tinyEvent.preventDefault();
  10118. editorApi.getCursorBox().each(function (bounds) {
  10119. var cWin = editorApi.win;
  10120. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10121. var cScrollBy = isOutside ? bounds.bottom - cWin.innerHeight + 50 : 0;
  10122. if (cScrollBy !== 0) {
  10123. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10124. }
  10125. });
  10126. })
  10127. ].concat(isAndroid6 === true ? [] : [
  10128. bind(SugarElement.fromDom(editorApi.win), 'blur', function () {
  10129. alloy.getByDom(toolstrip).each(Toggling.off);
  10130. }),
  10131. bind(outerDoc, 'select', updateMargin),
  10132. bind(editorApi.doc, 'selectionchange', updateMargin)
  10133. ]);
  10134. var destroy = function () {
  10135. each$1(listeners, function (l) {
  10136. l.unbind();
  10137. });
  10138. };
  10139. return { destroy: destroy };
  10140. };
  10141. var safeParse = function (element, attribute) {
  10142. var parsed = parseInt(get$b(element, attribute), 10);
  10143. return isNaN(parsed) ? 0 : parsed;
  10144. };
  10145. var COLLAPSED_WIDTH = 2;
  10146. var collapsedRect = function (rect) {
  10147. return __assign(__assign({}, rect), { width: COLLAPSED_WIDTH });
  10148. };
  10149. var toRect = function (rawRect) {
  10150. return {
  10151. left: rawRect.left,
  10152. top: rawRect.top,
  10153. right: rawRect.right,
  10154. bottom: rawRect.bottom,
  10155. width: rawRect.width,
  10156. height: rawRect.height
  10157. };
  10158. };
  10159. var getRectsFromRange = function (range) {
  10160. if (!range.collapsed) {
  10161. return map$2(range.getClientRects(), toRect);
  10162. } else {
  10163. var start_1 = SugarElement.fromDom(range.startContainer);
  10164. return parent(start_1).bind(function (parent) {
  10165. var selection = SimSelection.exact(start_1, range.startOffset, parent, getEnd(parent));
  10166. var optRect = getFirstRect(range.startContainer.ownerDocument.defaultView, selection);
  10167. return optRect.map(collapsedRect).map(pure$2);
  10168. }).getOr([]);
  10169. }
  10170. };
  10171. var getRectangles = function (cWin) {
  10172. var sel = cWin.getSelection();
  10173. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  10174. };
  10175. var autocompleteHack = function () {
  10176. return function (f) {
  10177. global$2.setTimeout(function () {
  10178. f();
  10179. }, 0);
  10180. };
  10181. };
  10182. var resume$1 = function (cWin) {
  10183. cWin.focus();
  10184. var iBody = SugarElement.fromDom(cWin.document.body);
  10185. var inInput = active().exists(function (elem) {
  10186. return contains$1([
  10187. 'input',
  10188. 'textarea'
  10189. ], name$1(elem));
  10190. });
  10191. var transaction = inInput ? autocompleteHack() : apply$1;
  10192. transaction(function () {
  10193. active().each(blur$1);
  10194. focus$3(iBody);
  10195. });
  10196. };
  10197. var EXTRA_SPACING = 50;
  10198. var data = 'data-' + resolve('last-outer-height');
  10199. var setLastHeight = function (cBody, value) {
  10200. set$8(cBody, data, value);
  10201. };
  10202. var getLastHeight = function (cBody) {
  10203. return safeParse(cBody, data);
  10204. };
  10205. var getBoundsFrom = function (rect) {
  10206. return {
  10207. top: rect.top,
  10208. bottom: rect.top + rect.height
  10209. };
  10210. };
  10211. var getBounds = function (cWin) {
  10212. var rects = getRectangles(cWin);
  10213. return rects.length > 0 ? Optional.some(rects[0]).map(getBoundsFrom) : Optional.none();
  10214. };
  10215. var findDelta = function (outerWindow, cBody) {
  10216. var last = getLastHeight(cBody);
  10217. var current = outerWindow.innerHeight;
  10218. return last > current ? Optional.some(last - current) : Optional.none();
  10219. };
  10220. var calculate = function (cWin, bounds, delta) {
  10221. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10222. return isOutside ? Math.min(delta, bounds.bottom - cWin.innerHeight + EXTRA_SPACING) : 0;
  10223. };
  10224. var setup$2 = function (outerWindow, cWin) {
  10225. var cBody = SugarElement.fromDom(cWin.document.body);
  10226. var toEditing = function () {
  10227. resume$1(cWin);
  10228. };
  10229. var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () {
  10230. findDelta(outerWindow, cBody).each(function (delta) {
  10231. getBounds(cWin).each(function (bounds) {
  10232. var cScrollBy = calculate(cWin, bounds, delta);
  10233. if (cScrollBy !== 0) {
  10234. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10235. }
  10236. });
  10237. });
  10238. setLastHeight(cBody, outerWindow.innerHeight);
  10239. });
  10240. setLastHeight(cBody, outerWindow.innerHeight);
  10241. var destroy = function () {
  10242. onResize.unbind();
  10243. };
  10244. return {
  10245. toEditing: toEditing,
  10246. destroy: destroy
  10247. };
  10248. };
  10249. var create$2 = function (platform, mask) {
  10250. var meta = tag();
  10251. var androidApi = api$2();
  10252. var androidEvents = api$2();
  10253. var enter = function () {
  10254. mask.hide();
  10255. add$1(platform.container, resolve('fullscreen-maximized'));
  10256. add$1(platform.container, resolve('android-maximized'));
  10257. meta.maximize();
  10258. add$1(platform.body, resolve('android-scroll-reload'));
  10259. androidApi.set(setup$2(platform.win, getWin(platform.editor).getOrDie('no')));
  10260. getActiveApi(platform.editor).each(function (editorApi) {
  10261. clobberStyles(platform.container, editorApi.body);
  10262. androidEvents.set(initEvents$1(editorApi, platform.toolstrip, platform.alloy));
  10263. });
  10264. };
  10265. var exit = function () {
  10266. meta.restore();
  10267. mask.show();
  10268. remove$3(platform.container, resolve('fullscreen-maximized'));
  10269. remove$3(platform.container, resolve('android-maximized'));
  10270. restoreStyles();
  10271. remove$3(platform.body, resolve('android-scroll-reload'));
  10272. androidEvents.clear();
  10273. androidApi.clear();
  10274. };
  10275. return {
  10276. enter: enter,
  10277. exit: exit
  10278. };
  10279. };
  10280. var first = function (fn, rate) {
  10281. var timer = null;
  10282. var cancel = function () {
  10283. if (!isNull(timer)) {
  10284. clearTimeout(timer);
  10285. timer = null;
  10286. }
  10287. };
  10288. var throttle = function () {
  10289. var args = [];
  10290. for (var _i = 0; _i < arguments.length; _i++) {
  10291. args[_i] = arguments[_i];
  10292. }
  10293. if (isNull(timer)) {
  10294. timer = setTimeout(function () {
  10295. timer = null;
  10296. fn.apply(null, args);
  10297. }, rate);
  10298. }
  10299. };
  10300. return {
  10301. cancel: cancel,
  10302. throttle: throttle
  10303. };
  10304. };
  10305. var last = function (fn, rate) {
  10306. var timer = null;
  10307. var cancel = function () {
  10308. if (!isNull(timer)) {
  10309. clearTimeout(timer);
  10310. timer = null;
  10311. }
  10312. };
  10313. var throttle = function () {
  10314. var args = [];
  10315. for (var _i = 0; _i < arguments.length; _i++) {
  10316. args[_i] = arguments[_i];
  10317. }
  10318. cancel();
  10319. timer = setTimeout(function () {
  10320. timer = null;
  10321. fn.apply(null, args);
  10322. }, rate);
  10323. };
  10324. return {
  10325. cancel: cancel,
  10326. throttle: throttle
  10327. };
  10328. };
  10329. var sketch = function (onView, _translate) {
  10330. var memIcon = record(Container.sketch({
  10331. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10332. containerBehaviours: derive$2([Toggling.config({
  10333. toggleClass: resolve('mask-tap-icon-selected'),
  10334. toggleOnExecute: false
  10335. })])
  10336. }));
  10337. var onViewThrottle = first(onView, 200);
  10338. return Container.sketch({
  10339. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10340. components: [Container.sketch({
  10341. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10342. components: [Button.sketch({
  10343. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10344. components: [memIcon.asSpec()],
  10345. action: function (_button) {
  10346. onViewThrottle.throttle();
  10347. },
  10348. buttonBehaviours: derive$2([Toggling.config({ toggleClass: resolve('mask-tap-icon-selected') })])
  10349. })]
  10350. })]
  10351. });
  10352. };
  10353. var unbindNoop = constant$1({ unbind: noop });
  10354. var MobileSchema = objOf([
  10355. requiredObjOf('editor', [
  10356. required$1('getFrame'),
  10357. option('getBody'),
  10358. option('getDoc'),
  10359. option('getWin'),
  10360. option('getSelection'),
  10361. option('setSelection'),
  10362. option('clearSelection'),
  10363. option('cursorSaver'),
  10364. option('onKeyup'),
  10365. option('onNodeChanged'),
  10366. option('getCursorBox'),
  10367. required$1('onDomChanged'),
  10368. defaulted('onTouchContent', noop),
  10369. defaulted('onTapContent', noop),
  10370. defaulted('onTouchToolstrip', noop),
  10371. defaulted('onScrollToCursor', unbindNoop),
  10372. defaulted('onScrollToElement', unbindNoop),
  10373. defaulted('onToEditing', unbindNoop),
  10374. defaulted('onToReading', unbindNoop),
  10375. defaulted('onToolbarScrollStart', identity)
  10376. ]),
  10377. required$1('socket'),
  10378. required$1('toolstrip'),
  10379. required$1('dropup'),
  10380. required$1('toolbar'),
  10381. required$1('container'),
  10382. required$1('alloy'),
  10383. customField('win', function (spec) {
  10384. return owner$2(spec.socket).dom.defaultView;
  10385. }),
  10386. customField('body', function (spec) {
  10387. return SugarElement.fromDom(spec.socket.dom.ownerDocument.body);
  10388. }),
  10389. defaulted('translate', identity),
  10390. defaulted('setReadOnly', noop),
  10391. defaulted('readOnlyOnInit', always)
  10392. ]);
  10393. var produce$1 = function (raw) {
  10394. var mobile = asRawOrDie$1('Getting AndroidWebapp schema', MobileSchema, raw);
  10395. set$5(mobile.toolstrip, 'width', '100%');
  10396. var onTap = function () {
  10397. mobile.setReadOnly(mobile.readOnlyOnInit());
  10398. mode.enter();
  10399. };
  10400. var mask = build$1(sketch(onTap, mobile.translate));
  10401. mobile.alloy.add(mask);
  10402. var maskApi = {
  10403. show: function () {
  10404. mobile.alloy.add(mask);
  10405. },
  10406. hide: function () {
  10407. mobile.alloy.remove(mask);
  10408. }
  10409. };
  10410. append$2(mobile.container, mask.element);
  10411. var mode = create$2(mobile, maskApi);
  10412. return {
  10413. setReadOnly: mobile.setReadOnly,
  10414. refreshStructure: noop,
  10415. enter: mode.enter,
  10416. exit: mode.exit,
  10417. destroy: noop
  10418. };
  10419. };
  10420. var schema$1 = constant$1([
  10421. required$1('dom'),
  10422. defaulted('shell', true),
  10423. field$1('toolbarBehaviours', [Replacing])
  10424. ]);
  10425. var enhanceGroups = function () {
  10426. return { behaviours: derive$2([Replacing.config({})]) };
  10427. };
  10428. var parts$1 = constant$1([optional({
  10429. name: 'groups',
  10430. overrides: enhanceGroups
  10431. })]);
  10432. var factory$1 = function (detail, components, _spec, _externals) {
  10433. var setGroups = function (toolbar, groups) {
  10434. getGroupContainer(toolbar).fold(function () {
  10435. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10436. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10437. }, function (container) {
  10438. Replacing.set(container, groups);
  10439. });
  10440. };
  10441. var getGroupContainer = function (component) {
  10442. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  10443. };
  10444. var extra = detail.shell ? {
  10445. behaviours: [Replacing.config({})],
  10446. components: []
  10447. } : {
  10448. behaviours: [],
  10449. components: components
  10450. };
  10451. return {
  10452. uid: detail.uid,
  10453. dom: detail.dom,
  10454. components: extra.components,
  10455. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10456. apis: { setGroups: setGroups },
  10457. domModification: { attributes: { role: 'group' } }
  10458. };
  10459. };
  10460. var Toolbar = composite({
  10461. name: 'Toolbar',
  10462. configFields: schema$1(),
  10463. partFields: parts$1(),
  10464. factory: factory$1,
  10465. apis: {
  10466. setGroups: function (apis, toolbar, groups) {
  10467. apis.setGroups(toolbar, groups);
  10468. }
  10469. }
  10470. });
  10471. var schema = constant$1([
  10472. required$1('items'),
  10473. markers(['itemSelector']),
  10474. field$1('tgroupBehaviours', [Keying])
  10475. ]);
  10476. var parts = constant$1([group({
  10477. name: 'items',
  10478. unit: 'item'
  10479. })]);
  10480. var factory = function (detail, components, _spec, _externals) {
  10481. return {
  10482. uid: detail.uid,
  10483. dom: detail.dom,
  10484. components: components,
  10485. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10486. mode: 'flow',
  10487. selector: detail.markers.itemSelector
  10488. })]),
  10489. domModification: { attributes: { role: 'toolbar' } }
  10490. };
  10491. };
  10492. var ToolbarGroup = composite({
  10493. name: 'ToolbarGroup',
  10494. configFields: schema(),
  10495. partFields: parts(),
  10496. factory: factory
  10497. });
  10498. var dataHorizontal = 'data-' + resolve('horizontal-scroll');
  10499. var canScrollVertically = function (container) {
  10500. container.dom.scrollTop = 1;
  10501. var result = container.dom.scrollTop !== 0;
  10502. container.dom.scrollTop = 0;
  10503. return result;
  10504. };
  10505. var canScrollHorizontally = function (container) {
  10506. container.dom.scrollLeft = 1;
  10507. var result = container.dom.scrollLeft !== 0;
  10508. container.dom.scrollLeft = 0;
  10509. return result;
  10510. };
  10511. var hasVerticalScroll = function (container) {
  10512. return container.dom.scrollTop > 0 || canScrollVertically(container);
  10513. };
  10514. var hasHorizontalScroll = function (container) {
  10515. return container.dom.scrollLeft > 0 || canScrollHorizontally(container);
  10516. };
  10517. var markAsHorizontal = function (container) {
  10518. set$8(container, dataHorizontal, 'true');
  10519. };
  10520. var hasScroll = function (container) {
  10521. return get$b(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10522. };
  10523. var exclusive = function (scope, selector) {
  10524. return bind(scope, 'touchmove', function (event) {
  10525. closest$1(event.target, selector).filter(hasScroll).fold(function () {
  10526. event.prevent();
  10527. }, noop);
  10528. });
  10529. };
  10530. var ScrollingToolbar = function () {
  10531. var makeGroup = function (gSpec) {
  10532. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10533. return {
  10534. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10535. tgroupBehaviours: derive$2([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, _simulatedEvent) {
  10536. set$5(component.element, 'overflow-x', 'auto');
  10537. markAsHorizontal(component.element);
  10538. register$2(component.element);
  10539. })] : [])]),
  10540. components: [Container.sketch({ components: [ToolbarGroup.parts.items({})] })],
  10541. markers: { itemSelector: '.' + resolve('toolbar-group-item') },
  10542. items: gSpec.items
  10543. };
  10544. };
  10545. var toolbar = build$1(Toolbar.sketch({
  10546. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10547. components: [Toolbar.parts.groups({})],
  10548. toolbarBehaviours: derive$2([
  10549. Toggling.config({
  10550. toggleClass: resolve('context-toolbar'),
  10551. toggleOnExecute: false,
  10552. aria: { mode: 'none' }
  10553. }),
  10554. Keying.config({ mode: 'cyclic' })
  10555. ]),
  10556. shell: true
  10557. }));
  10558. var wrapper = build$1(Container.sketch({
  10559. dom: { classes: [resolve('toolstrip')] },
  10560. components: [premade(toolbar)],
  10561. containerBehaviours: derive$2([Toggling.config({
  10562. toggleClass: resolve('android-selection-context-toolbar'),
  10563. toggleOnExecute: false
  10564. })])
  10565. }));
  10566. var resetGroups = function () {
  10567. Toolbar.setGroups(toolbar, initGroups.get());
  10568. Toggling.off(toolbar);
  10569. };
  10570. var initGroups = Cell([]);
  10571. var setGroups = function (gs) {
  10572. initGroups.set(gs);
  10573. resetGroups();
  10574. };
  10575. var createGroups = function (gs) {
  10576. return map$2(gs, compose(ToolbarGroup.sketch, makeGroup));
  10577. };
  10578. var refresh = function () {
  10579. };
  10580. var setContextToolbar = function (gs) {
  10581. Toggling.on(toolbar);
  10582. Toolbar.setGroups(toolbar, gs);
  10583. };
  10584. var restoreToolbar = function () {
  10585. if (Toggling.isOn(toolbar)) {
  10586. resetGroups();
  10587. }
  10588. };
  10589. var focus = function () {
  10590. Keying.focusIn(toolbar);
  10591. };
  10592. return {
  10593. wrapper: wrapper,
  10594. toolbar: toolbar,
  10595. createGroups: createGroups,
  10596. setGroups: setGroups,
  10597. setContextToolbar: setContextToolbar,
  10598. restoreToolbar: restoreToolbar,
  10599. refresh: refresh,
  10600. focus: focus
  10601. };
  10602. };
  10603. var makeEditSwitch = function (webapp) {
  10604. return build$1(Button.sketch({
  10605. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10606. action: function () {
  10607. webapp.run(function (w) {
  10608. w.setReadOnly(false);
  10609. });
  10610. }
  10611. }));
  10612. };
  10613. var makeSocket = function () {
  10614. return build$1(Container.sketch({
  10615. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10616. components: [],
  10617. containerBehaviours: derive$2([Replacing.config({})])
  10618. }));
  10619. };
  10620. var showEdit = function (socket, switchToEdit) {
  10621. Replacing.append(socket, premade(switchToEdit));
  10622. };
  10623. var hideEdit = function (socket, switchToEdit) {
  10624. Replacing.remove(socket, switchToEdit);
  10625. };
  10626. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10627. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10628. swap(root);
  10629. var f = readOnly ? showEdit : hideEdit;
  10630. f(socket, switchToEdit);
  10631. };
  10632. var getAnimationRoot = function (component, slideConfig) {
  10633. return slideConfig.getAnimationRoot.fold(function () {
  10634. return component.element;
  10635. }, function (get) {
  10636. return get(component);
  10637. });
  10638. };
  10639. var getDimensionProperty = function (slideConfig) {
  10640. return slideConfig.dimension.property;
  10641. };
  10642. var getDimension = function (slideConfig, elem) {
  10643. return slideConfig.dimension.getDimension(elem);
  10644. };
  10645. var disableTransitions = function (component, slideConfig) {
  10646. var root = getAnimationRoot(component, slideConfig);
  10647. remove$1(root, [
  10648. slideConfig.shrinkingClass,
  10649. slideConfig.growingClass
  10650. ]);
  10651. };
  10652. var setShrunk = function (component, slideConfig) {
  10653. remove$3(component.element, slideConfig.openClass);
  10654. add$1(component.element, slideConfig.closedClass);
  10655. set$5(component.element, getDimensionProperty(slideConfig), '0px');
  10656. reflow(component.element);
  10657. };
  10658. var setGrown = function (component, slideConfig) {
  10659. remove$3(component.element, slideConfig.closedClass);
  10660. add$1(component.element, slideConfig.openClass);
  10661. remove$2(component.element, getDimensionProperty(slideConfig));
  10662. };
  10663. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10664. slideState.setCollapsed();
  10665. set$5(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  10666. reflow(component.element);
  10667. disableTransitions(component, slideConfig);
  10668. setShrunk(component, slideConfig);
  10669. slideConfig.onStartShrink(component);
  10670. slideConfig.onShrunk(component);
  10671. };
  10672. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10673. var size = calculatedSize.getOrThunk(function () {
  10674. return getDimension(slideConfig, component.element);
  10675. });
  10676. slideState.setCollapsed();
  10677. set$5(component.element, getDimensionProperty(slideConfig), size);
  10678. reflow(component.element);
  10679. var root = getAnimationRoot(component, slideConfig);
  10680. remove$3(root, slideConfig.growingClass);
  10681. add$1(root, slideConfig.shrinkingClass);
  10682. setShrunk(component, slideConfig);
  10683. slideConfig.onStartShrink(component);
  10684. };
  10685. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10686. var size = getDimension(slideConfig, component.element);
  10687. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10688. shrinker(component, slideConfig, slideState, Optional.some(size));
  10689. };
  10690. var doStartGrow = function (component, slideConfig, slideState) {
  10691. var root = getAnimationRoot(component, slideConfig);
  10692. var wasShrinking = has(root, slideConfig.shrinkingClass);
  10693. var beforeSize = getDimension(slideConfig, component.element);
  10694. setGrown(component, slideConfig);
  10695. var fullSize = getDimension(slideConfig, component.element);
  10696. var startPartialGrow = function () {
  10697. set$5(component.element, getDimensionProperty(slideConfig), beforeSize);
  10698. reflow(component.element);
  10699. };
  10700. var startCompleteGrow = function () {
  10701. setShrunk(component, slideConfig);
  10702. };
  10703. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  10704. setStartSize();
  10705. remove$3(root, slideConfig.shrinkingClass);
  10706. add$1(root, slideConfig.growingClass);
  10707. setGrown(component, slideConfig);
  10708. set$5(component.element, getDimensionProperty(slideConfig), fullSize);
  10709. slideState.setExpanded();
  10710. slideConfig.onStartGrow(component);
  10711. };
  10712. var refresh$1 = function (component, slideConfig, slideState) {
  10713. if (slideState.isExpanded()) {
  10714. remove$2(component.element, getDimensionProperty(slideConfig));
  10715. var fullSize = getDimension(slideConfig, component.element);
  10716. set$5(component.element, getDimensionProperty(slideConfig), fullSize);
  10717. }
  10718. };
  10719. var grow = function (component, slideConfig, slideState) {
  10720. if (!slideState.isExpanded()) {
  10721. doStartGrow(component, slideConfig, slideState);
  10722. }
  10723. };
  10724. var shrink = function (component, slideConfig, slideState) {
  10725. if (slideState.isExpanded()) {
  10726. doStartSmartShrink(component, slideConfig, slideState);
  10727. }
  10728. };
  10729. var immediateShrink = function (component, slideConfig, slideState) {
  10730. if (slideState.isExpanded()) {
  10731. doImmediateShrink(component, slideConfig, slideState);
  10732. }
  10733. };
  10734. var hasGrown = function (component, slideConfig, slideState) {
  10735. return slideState.isExpanded();
  10736. };
  10737. var hasShrunk = function (component, slideConfig, slideState) {
  10738. return slideState.isCollapsed();
  10739. };
  10740. var isGrowing = function (component, slideConfig, _slideState) {
  10741. var root = getAnimationRoot(component, slideConfig);
  10742. return has(root, slideConfig.growingClass) === true;
  10743. };
  10744. var isShrinking = function (component, slideConfig, _slideState) {
  10745. var root = getAnimationRoot(component, slideConfig);
  10746. return has(root, slideConfig.shrinkingClass) === true;
  10747. };
  10748. var isTransitioning = function (component, slideConfig, slideState) {
  10749. return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  10750. };
  10751. var toggleGrow = function (component, slideConfig, slideState) {
  10752. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  10753. f(component, slideConfig, slideState);
  10754. };
  10755. var SlidingApis = /*#__PURE__*/Object.freeze({
  10756. __proto__: null,
  10757. refresh: refresh$1,
  10758. grow: grow,
  10759. shrink: shrink,
  10760. immediateShrink: immediateShrink,
  10761. hasGrown: hasGrown,
  10762. hasShrunk: hasShrunk,
  10763. isGrowing: isGrowing,
  10764. isShrinking: isShrinking,
  10765. isTransitioning: isTransitioning,
  10766. toggleGrow: toggleGrow,
  10767. disableTransitions: disableTransitions
  10768. });
  10769. var exhibit = function (base, slideConfig, _slideState) {
  10770. var expanded = slideConfig.expanded;
  10771. return expanded ? nu$3({
  10772. classes: [slideConfig.openClass],
  10773. styles: {}
  10774. }) : nu$3({
  10775. classes: [slideConfig.closedClass],
  10776. styles: wrap(slideConfig.dimension.property, '0px')
  10777. });
  10778. };
  10779. var events = function (slideConfig, slideState) {
  10780. return derive$3([runOnSource(transitionend(), function (component, simulatedEvent) {
  10781. var raw = simulatedEvent.event.raw;
  10782. if (raw.propertyName === slideConfig.dimension.property) {
  10783. disableTransitions(component, slideConfig);
  10784. if (slideState.isExpanded()) {
  10785. remove$2(component.element, slideConfig.dimension.property);
  10786. }
  10787. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  10788. notify(component);
  10789. }
  10790. })]);
  10791. };
  10792. var ActiveSliding = /*#__PURE__*/Object.freeze({
  10793. __proto__: null,
  10794. exhibit: exhibit,
  10795. events: events
  10796. });
  10797. var SlidingSchema = [
  10798. required$1('closedClass'),
  10799. required$1('openClass'),
  10800. required$1('shrinkingClass'),
  10801. required$1('growingClass'),
  10802. option('getAnimationRoot'),
  10803. onHandler('onShrunk'),
  10804. onHandler('onStartShrink'),
  10805. onHandler('onGrown'),
  10806. onHandler('onStartGrow'),
  10807. defaulted('expanded', false),
  10808. requiredOf('dimension', choose$1('property', {
  10809. width: [
  10810. output('property', 'width'),
  10811. output('getDimension', function (elem) {
  10812. return get$5(elem) + 'px';
  10813. })
  10814. ],
  10815. height: [
  10816. output('property', 'height'),
  10817. output('getDimension', function (elem) {
  10818. return get$7(elem) + 'px';
  10819. })
  10820. ]
  10821. }))
  10822. ];
  10823. var init$1 = function (spec) {
  10824. var state = Cell(spec.expanded);
  10825. var readState = function () {
  10826. return 'expanded: ' + state.get();
  10827. };
  10828. return nu$2({
  10829. isExpanded: function () {
  10830. return state.get() === true;
  10831. },
  10832. isCollapsed: function () {
  10833. return state.get() === false;
  10834. },
  10835. setCollapsed: curry(state.set, false),
  10836. setExpanded: curry(state.set, true),
  10837. readState: readState
  10838. });
  10839. };
  10840. var SlidingState = /*#__PURE__*/Object.freeze({
  10841. __proto__: null,
  10842. init: init$1
  10843. });
  10844. var Sliding = create$5({
  10845. fields: SlidingSchema,
  10846. name: 'sliding',
  10847. active: ActiveSliding,
  10848. apis: SlidingApis,
  10849. state: SlidingState
  10850. });
  10851. var build = function (refresh, scrollIntoView) {
  10852. var dropup = build$1(Container.sketch({
  10853. dom: {
  10854. tag: 'div',
  10855. classes: [resolve('dropup')]
  10856. },
  10857. components: [],
  10858. containerBehaviours: derive$2([
  10859. Replacing.config({}),
  10860. Sliding.config({
  10861. closedClass: resolve('dropup-closed'),
  10862. openClass: resolve('dropup-open'),
  10863. shrinkingClass: resolve('dropup-shrinking'),
  10864. growingClass: resolve('dropup-growing'),
  10865. dimension: { property: 'height' },
  10866. onShrunk: function (component) {
  10867. refresh();
  10868. scrollIntoView();
  10869. Replacing.set(component, []);
  10870. },
  10871. onGrown: function (_component) {
  10872. refresh();
  10873. scrollIntoView();
  10874. }
  10875. }),
  10876. orientation(function (_component, _data) {
  10877. disappear(noop);
  10878. })
  10879. ])
  10880. }));
  10881. var appear = function (menu, update, component) {
  10882. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  10883. window.requestAnimationFrame(function () {
  10884. update(component);
  10885. Replacing.set(dropup, [menu()]);
  10886. Sliding.grow(dropup);
  10887. });
  10888. }
  10889. };
  10890. var disappear = function (onReadyToShrink) {
  10891. window.requestAnimationFrame(function () {
  10892. onReadyToShrink();
  10893. Sliding.shrink(dropup);
  10894. });
  10895. };
  10896. return {
  10897. appear: appear,
  10898. disappear: disappear,
  10899. component: dropup,
  10900. element: dropup.element
  10901. };
  10902. };
  10903. var closest = function (scope, selector, isRoot) {
  10904. return closest$1(scope, selector, isRoot).isSome();
  10905. };
  10906. var isDangerous = function (event) {
  10907. var keyEv = event.raw;
  10908. return keyEv.which === BACKSPACE[0] && !contains$1([
  10909. 'input',
  10910. 'textarea'
  10911. ], name$1(event.target)) && !closest(event.target, '[contenteditable="true"]');
  10912. };
  10913. var isFirefox = function () {
  10914. return detect$1().browser.isFirefox();
  10915. };
  10916. var settingsSchema = objOfOnly([
  10917. requiredFunction('triggerEvent'),
  10918. defaulted('stopBackspace', true)
  10919. ]);
  10920. var bindFocus = function (container, handler) {
  10921. if (isFirefox()) {
  10922. return capture(container, 'focus', handler);
  10923. } else {
  10924. return bind(container, 'focusin', handler);
  10925. }
  10926. };
  10927. var bindBlur = function (container, handler) {
  10928. if (isFirefox()) {
  10929. return capture(container, 'blur', handler);
  10930. } else {
  10931. return bind(container, 'focusout', handler);
  10932. }
  10933. };
  10934. var setup$1 = function (container, rawSettings) {
  10935. var settings = asRawOrDie$1('Getting GUI events settings', settingsSchema, rawSettings);
  10936. var pointerEvents = [
  10937. 'touchstart',
  10938. 'touchmove',
  10939. 'touchend',
  10940. 'touchcancel',
  10941. 'gesturestart',
  10942. 'mousedown',
  10943. 'mouseup',
  10944. 'mouseover',
  10945. 'mousemove',
  10946. 'mouseout',
  10947. 'click'
  10948. ];
  10949. var tapEvent = monitor$1(settings);
  10950. var simpleEvents = map$2(pointerEvents.concat([
  10951. 'selectstart',
  10952. 'input',
  10953. 'contextmenu',
  10954. 'change',
  10955. 'transitionend',
  10956. 'transitioncancel',
  10957. 'drag',
  10958. 'dragstart',
  10959. 'dragend',
  10960. 'dragenter',
  10961. 'dragleave',
  10962. 'dragover',
  10963. 'drop',
  10964. 'keyup'
  10965. ]), function (type) {
  10966. return bind(container, type, function (event) {
  10967. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  10968. if (tapStopped) {
  10969. event.kill();
  10970. }
  10971. });
  10972. var stopped = settings.triggerEvent(type, event);
  10973. if (stopped) {
  10974. event.kill();
  10975. }
  10976. });
  10977. });
  10978. var pasteTimeout = value();
  10979. var onPaste = bind(container, 'paste', function (event) {
  10980. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  10981. if (tapStopped) {
  10982. event.kill();
  10983. }
  10984. });
  10985. var stopped = settings.triggerEvent('paste', event);
  10986. if (stopped) {
  10987. event.kill();
  10988. }
  10989. pasteTimeout.set(setTimeout(function () {
  10990. settings.triggerEvent(postPaste(), event);
  10991. }, 0));
  10992. });
  10993. var onKeydown = bind(container, 'keydown', function (event) {
  10994. var stopped = settings.triggerEvent('keydown', event);
  10995. if (stopped) {
  10996. event.kill();
  10997. } else if (settings.stopBackspace === true && isDangerous(event)) {
  10998. event.prevent();
  10999. }
  11000. });
  11001. var onFocusIn = bindFocus(container, function (event) {
  11002. var stopped = settings.triggerEvent('focusin', event);
  11003. if (stopped) {
  11004. event.kill();
  11005. }
  11006. });
  11007. var focusoutTimeout = value();
  11008. var onFocusOut = bindBlur(container, function (event) {
  11009. var stopped = settings.triggerEvent('focusout', event);
  11010. if (stopped) {
  11011. event.kill();
  11012. }
  11013. focusoutTimeout.set(setTimeout(function () {
  11014. settings.triggerEvent(postBlur(), event);
  11015. }, 0));
  11016. });
  11017. var unbind = function () {
  11018. each$1(simpleEvents, function (e) {
  11019. e.unbind();
  11020. });
  11021. onKeydown.unbind();
  11022. onFocusIn.unbind();
  11023. onFocusOut.unbind();
  11024. onPaste.unbind();
  11025. pasteTimeout.on(clearTimeout);
  11026. focusoutTimeout.on(clearTimeout);
  11027. };
  11028. return { unbind: unbind };
  11029. };
  11030. var derive$1 = function (rawEvent, rawTarget) {
  11031. var source = get$c(rawEvent, 'target').getOr(rawTarget);
  11032. return Cell(source);
  11033. };
  11034. var fromSource = function (event, source) {
  11035. var stopper = Cell(false);
  11036. var cutter = Cell(false);
  11037. var stop = function () {
  11038. stopper.set(true);
  11039. };
  11040. var cut = function () {
  11041. cutter.set(true);
  11042. };
  11043. return {
  11044. stop: stop,
  11045. cut: cut,
  11046. isStopped: stopper.get,
  11047. isCut: cutter.get,
  11048. event: event,
  11049. setSource: source.set,
  11050. getSource: source.get
  11051. };
  11052. };
  11053. var fromExternal = function (event) {
  11054. var stopper = Cell(false);
  11055. var stop = function () {
  11056. stopper.set(true);
  11057. };
  11058. return {
  11059. stop: stop,
  11060. cut: noop,
  11061. isStopped: stopper.get,
  11062. isCut: never,
  11063. event: event,
  11064. setSource: die('Cannot set source of a broadcasted event'),
  11065. getSource: die('Cannot get source of a broadcasted event')
  11066. };
  11067. };
  11068. var adt = Adt.generate([
  11069. { stopped: [] },
  11070. { resume: ['element'] },
  11071. { complete: [] }
  11072. ]);
  11073. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11074. var handler = lookup(eventType, target);
  11075. var simulatedEvent = fromSource(rawEvent, source);
  11076. return handler.fold(function () {
  11077. logger.logEventNoHandlers(eventType, target);
  11078. return adt.complete();
  11079. }, function (handlerInfo) {
  11080. var descHandler = handlerInfo.descHandler;
  11081. var eventHandler = getCurried(descHandler);
  11082. eventHandler(simulatedEvent);
  11083. if (simulatedEvent.isStopped()) {
  11084. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  11085. return adt.stopped();
  11086. } else if (simulatedEvent.isCut()) {
  11087. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  11088. return adt.complete();
  11089. } else {
  11090. return parent(handlerInfo.element).fold(function () {
  11091. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  11092. return adt.complete();
  11093. }, function (parent) {
  11094. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  11095. return adt.resume(parent);
  11096. });
  11097. }
  11098. });
  11099. };
  11100. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11101. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) {
  11102. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11103. }, never);
  11104. };
  11105. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11106. var source = derive$1(rawEvent, target);
  11107. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11108. };
  11109. var broadcast = function (listeners, rawEvent, _logger) {
  11110. var simulatedEvent = fromExternal(rawEvent);
  11111. each$1(listeners, function (listener) {
  11112. var descHandler = listener.descHandler;
  11113. var handler = getCurried(descHandler);
  11114. handler(simulatedEvent);
  11115. });
  11116. return simulatedEvent.isStopped();
  11117. };
  11118. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11119. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  11120. };
  11121. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11122. var source = derive$1(rawEvent, rawTarget);
  11123. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11124. };
  11125. var eventHandler = function (element, descHandler) {
  11126. return {
  11127. element: element,
  11128. descHandler: descHandler
  11129. };
  11130. };
  11131. var broadcastHandler = function (id, handler) {
  11132. return {
  11133. id: id,
  11134. descHandler: handler
  11135. };
  11136. };
  11137. var EventRegistry = function () {
  11138. var registry = {};
  11139. var registerId = function (extraArgs, id, events) {
  11140. each(events, function (v, k) {
  11141. var handlers = registry[k] !== undefined ? registry[k] : {};
  11142. handlers[id] = curryArgs(v, extraArgs);
  11143. registry[k] = handlers;
  11144. });
  11145. };
  11146. var findHandler = function (handlers, elem) {
  11147. return read(elem).fold(function () {
  11148. return Optional.none();
  11149. }, function (id) {
  11150. return handlers.bind(function (h) {
  11151. return get$c(h, id);
  11152. }).map(function (descHandler) {
  11153. return eventHandler(elem, descHandler);
  11154. });
  11155. });
  11156. };
  11157. var filterByType = function (type) {
  11158. return get$c(registry, type).map(function (handlers) {
  11159. return mapToArray(handlers, function (f, id) {
  11160. return broadcastHandler(id, f);
  11161. });
  11162. }).getOr([]);
  11163. };
  11164. var find = function (isAboveRoot, type, target) {
  11165. var handlers = get$c(registry, type);
  11166. return closest$3(target, function (elem) {
  11167. return findHandler(handlers, elem);
  11168. }, isAboveRoot);
  11169. };
  11170. var unregisterId = function (id) {
  11171. each(registry, function (handlersById, _eventName) {
  11172. if (has$2(handlersById, id)) {
  11173. delete handlersById[id];
  11174. }
  11175. });
  11176. };
  11177. return {
  11178. registerId: registerId,
  11179. unregisterId: unregisterId,
  11180. filterByType: filterByType,
  11181. find: find
  11182. };
  11183. };
  11184. var Registry = function () {
  11185. var events = EventRegistry();
  11186. var components = {};
  11187. var readOrTag = function (component) {
  11188. var elem = component.element;
  11189. return read(elem).getOrThunk(function () {
  11190. return write('uid-', component.element);
  11191. });
  11192. };
  11193. var failOnDuplicate = function (component, tagId) {
  11194. var conflict = components[tagId];
  11195. if (conflict === component) {
  11196. unregister(component);
  11197. } else {
  11198. throw new Error('The tagId "' + tagId + '" is already used by: ' + element(conflict.element) + '\nCannot use it for: ' + element(component.element) + '\n' + 'The conflicting element is' + (inBody(conflict.element) ? ' ' : ' not ') + 'already in the DOM');
  11199. }
  11200. };
  11201. var register = function (component) {
  11202. var tagId = readOrTag(component);
  11203. if (hasNonNullableKey(components, tagId)) {
  11204. failOnDuplicate(component, tagId);
  11205. }
  11206. var extraArgs = [component];
  11207. events.registerId(extraArgs, tagId, component.events);
  11208. components[tagId] = component;
  11209. };
  11210. var unregister = function (component) {
  11211. read(component.element).each(function (tagId) {
  11212. delete components[tagId];
  11213. events.unregisterId(tagId);
  11214. });
  11215. };
  11216. var filter = function (type) {
  11217. return events.filterByType(type);
  11218. };
  11219. var find = function (isAboveRoot, type, target) {
  11220. return events.find(isAboveRoot, type, target);
  11221. };
  11222. var getById = function (id) {
  11223. return get$c(components, id);
  11224. };
  11225. return {
  11226. find: find,
  11227. filter: filter,
  11228. register: register,
  11229. unregister: unregister,
  11230. getById: getById
  11231. };
  11232. };
  11233. var takeover$1 = function (root) {
  11234. var isAboveRoot = function (el) {
  11235. return parent(root.element).fold(always, function (parent) {
  11236. return eq(el, parent);
  11237. });
  11238. };
  11239. var registry = Registry();
  11240. var lookup = function (eventName, target) {
  11241. return registry.find(isAboveRoot, eventName, target);
  11242. };
  11243. var domEvents = setup$1(root.element, {
  11244. triggerEvent: function (eventName, event) {
  11245. return monitorEvent(eventName, event.target, function (logger) {
  11246. return triggerUntilStopped(lookup, eventName, event, logger);
  11247. });
  11248. }
  11249. });
  11250. var systemApi = {
  11251. debugInfo: constant$1('real'),
  11252. triggerEvent: function (eventName, target, data) {
  11253. monitorEvent(eventName, target, function (logger) {
  11254. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11255. });
  11256. },
  11257. triggerFocus: function (target, originator) {
  11258. read(target).fold(function () {
  11259. focus$3(target);
  11260. }, function (_alloyId) {
  11261. monitorEvent(focus$4(), target, function (logger) {
  11262. triggerHandler(lookup, focus$4(), {
  11263. originator: originator,
  11264. kill: noop,
  11265. prevent: noop,
  11266. target: target
  11267. }, target, logger);
  11268. return false;
  11269. });
  11270. });
  11271. },
  11272. triggerEscape: function (comp, simulatedEvent) {
  11273. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  11274. },
  11275. getByUid: function (uid) {
  11276. return getByUid(uid);
  11277. },
  11278. getByDom: function (elem) {
  11279. return getByDom(elem);
  11280. },
  11281. build: build$1,
  11282. addToGui: function (c) {
  11283. add(c);
  11284. },
  11285. removeFromGui: function (c) {
  11286. remove(c);
  11287. },
  11288. addToWorld: function (c) {
  11289. addToWorld(c);
  11290. },
  11291. removeFromWorld: function (c) {
  11292. removeFromWorld(c);
  11293. },
  11294. broadcast: function (message) {
  11295. broadcast$1(message);
  11296. },
  11297. broadcastOn: function (channels, message) {
  11298. broadcastOn(channels, message);
  11299. },
  11300. broadcastEvent: function (eventName, event) {
  11301. broadcastEvent(eventName, event);
  11302. },
  11303. isConnected: always
  11304. };
  11305. var addToWorld = function (component) {
  11306. component.connect(systemApi);
  11307. if (!isText(component.element)) {
  11308. registry.register(component);
  11309. each$1(component.components(), addToWorld);
  11310. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  11311. }
  11312. };
  11313. var removeFromWorld = function (component) {
  11314. if (!isText(component.element)) {
  11315. each$1(component.components(), removeFromWorld);
  11316. registry.unregister(component);
  11317. }
  11318. component.disconnect();
  11319. };
  11320. var add = function (component) {
  11321. attach(root, component);
  11322. };
  11323. var remove = function (component) {
  11324. detach(component);
  11325. };
  11326. var destroy = function () {
  11327. domEvents.unbind();
  11328. remove$7(root.element);
  11329. };
  11330. var broadcastData = function (data) {
  11331. var receivers = registry.filter(receive$1());
  11332. each$1(receivers, function (receiver) {
  11333. var descHandler = receiver.descHandler;
  11334. var handler = getCurried(descHandler);
  11335. handler(data);
  11336. });
  11337. };
  11338. var broadcast$1 = function (message) {
  11339. broadcastData({
  11340. universal: true,
  11341. data: message
  11342. });
  11343. };
  11344. var broadcastOn = function (channels, message) {
  11345. broadcastData({
  11346. universal: false,
  11347. channels: channels,
  11348. data: message
  11349. });
  11350. };
  11351. var broadcastEvent = function (eventName, event) {
  11352. var listeners = registry.filter(eventName);
  11353. return broadcast(listeners, event);
  11354. };
  11355. var getByUid = function (uid) {
  11356. return registry.getById(uid).fold(function () {
  11357. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11358. }, Result.value);
  11359. };
  11360. var getByDom = function (elem) {
  11361. var uid = read(elem).getOr('not found');
  11362. return getByUid(uid);
  11363. };
  11364. addToWorld(root);
  11365. return {
  11366. root: root,
  11367. element: root.element,
  11368. destroy: destroy,
  11369. add: add,
  11370. remove: remove,
  11371. getByUid: getByUid,
  11372. getByDom: getByDom,
  11373. addToWorld: addToWorld,
  11374. removeFromWorld: removeFromWorld,
  11375. broadcast: broadcast$1,
  11376. broadcastOn: broadcastOn,
  11377. broadcastEvent: broadcastEvent
  11378. };
  11379. };
  11380. var READ_ONLY_MODE_CLASS = resolve('readonly-mode');
  11381. var EDIT_MODE_CLASS = resolve('edit-mode');
  11382. function OuterContainer (spec) {
  11383. var root = build$1(Container.sketch({
  11384. dom: { classes: [resolve('outer-container')].concat(spec.classes) },
  11385. containerBehaviours: derive$2([Swapping.config({
  11386. alpha: READ_ONLY_MODE_CLASS,
  11387. omega: EDIT_MODE_CLASS
  11388. })])
  11389. }));
  11390. return takeover$1(root);
  11391. }
  11392. function AndroidRealm (scrollIntoView) {
  11393. var alloy = OuterContainer({ classes: [resolve('android-container')] });
  11394. var toolbar = ScrollingToolbar();
  11395. var webapp = api$2();
  11396. var switchToEdit = makeEditSwitch(webapp);
  11397. var socket = makeSocket();
  11398. var dropup = build(noop, scrollIntoView);
  11399. alloy.add(toolbar.wrapper);
  11400. alloy.add(socket);
  11401. alloy.add(dropup.component);
  11402. var setToolbarGroups = function (rawGroups) {
  11403. var groups = toolbar.createGroups(rawGroups);
  11404. toolbar.setGroups(groups);
  11405. };
  11406. var setContextToolbar = function (rawGroups) {
  11407. var groups = toolbar.createGroups(rawGroups);
  11408. toolbar.setContextToolbar(groups);
  11409. };
  11410. var focusToolbar = function () {
  11411. toolbar.focus();
  11412. };
  11413. var restoreToolbar = function () {
  11414. toolbar.restoreToolbar();
  11415. };
  11416. var init = function (spec) {
  11417. webapp.set(produce$1(spec));
  11418. };
  11419. var exit = function () {
  11420. webapp.run(function (w) {
  11421. w.exit();
  11422. Replacing.remove(socket, switchToEdit);
  11423. });
  11424. };
  11425. var updateMode$1 = function (readOnly) {
  11426. updateMode(socket, switchToEdit, readOnly, alloy.root);
  11427. };
  11428. return {
  11429. system: alloy,
  11430. element: alloy.element,
  11431. init: init,
  11432. exit: exit,
  11433. setToolbarGroups: setToolbarGroups,
  11434. setContextToolbar: setContextToolbar,
  11435. focusToolbar: focusToolbar,
  11436. restoreToolbar: restoreToolbar,
  11437. updateMode: updateMode$1,
  11438. socket: socket,
  11439. dropup: dropup
  11440. };
  11441. }
  11442. var input = function (parent, operation) {
  11443. var input = SugarElement.fromTag('input');
  11444. setAll(input, {
  11445. opacity: '0',
  11446. position: 'absolute',
  11447. top: '-1000px',
  11448. left: '-1000px'
  11449. });
  11450. append$2(parent, input);
  11451. focus$3(input);
  11452. operation(input);
  11453. remove$7(input);
  11454. };
  11455. var refresh = function (winScope) {
  11456. var sel = winScope.getSelection();
  11457. if (sel.rangeCount > 0) {
  11458. var br = sel.getRangeAt(0);
  11459. var r = winScope.document.createRange();
  11460. r.setStart(br.startContainer, br.startOffset);
  11461. r.setEnd(br.endContainer, br.endOffset);
  11462. sel.removeAllRanges();
  11463. sel.addRange(r);
  11464. }
  11465. };
  11466. var resume = function (cWin, frame) {
  11467. active().each(function (active) {
  11468. if (!eq(active, frame)) {
  11469. blur$1(active);
  11470. }
  11471. });
  11472. cWin.focus();
  11473. focus$3(SugarElement.fromDom(cWin.document.body));
  11474. refresh(cWin);
  11475. };
  11476. var stubborn = function (outerBody, cWin, page, frame) {
  11477. var toEditing = function () {
  11478. resume(cWin, frame);
  11479. };
  11480. var toReading = function () {
  11481. input(outerBody, blur$1);
  11482. };
  11483. var captureInput = bind(page, 'keydown', function (evt) {
  11484. if (!contains$1([
  11485. 'input',
  11486. 'textarea'
  11487. ], name$1(evt.target))) {
  11488. toEditing();
  11489. }
  11490. });
  11491. var onToolbarTouch = noop;
  11492. var destroy = function () {
  11493. captureInput.unbind();
  11494. };
  11495. return {
  11496. toReading: toReading,
  11497. toEditing: toEditing,
  11498. onToolbarTouch: onToolbarTouch,
  11499. destroy: destroy
  11500. };
  11501. };
  11502. var initEvents = function (editorApi, iosApi, toolstrip, socket, _dropup) {
  11503. var saveSelectionFirst = function () {
  11504. iosApi.run(function (api) {
  11505. api.highlightSelection();
  11506. });
  11507. };
  11508. var refreshIosSelection = function () {
  11509. iosApi.run(function (api) {
  11510. api.refreshSelection();
  11511. });
  11512. };
  11513. var scrollToY = function (yTop, height) {
  11514. var y = yTop - socket.dom.scrollTop;
  11515. iosApi.run(function (api) {
  11516. api.scrollIntoView(y, y + height);
  11517. });
  11518. };
  11519. var scrollToElement = function (_target) {
  11520. scrollToY(iosApi, socket);
  11521. };
  11522. var scrollToCursor = function () {
  11523. editorApi.getCursorBox().each(function (box) {
  11524. scrollToY(box.top, box.height);
  11525. });
  11526. };
  11527. var clearSelection = function () {
  11528. iosApi.run(function (api) {
  11529. api.clearSelection();
  11530. });
  11531. };
  11532. var clearAndRefresh = function () {
  11533. clearSelection();
  11534. refreshThrottle.throttle();
  11535. };
  11536. var refreshView = function () {
  11537. scrollToCursor();
  11538. iosApi.run(function (api) {
  11539. api.syncHeight();
  11540. });
  11541. };
  11542. var reposition = function () {
  11543. var toolbarHeight = get$7(toolstrip);
  11544. iosApi.run(function (api) {
  11545. api.setViewportOffset(toolbarHeight);
  11546. });
  11547. refreshIosSelection();
  11548. refreshView();
  11549. };
  11550. var toEditing = function () {
  11551. iosApi.run(function (api) {
  11552. api.toEditing();
  11553. });
  11554. };
  11555. var toReading = function () {
  11556. iosApi.run(function (api) {
  11557. api.toReading();
  11558. });
  11559. };
  11560. var onToolbarTouch = function (event) {
  11561. iosApi.run(function (api) {
  11562. api.onToolbarTouch(event);
  11563. });
  11564. };
  11565. var tapping = monitor(editorApi);
  11566. var refreshThrottle = last(refreshView, 300);
  11567. var listeners = [
  11568. editorApi.onKeyup(clearAndRefresh),
  11569. editorApi.onNodeChanged(refreshIosSelection),
  11570. editorApi.onDomChanged(refreshThrottle.throttle),
  11571. editorApi.onDomChanged(refreshIosSelection),
  11572. editorApi.onScrollToCursor(function (tinyEvent) {
  11573. tinyEvent.preventDefault();
  11574. refreshThrottle.throttle();
  11575. }),
  11576. editorApi.onScrollToElement(function (event) {
  11577. scrollToElement(event.element);
  11578. }),
  11579. editorApi.onToEditing(toEditing),
  11580. editorApi.onToReading(toReading),
  11581. bind(editorApi.doc, 'touchend', function (touchEvent) {
  11582. if (eq(editorApi.html, touchEvent.target) || eq(editorApi.body, touchEvent.target)) ;
  11583. }),
  11584. bind(toolstrip, 'transitionend', function (transitionEvent) {
  11585. if (transitionEvent.raw.propertyName === 'height') {
  11586. reposition();
  11587. }
  11588. }),
  11589. capture(toolstrip, 'touchstart', function (touchEvent) {
  11590. saveSelectionFirst();
  11591. onToolbarTouch(touchEvent);
  11592. editorApi.onTouchToolstrip();
  11593. }),
  11594. bind(editorApi.body, 'touchstart', function (evt) {
  11595. clearSelection();
  11596. editorApi.onTouchContent();
  11597. tapping.fireTouchstart(evt);
  11598. }),
  11599. tapping.onTouchmove(),
  11600. tapping.onTouchend(),
  11601. bind(editorApi.body, 'click', function (event) {
  11602. event.kill();
  11603. }),
  11604. bind(toolstrip, 'touchmove', function () {
  11605. editorApi.onToolbarScrollStart();
  11606. })
  11607. ];
  11608. var destroy = function () {
  11609. each$1(listeners, function (l) {
  11610. l.unbind();
  11611. });
  11612. };
  11613. return { destroy: destroy };
  11614. };
  11615. function FakeSelection (win, frame) {
  11616. var doc = win.document;
  11617. var container = SugarElement.fromTag('div');
  11618. add$1(container, resolve('unfocused-selections'));
  11619. append$2(SugarElement.fromDom(doc.documentElement), container);
  11620. var onTouch = bind(container, 'touchstart', function (event) {
  11621. event.prevent();
  11622. resume(win, frame);
  11623. clear();
  11624. });
  11625. var make = function (rectangle) {
  11626. var span = SugarElement.fromTag('span');
  11627. add(span, [
  11628. resolve('layer-editor'),
  11629. resolve('unfocused-selection')
  11630. ]);
  11631. setAll(span, {
  11632. left: rectangle.left + 'px',
  11633. top: rectangle.top + 'px',
  11634. width: rectangle.width + 'px',
  11635. height: rectangle.height + 'px'
  11636. });
  11637. return span;
  11638. };
  11639. var update = function () {
  11640. clear();
  11641. var rectangles = getRectangles(win);
  11642. var spans = map$2(rectangles, make);
  11643. append$1(container, spans);
  11644. };
  11645. var clear = function () {
  11646. empty(container);
  11647. };
  11648. var destroy = function () {
  11649. onTouch.unbind();
  11650. remove$7(container);
  11651. };
  11652. var isActive = function () {
  11653. return children(container).length > 0;
  11654. };
  11655. return {
  11656. update: update,
  11657. isActive: isActive,
  11658. destroy: destroy,
  11659. clear: clear
  11660. };
  11661. }
  11662. var exports$1 = {}, module = { exports: exports$1 };
  11663. (function (define, exports, module, require) {
  11664. (function (f) {
  11665. if (typeof exports === 'object' && typeof module !== 'undefined') {
  11666. module.exports = f();
  11667. } else if (typeof define === 'function' && define.amd) {
  11668. define([], f);
  11669. } else {
  11670. var g;
  11671. if (typeof window !== 'undefined') {
  11672. g = window;
  11673. } else if (typeof global !== 'undefined') {
  11674. g = global;
  11675. } else if (typeof self !== 'undefined') {
  11676. g = self;
  11677. } else {
  11678. g = this;
  11679. }
  11680. g.EphoxContactWrapper = f();
  11681. }
  11682. }(function () {
  11683. return function () {
  11684. function r(e, n, t) {
  11685. function o(i, f) {
  11686. if (!n[i]) {
  11687. if (!e[i]) {
  11688. var c = 'function' == typeof require && require;
  11689. if (!f && c)
  11690. return c(i, !0);
  11691. if (u)
  11692. return u(i, !0);
  11693. var a = new Error('Cannot find module \'' + i + '\'');
  11694. throw a.code = 'MODULE_NOT_FOUND', a;
  11695. }
  11696. var p = n[i] = { exports: {} };
  11697. e[i][0].call(p.exports, function (r) {
  11698. var n = e[i][1][r];
  11699. return o(n || r);
  11700. }, p, p.exports, r, e, n, t);
  11701. }
  11702. return n[i].exports;
  11703. }
  11704. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  11705. o(t[i]);
  11706. return o;
  11707. }
  11708. return r;
  11709. }()({
  11710. 1: [
  11711. function (require, module, exports) {
  11712. var process = module.exports = {};
  11713. var cachedSetTimeout;
  11714. var cachedClearTimeout;
  11715. function defaultSetTimout() {
  11716. throw new Error('setTimeout has not been defined');
  11717. }
  11718. function defaultClearTimeout() {
  11719. throw new Error('clearTimeout has not been defined');
  11720. }
  11721. (function () {
  11722. try {
  11723. if (typeof setTimeout === 'function') {
  11724. cachedSetTimeout = setTimeout;
  11725. } else {
  11726. cachedSetTimeout = defaultSetTimout;
  11727. }
  11728. } catch (e) {
  11729. cachedSetTimeout = defaultSetTimout;
  11730. }
  11731. try {
  11732. if (typeof clearTimeout === 'function') {
  11733. cachedClearTimeout = clearTimeout;
  11734. } else {
  11735. cachedClearTimeout = defaultClearTimeout;
  11736. }
  11737. } catch (e) {
  11738. cachedClearTimeout = defaultClearTimeout;
  11739. }
  11740. }());
  11741. function runTimeout(fun) {
  11742. if (cachedSetTimeout === setTimeout) {
  11743. return setTimeout(fun, 0);
  11744. }
  11745. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11746. cachedSetTimeout = setTimeout;
  11747. return setTimeout(fun, 0);
  11748. }
  11749. try {
  11750. return cachedSetTimeout(fun, 0);
  11751. } catch (e) {
  11752. try {
  11753. return cachedSetTimeout.call(null, fun, 0);
  11754. } catch (e) {
  11755. return cachedSetTimeout.call(this, fun, 0);
  11756. }
  11757. }
  11758. }
  11759. function runClearTimeout(marker) {
  11760. if (cachedClearTimeout === clearTimeout) {
  11761. return clearTimeout(marker);
  11762. }
  11763. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11764. cachedClearTimeout = clearTimeout;
  11765. return clearTimeout(marker);
  11766. }
  11767. try {
  11768. return cachedClearTimeout(marker);
  11769. } catch (e) {
  11770. try {
  11771. return cachedClearTimeout.call(null, marker);
  11772. } catch (e) {
  11773. return cachedClearTimeout.call(this, marker);
  11774. }
  11775. }
  11776. }
  11777. var queue = [];
  11778. var draining = false;
  11779. var currentQueue;
  11780. var queueIndex = -1;
  11781. function cleanUpNextTick() {
  11782. if (!draining || !currentQueue) {
  11783. return;
  11784. }
  11785. draining = false;
  11786. if (currentQueue.length) {
  11787. queue = currentQueue.concat(queue);
  11788. } else {
  11789. queueIndex = -1;
  11790. }
  11791. if (queue.length) {
  11792. drainQueue();
  11793. }
  11794. }
  11795. function drainQueue() {
  11796. if (draining) {
  11797. return;
  11798. }
  11799. var timeout = runTimeout(cleanUpNextTick);
  11800. draining = true;
  11801. var len = queue.length;
  11802. while (len) {
  11803. currentQueue = queue;
  11804. queue = [];
  11805. while (++queueIndex < len) {
  11806. if (currentQueue) {
  11807. currentQueue[queueIndex].run();
  11808. }
  11809. }
  11810. queueIndex = -1;
  11811. len = queue.length;
  11812. }
  11813. currentQueue = null;
  11814. draining = false;
  11815. runClearTimeout(timeout);
  11816. }
  11817. process.nextTick = function (fun) {
  11818. var args = new Array(arguments.length - 1);
  11819. if (arguments.length > 1) {
  11820. for (var i = 1; i < arguments.length; i++) {
  11821. args[i - 1] = arguments[i];
  11822. }
  11823. }
  11824. queue.push(new Item(fun, args));
  11825. if (queue.length === 1 && !draining) {
  11826. runTimeout(drainQueue);
  11827. }
  11828. };
  11829. function Item(fun, array) {
  11830. this.fun = fun;
  11831. this.array = array;
  11832. }
  11833. Item.prototype.run = function () {
  11834. this.fun.apply(null, this.array);
  11835. };
  11836. process.title = 'browser';
  11837. process.browser = true;
  11838. process.env = {};
  11839. process.argv = [];
  11840. process.version = '';
  11841. process.versions = {};
  11842. function noop() {
  11843. }
  11844. process.on = noop;
  11845. process.addListener = noop;
  11846. process.once = noop;
  11847. process.off = noop;
  11848. process.removeListener = noop;
  11849. process.removeAllListeners = noop;
  11850. process.emit = noop;
  11851. process.prependListener = noop;
  11852. process.prependOnceListener = noop;
  11853. process.listeners = function (name) {
  11854. return [];
  11855. };
  11856. process.binding = function (name) {
  11857. throw new Error('process.binding is not supported');
  11858. };
  11859. process.cwd = function () {
  11860. return '/';
  11861. };
  11862. process.chdir = function (dir) {
  11863. throw new Error('process.chdir is not supported');
  11864. };
  11865. process.umask = function () {
  11866. return 0;
  11867. };
  11868. },
  11869. {}
  11870. ],
  11871. 2: [
  11872. function (require, module, exports) {
  11873. (function (setImmediate) {
  11874. (function (root) {
  11875. var setTimeoutFunc = setTimeout;
  11876. function noop() {
  11877. }
  11878. function bind(fn, thisArg) {
  11879. return function () {
  11880. fn.apply(thisArg, arguments);
  11881. };
  11882. }
  11883. function Promise(fn) {
  11884. if (typeof this !== 'object')
  11885. throw new TypeError('Promises must be constructed via new');
  11886. if (typeof fn !== 'function')
  11887. throw new TypeError('not a function');
  11888. this._state = 0;
  11889. this._handled = false;
  11890. this._value = undefined;
  11891. this._deferreds = [];
  11892. doResolve(fn, this);
  11893. }
  11894. function handle(self, deferred) {
  11895. while (self._state === 3) {
  11896. self = self._value;
  11897. }
  11898. if (self._state === 0) {
  11899. self._deferreds.push(deferred);
  11900. return;
  11901. }
  11902. self._handled = true;
  11903. Promise._immediateFn(function () {
  11904. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  11905. if (cb === null) {
  11906. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  11907. return;
  11908. }
  11909. var ret;
  11910. try {
  11911. ret = cb(self._value);
  11912. } catch (e) {
  11913. reject(deferred.promise, e);
  11914. return;
  11915. }
  11916. resolve(deferred.promise, ret);
  11917. });
  11918. }
  11919. function resolve(self, newValue) {
  11920. try {
  11921. if (newValue === self)
  11922. throw new TypeError('A promise cannot be resolved with itself.');
  11923. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  11924. var then = newValue.then;
  11925. if (newValue instanceof Promise) {
  11926. self._state = 3;
  11927. self._value = newValue;
  11928. finale(self);
  11929. return;
  11930. } else if (typeof then === 'function') {
  11931. doResolve(bind(then, newValue), self);
  11932. return;
  11933. }
  11934. }
  11935. self._state = 1;
  11936. self._value = newValue;
  11937. finale(self);
  11938. } catch (e) {
  11939. reject(self, e);
  11940. }
  11941. }
  11942. function reject(self, newValue) {
  11943. self._state = 2;
  11944. self._value = newValue;
  11945. finale(self);
  11946. }
  11947. function finale(self) {
  11948. if (self._state === 2 && self._deferreds.length === 0) {
  11949. Promise._immediateFn(function () {
  11950. if (!self._handled) {
  11951. Promise._unhandledRejectionFn(self._value);
  11952. }
  11953. });
  11954. }
  11955. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  11956. handle(self, self._deferreds[i]);
  11957. }
  11958. self._deferreds = null;
  11959. }
  11960. function Handler(onFulfilled, onRejected, promise) {
  11961. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  11962. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  11963. this.promise = promise;
  11964. }
  11965. function doResolve(fn, self) {
  11966. var done = false;
  11967. try {
  11968. fn(function (value) {
  11969. if (done)
  11970. return;
  11971. done = true;
  11972. resolve(self, value);
  11973. }, function (reason) {
  11974. if (done)
  11975. return;
  11976. done = true;
  11977. reject(self, reason);
  11978. });
  11979. } catch (ex) {
  11980. if (done)
  11981. return;
  11982. done = true;
  11983. reject(self, ex);
  11984. }
  11985. }
  11986. Promise.prototype['catch'] = function (onRejected) {
  11987. return this.then(null, onRejected);
  11988. };
  11989. Promise.prototype.then = function (onFulfilled, onRejected) {
  11990. var prom = new this.constructor(noop);
  11991. handle(this, new Handler(onFulfilled, onRejected, prom));
  11992. return prom;
  11993. };
  11994. Promise.all = function (arr) {
  11995. var args = Array.prototype.slice.call(arr);
  11996. return new Promise(function (resolve, reject) {
  11997. if (args.length === 0)
  11998. return resolve([]);
  11999. var remaining = args.length;
  12000. function res(i, val) {
  12001. try {
  12002. if (val && (typeof val === 'object' || typeof val === 'function')) {
  12003. var then = val.then;
  12004. if (typeof then === 'function') {
  12005. then.call(val, function (val) {
  12006. res(i, val);
  12007. }, reject);
  12008. return;
  12009. }
  12010. }
  12011. args[i] = val;
  12012. if (--remaining === 0) {
  12013. resolve(args);
  12014. }
  12015. } catch (ex) {
  12016. reject(ex);
  12017. }
  12018. }
  12019. for (var i = 0; i < args.length; i++) {
  12020. res(i, args[i]);
  12021. }
  12022. });
  12023. };
  12024. Promise.resolve = function (value) {
  12025. if (value && typeof value === 'object' && value.constructor === Promise) {
  12026. return value;
  12027. }
  12028. return new Promise(function (resolve) {
  12029. resolve(value);
  12030. });
  12031. };
  12032. Promise.reject = function (value) {
  12033. return new Promise(function (resolve, reject) {
  12034. reject(value);
  12035. });
  12036. };
  12037. Promise.race = function (values) {
  12038. return new Promise(function (resolve, reject) {
  12039. for (var i = 0, len = values.length; i < len; i++) {
  12040. values[i].then(resolve, reject);
  12041. }
  12042. });
  12043. };
  12044. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  12045. setImmediate(fn);
  12046. } : function (fn) {
  12047. setTimeoutFunc(fn, 0);
  12048. };
  12049. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  12050. if (typeof console !== 'undefined' && console) {
  12051. console.warn('Possible Unhandled Promise Rejection:', err);
  12052. }
  12053. };
  12054. Promise._setImmediateFn = function _setImmediateFn(fn) {
  12055. Promise._immediateFn = fn;
  12056. };
  12057. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  12058. Promise._unhandledRejectionFn = fn;
  12059. };
  12060. if (typeof module !== 'undefined' && module.exports) {
  12061. module.exports = Promise;
  12062. } else if (!root.Promise) {
  12063. root.Promise = Promise;
  12064. }
  12065. }(this));
  12066. }.call(this, require('timers').setImmediate));
  12067. },
  12068. { 'timers': 3 }
  12069. ],
  12070. 3: [
  12071. function (require, module, exports) {
  12072. (function (setImmediate, clearImmediate) {
  12073. var nextTick = require('process/browser.js').nextTick;
  12074. var apply = Function.prototype.apply;
  12075. var slice = Array.prototype.slice;
  12076. var immediateIds = {};
  12077. var nextImmediateId = 0;
  12078. exports.setTimeout = function () {
  12079. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  12080. };
  12081. exports.setInterval = function () {
  12082. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12083. };
  12084. exports.clearTimeout = exports.clearInterval = function (timeout) {
  12085. timeout.close();
  12086. };
  12087. function Timeout(id, clearFn) {
  12088. this._id = id;
  12089. this._clearFn = clearFn;
  12090. }
  12091. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  12092. };
  12093. Timeout.prototype.close = function () {
  12094. this._clearFn.call(window, this._id);
  12095. };
  12096. exports.enroll = function (item, msecs) {
  12097. clearTimeout(item._idleTimeoutId);
  12098. item._idleTimeout = msecs;
  12099. };
  12100. exports.unenroll = function (item) {
  12101. clearTimeout(item._idleTimeoutId);
  12102. item._idleTimeout = -1;
  12103. };
  12104. exports._unrefActive = exports.active = function (item) {
  12105. clearTimeout(item._idleTimeoutId);
  12106. var msecs = item._idleTimeout;
  12107. if (msecs >= 0) {
  12108. item._idleTimeoutId = setTimeout(function onTimeout() {
  12109. if (item._onTimeout)
  12110. item._onTimeout();
  12111. }, msecs);
  12112. }
  12113. };
  12114. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  12115. var id = nextImmediateId++;
  12116. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  12117. immediateIds[id] = true;
  12118. nextTick(function onNextTick() {
  12119. if (immediateIds[id]) {
  12120. if (args) {
  12121. fn.apply(null, args);
  12122. } else {
  12123. fn.call(null);
  12124. }
  12125. exports.clearImmediate(id);
  12126. }
  12127. });
  12128. return id;
  12129. };
  12130. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  12131. delete immediateIds[id];
  12132. };
  12133. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  12134. },
  12135. {
  12136. 'process/browser.js': 1,
  12137. 'timers': 3
  12138. }
  12139. ],
  12140. 4: [
  12141. function (require, module, exports) {
  12142. var promisePolyfill = require('promise-polyfill');
  12143. var Global = function () {
  12144. if (typeof window !== 'undefined') {
  12145. return window;
  12146. } else {
  12147. return Function('return this;')();
  12148. }
  12149. }();
  12150. module.exports = { boltExport: Global.Promise || promisePolyfill };
  12151. },
  12152. { 'promise-polyfill': 2 }
  12153. ]
  12154. }, {}, [4])(4);
  12155. }));
  12156. }(undefined, exports$1, module, undefined));
  12157. var Promise$1 = module.exports.boltExport;
  12158. var nu$1 = function (baseFn) {
  12159. var data = Optional.none();
  12160. var callbacks = [];
  12161. var map = function (f) {
  12162. return nu$1(function (nCallback) {
  12163. get(function (data) {
  12164. nCallback(f(data));
  12165. });
  12166. });
  12167. };
  12168. var get = function (nCallback) {
  12169. if (isReady()) {
  12170. call(nCallback);
  12171. } else {
  12172. callbacks.push(nCallback);
  12173. }
  12174. };
  12175. var set = function (x) {
  12176. if (!isReady()) {
  12177. data = Optional.some(x);
  12178. run(callbacks);
  12179. callbacks = [];
  12180. }
  12181. };
  12182. var isReady = function () {
  12183. return data.isSome();
  12184. };
  12185. var run = function (cbs) {
  12186. each$1(cbs, call);
  12187. };
  12188. var call = function (cb) {
  12189. data.each(function (x) {
  12190. setTimeout(function () {
  12191. cb(x);
  12192. }, 0);
  12193. });
  12194. };
  12195. baseFn(set);
  12196. return {
  12197. get: get,
  12198. map: map,
  12199. isReady: isReady
  12200. };
  12201. };
  12202. var pure$1 = function (a) {
  12203. return nu$1(function (callback) {
  12204. callback(a);
  12205. });
  12206. };
  12207. var LazyValue = {
  12208. nu: nu$1,
  12209. pure: pure$1
  12210. };
  12211. var errorReporter = function (err) {
  12212. setTimeout(function () {
  12213. throw err;
  12214. }, 0);
  12215. };
  12216. var make = function (run) {
  12217. var get = function (callback) {
  12218. run().then(callback, errorReporter);
  12219. };
  12220. var map = function (fab) {
  12221. return make(function () {
  12222. return run().then(fab);
  12223. });
  12224. };
  12225. var bind = function (aFutureB) {
  12226. return make(function () {
  12227. return run().then(function (v) {
  12228. return aFutureB(v).toPromise();
  12229. });
  12230. });
  12231. };
  12232. var anonBind = function (futureB) {
  12233. return make(function () {
  12234. return run().then(function () {
  12235. return futureB.toPromise();
  12236. });
  12237. });
  12238. };
  12239. var toLazy = function () {
  12240. return LazyValue.nu(get);
  12241. };
  12242. var toCached = function () {
  12243. var cache = null;
  12244. return make(function () {
  12245. if (cache === null) {
  12246. cache = run();
  12247. }
  12248. return cache;
  12249. });
  12250. };
  12251. var toPromise = run;
  12252. return {
  12253. map: map,
  12254. bind: bind,
  12255. anonBind: anonBind,
  12256. toLazy: toLazy,
  12257. toCached: toCached,
  12258. toPromise: toPromise,
  12259. get: get
  12260. };
  12261. };
  12262. var nu = function (baseFn) {
  12263. return make(function () {
  12264. return new Promise$1(baseFn);
  12265. });
  12266. };
  12267. var pure = function (a) {
  12268. return make(function () {
  12269. return Promise$1.resolve(a);
  12270. });
  12271. };
  12272. var Future = {
  12273. nu: nu,
  12274. pure: pure
  12275. };
  12276. var adjust = function (value, destination, amount) {
  12277. if (Math.abs(value - destination) <= amount) {
  12278. return Optional.none();
  12279. } else if (value < destination) {
  12280. return Optional.some(value + amount);
  12281. } else {
  12282. return Optional.some(value - amount);
  12283. }
  12284. };
  12285. var create$1 = function () {
  12286. var interval = null;
  12287. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  12288. var finished = false;
  12289. var finish = function (v) {
  12290. finished = true;
  12291. doFinish(v);
  12292. };
  12293. global$2.clearInterval(interval);
  12294. var abort = function (v) {
  12295. global$2.clearInterval(interval);
  12296. finish(v);
  12297. };
  12298. interval = global$2.setInterval(function () {
  12299. var value = getCurrent();
  12300. adjust(value, destination, amount).fold(function () {
  12301. global$2.clearInterval(interval);
  12302. finish(destination);
  12303. }, function (s) {
  12304. increment(s, abort);
  12305. if (!finished) {
  12306. var newValue = getCurrent();
  12307. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  12308. global$2.clearInterval(interval);
  12309. finish(destination);
  12310. }
  12311. }
  12312. });
  12313. }, rate);
  12314. };
  12315. return { animate: animate };
  12316. };
  12317. var findDevice = function (deviceWidth, deviceHeight) {
  12318. var devices = [
  12319. {
  12320. width: 320,
  12321. height: 480,
  12322. keyboard: {
  12323. portrait: 300,
  12324. landscape: 240
  12325. }
  12326. },
  12327. {
  12328. width: 320,
  12329. height: 568,
  12330. keyboard: {
  12331. portrait: 300,
  12332. landscape: 240
  12333. }
  12334. },
  12335. {
  12336. width: 375,
  12337. height: 667,
  12338. keyboard: {
  12339. portrait: 305,
  12340. landscape: 240
  12341. }
  12342. },
  12343. {
  12344. width: 414,
  12345. height: 736,
  12346. keyboard: {
  12347. portrait: 320,
  12348. landscape: 240
  12349. }
  12350. },
  12351. {
  12352. width: 768,
  12353. height: 1024,
  12354. keyboard: {
  12355. portrait: 320,
  12356. landscape: 400
  12357. }
  12358. },
  12359. {
  12360. width: 1024,
  12361. height: 1366,
  12362. keyboard: {
  12363. portrait: 380,
  12364. landscape: 460
  12365. }
  12366. }
  12367. ];
  12368. return findMap(devices, function (device) {
  12369. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  12370. }).getOr({
  12371. portrait: deviceHeight / 5,
  12372. landscape: deviceWidth / 4
  12373. });
  12374. };
  12375. var softKeyboardLimits = function (outerWindow) {
  12376. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  12377. };
  12378. var accountableKeyboardHeight = function (outerWindow) {
  12379. var portrait = get$1(outerWindow).isPortrait();
  12380. var limits = softKeyboardLimits(outerWindow);
  12381. var keyboard = portrait ? limits.portrait : limits.landscape;
  12382. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  12383. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  12384. };
  12385. var getGreenzone = function (socket, dropup) {
  12386. var outerWindow = owner$2(socket).dom.defaultView;
  12387. var viewportHeight = get$7(socket) + get$7(dropup);
  12388. var acc = accountableKeyboardHeight(outerWindow);
  12389. return viewportHeight - acc;
  12390. };
  12391. var updatePadding = function (contentBody, socket, dropup) {
  12392. var greenzoneHeight = getGreenzone(socket, dropup);
  12393. var deltaHeight = get$7(socket) + get$7(dropup) - greenzoneHeight;
  12394. set$5(contentBody, 'padding-bottom', deltaHeight + 'px');
  12395. };
  12396. var fixture = Adt.generate([
  12397. {
  12398. fixed: [
  12399. 'element',
  12400. 'property',
  12401. 'offsetY'
  12402. ]
  12403. },
  12404. {
  12405. scroller: [
  12406. 'element',
  12407. 'offsetY'
  12408. ]
  12409. }
  12410. ]);
  12411. var yFixedData = 'data-' + resolve('position-y-fixed');
  12412. var yFixedProperty = 'data-' + resolve('y-property');
  12413. var yScrollingData = 'data-' + resolve('scrolling');
  12414. var windowSizeData = 'data-' + resolve('last-window-height');
  12415. var getYFixedData = function (element) {
  12416. return safeParse(element, yFixedData);
  12417. };
  12418. var getYFixedProperty = function (element) {
  12419. return get$b(element, yFixedProperty);
  12420. };
  12421. var getLastWindowSize = function (element) {
  12422. return safeParse(element, windowSizeData);
  12423. };
  12424. var classifyFixed = function (element, offsetY) {
  12425. var prop = getYFixedProperty(element);
  12426. return fixture.fixed(element, prop, offsetY);
  12427. };
  12428. var classifyScrolling = function (element, offsetY) {
  12429. return fixture.scroller(element, offsetY);
  12430. };
  12431. var classify = function (element) {
  12432. var offsetY = getYFixedData(element);
  12433. var classifier = get$b(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  12434. return classifier(element, offsetY);
  12435. };
  12436. var findFixtures = function (container) {
  12437. var candidates = descendants(container, '[' + yFixedData + ']');
  12438. return map$2(candidates, classify);
  12439. };
  12440. var takeoverToolbar = function (toolbar) {
  12441. var oldToolbarStyle = get$b(toolbar, 'style');
  12442. setAll(toolbar, {
  12443. position: 'absolute',
  12444. top: '0px'
  12445. });
  12446. set$8(toolbar, yFixedData, '0px');
  12447. set$8(toolbar, yFixedProperty, 'top');
  12448. var restore = function () {
  12449. set$8(toolbar, 'style', oldToolbarStyle || '');
  12450. remove$6(toolbar, yFixedData);
  12451. remove$6(toolbar, yFixedProperty);
  12452. };
  12453. return { restore: restore };
  12454. };
  12455. var takeoverViewport = function (toolbarHeight, height, viewport) {
  12456. var oldViewportStyle = get$b(viewport, 'style');
  12457. register$2(viewport);
  12458. setAll(viewport, {
  12459. position: 'absolute',
  12460. height: height + 'px',
  12461. width: '100%',
  12462. top: toolbarHeight + 'px'
  12463. });
  12464. set$8(viewport, yFixedData, toolbarHeight + 'px');
  12465. set$8(viewport, yScrollingData, 'true');
  12466. set$8(viewport, yFixedProperty, 'top');
  12467. var restore = function () {
  12468. deregister(viewport);
  12469. set$8(viewport, 'style', oldViewportStyle || '');
  12470. remove$6(viewport, yFixedData);
  12471. remove$6(viewport, yScrollingData);
  12472. remove$6(viewport, yFixedProperty);
  12473. };
  12474. return { restore: restore };
  12475. };
  12476. var takeoverDropup = function (dropup) {
  12477. var oldDropupStyle = get$b(dropup, 'style');
  12478. setAll(dropup, {
  12479. position: 'absolute',
  12480. bottom: '0px'
  12481. });
  12482. set$8(dropup, yFixedData, '0px');
  12483. set$8(dropup, yFixedProperty, 'bottom');
  12484. var restore = function () {
  12485. set$8(dropup, 'style', oldDropupStyle || '');
  12486. remove$6(dropup, yFixedData);
  12487. remove$6(dropup, yFixedProperty);
  12488. };
  12489. return { restore: restore };
  12490. };
  12491. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12492. var outerWindow = owner$2(viewport).dom.defaultView;
  12493. var winH = outerWindow.innerHeight;
  12494. set$8(viewport, windowSizeData, winH + 'px');
  12495. return winH - toolbarHeight - dropupHeight;
  12496. };
  12497. var takeover = function (viewport, contentBody, toolbar, dropup) {
  12498. var outerWindow = owner$2(viewport).dom.defaultView;
  12499. var toolbarSetup = takeoverToolbar(toolbar);
  12500. var toolbarHeight = get$7(toolbar);
  12501. var dropupHeight = get$7(dropup);
  12502. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12503. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12504. var dropupSetup = takeoverDropup(dropup);
  12505. var isActive = true;
  12506. var restore = function () {
  12507. isActive = false;
  12508. toolbarSetup.restore();
  12509. viewportSetup.restore();
  12510. dropupSetup.restore();
  12511. };
  12512. var isExpanding = function () {
  12513. var currentWinHeight = outerWindow.innerHeight;
  12514. var lastWinHeight = getLastWindowSize(viewport);
  12515. return currentWinHeight > lastWinHeight;
  12516. };
  12517. var refresh = function () {
  12518. if (isActive) {
  12519. var newToolbarHeight = get$7(toolbar);
  12520. var dropupHeight_1 = get$7(dropup);
  12521. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12522. set$8(viewport, yFixedData, newToolbarHeight + 'px');
  12523. set$5(viewport, 'height', newHeight + 'px');
  12524. updatePadding(contentBody, viewport, dropup);
  12525. }
  12526. };
  12527. var setViewportOffset = function (newYOffset) {
  12528. var offsetPx = newYOffset + 'px';
  12529. set$8(viewport, yFixedData, offsetPx);
  12530. refresh();
  12531. };
  12532. updatePadding(contentBody, viewport, dropup);
  12533. return {
  12534. setViewportOffset: setViewportOffset,
  12535. isExpanding: isExpanding,
  12536. isShrinking: not(isExpanding),
  12537. refresh: refresh,
  12538. restore: restore
  12539. };
  12540. };
  12541. var animator = create$1();
  12542. var ANIMATION_STEP = 15;
  12543. var NUM_TOP_ANIMATION_FRAMES = 10;
  12544. var ANIMATION_RATE = 10;
  12545. var lastScroll = 'data-' + resolve('last-scroll-top');
  12546. var getTop = function (element) {
  12547. var raw = getRaw(element, 'top').getOr('0');
  12548. return parseInt(raw, 10);
  12549. };
  12550. var getScrollTop = function (element) {
  12551. return parseInt(element.dom.scrollTop, 10);
  12552. };
  12553. var moveScrollAndTop = function (element, destination, finalTop) {
  12554. return Future.nu(function (callback) {
  12555. var getCurrent = curry(getScrollTop, element);
  12556. var update = function (newScroll) {
  12557. element.dom.scrollTop = newScroll;
  12558. set$5(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12559. };
  12560. var finish = function () {
  12561. element.dom.scrollTop = destination;
  12562. set$5(element, 'top', finalTop + 'px');
  12563. callback(destination);
  12564. };
  12565. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12566. });
  12567. };
  12568. var moveOnlyScroll = function (element, destination) {
  12569. return Future.nu(function (callback) {
  12570. var getCurrent = curry(getScrollTop, element);
  12571. set$8(element, lastScroll, getCurrent());
  12572. var update = function (newScroll, abort) {
  12573. var previous = safeParse(element, lastScroll);
  12574. if (previous !== element.dom.scrollTop) {
  12575. abort(element.dom.scrollTop);
  12576. } else {
  12577. element.dom.scrollTop = newScroll;
  12578. set$8(element, lastScroll, newScroll);
  12579. }
  12580. };
  12581. var finish = function () {
  12582. element.dom.scrollTop = destination;
  12583. set$8(element, lastScroll, destination);
  12584. callback(destination);
  12585. };
  12586. var distance = Math.abs(destination - getCurrent());
  12587. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12588. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12589. });
  12590. };
  12591. var moveOnlyTop = function (element, destination) {
  12592. return Future.nu(function (callback) {
  12593. var getCurrent = curry(getTop, element);
  12594. var update = function (newTop) {
  12595. set$5(element, 'top', newTop + 'px');
  12596. };
  12597. var finish = function () {
  12598. update(destination);
  12599. callback(destination);
  12600. };
  12601. var distance = Math.abs(destination - getCurrent());
  12602. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12603. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12604. });
  12605. };
  12606. var updateTop = function (element, amount) {
  12607. var newTop = amount + getYFixedData(element) + 'px';
  12608. set$5(element, 'top', newTop);
  12609. };
  12610. var moveWindowScroll = function (toolbar, viewport, destY) {
  12611. var outerWindow = owner$2(toolbar).dom.defaultView;
  12612. return Future.nu(function (callback) {
  12613. updateTop(toolbar, destY);
  12614. updateTop(viewport, destY);
  12615. outerWindow.scrollTo(0, destY);
  12616. callback(destY);
  12617. });
  12618. };
  12619. function BackgroundActivity (doAction) {
  12620. var action = Cell(LazyValue.pure({}));
  12621. var start = function (value) {
  12622. var future = LazyValue.nu(function (callback) {
  12623. return doAction(value).get(callback);
  12624. });
  12625. action.set(future);
  12626. };
  12627. var idle = function (g) {
  12628. action.get().get(function () {
  12629. g();
  12630. });
  12631. };
  12632. return {
  12633. start: start,
  12634. idle: idle
  12635. };
  12636. }
  12637. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12638. var greenzone = getGreenzone(socket, dropup);
  12639. var refreshCursor = curry(refresh, cWin);
  12640. if (top > greenzone || bottom > greenzone) {
  12641. moveOnlyScroll(socket, socket.dom.scrollTop - greenzone + bottom).get(refreshCursor);
  12642. } else if (top < 0) {
  12643. moveOnlyScroll(socket, socket.dom.scrollTop + top).get(refreshCursor);
  12644. } else ;
  12645. };
  12646. var par$1 = function (asyncValues, nu) {
  12647. return nu(function (callback) {
  12648. var r = [];
  12649. var count = 0;
  12650. var cb = function (i) {
  12651. return function (value) {
  12652. r[i] = value;
  12653. count++;
  12654. if (count >= asyncValues.length) {
  12655. callback(r);
  12656. }
  12657. };
  12658. };
  12659. if (asyncValues.length === 0) {
  12660. callback([]);
  12661. } else {
  12662. each$1(asyncValues, function (asyncValue, i) {
  12663. asyncValue.get(cb(i));
  12664. });
  12665. }
  12666. });
  12667. };
  12668. var par = function (futures) {
  12669. return par$1(futures, Future.nu);
  12670. };
  12671. var updateFixed = function (element, property, winY, offsetY) {
  12672. var destination = winY + offsetY;
  12673. set$5(element, property, destination + 'px');
  12674. return Future.pure(offsetY);
  12675. };
  12676. var updateScrollingFixed = function (element, winY, offsetY) {
  12677. var destTop = winY + offsetY;
  12678. var oldProp = getRaw(element, 'top').getOr(offsetY);
  12679. var delta = destTop - parseInt(oldProp, 10);
  12680. var destScroll = element.dom.scrollTop + delta;
  12681. return moveScrollAndTop(element, destScroll, destTop);
  12682. };
  12683. var updateFixture = function (fixture, winY) {
  12684. return fixture.fold(function (element, property, offsetY) {
  12685. return updateFixed(element, property, winY, offsetY);
  12686. }, function (element, offsetY) {
  12687. return updateScrollingFixed(element, winY, offsetY);
  12688. });
  12689. };
  12690. var updatePositions = function (container, winY) {
  12691. var fixtures = findFixtures(container);
  12692. var updates = map$2(fixtures, function (fixture) {
  12693. return updateFixture(fixture, winY);
  12694. });
  12695. return par(updates);
  12696. };
  12697. var VIEW_MARGIN = 5;
  12698. var register = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  12699. var scroller = BackgroundActivity(function (y) {
  12700. return moveWindowScroll(toolstrip, socket, y);
  12701. });
  12702. var scrollBounds = function () {
  12703. var rects = getRectangles(cWin);
  12704. return Optional.from(rects[0]).bind(function (rect) {
  12705. var viewTop = rect.top - socket.dom.scrollTop;
  12706. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  12707. return outside ? Optional.some({
  12708. top: viewTop,
  12709. bottom: viewTop + rect.height
  12710. }) : Optional.none();
  12711. });
  12712. };
  12713. var scrollThrottle = last(function () {
  12714. scroller.idle(function () {
  12715. updatePositions(container, outerWindow.pageYOffset).get(function () {
  12716. var extraScroll = scrollBounds();
  12717. extraScroll.each(function (extra) {
  12718. socket.dom.scrollTop = socket.dom.scrollTop + extra.top;
  12719. });
  12720. scroller.start(0);
  12721. structure.refresh();
  12722. });
  12723. });
  12724. }, 1000);
  12725. var onScroll = bind(SugarElement.fromDom(outerWindow), 'scroll', function () {
  12726. if (outerWindow.pageYOffset < 0) {
  12727. return;
  12728. }
  12729. scrollThrottle.throttle();
  12730. });
  12731. updatePositions(container, outerWindow.pageYOffset).get(identity);
  12732. return { unbind: onScroll.unbind };
  12733. };
  12734. var setup = function (bag) {
  12735. var cWin = bag.cWin;
  12736. var ceBody = bag.ceBody;
  12737. var socket = bag.socket;
  12738. var toolstrip = bag.toolstrip;
  12739. var contentElement = bag.contentElement;
  12740. var keyboardType = bag.keyboardType;
  12741. var outerWindow = bag.outerWindow;
  12742. var dropup = bag.dropup;
  12743. var outerBody = bag.outerBody;
  12744. var structure = takeover(socket, ceBody, toolstrip, dropup);
  12745. var keyboardModel = keyboardType(outerBody, cWin, body(), contentElement);
  12746. var toEditing = function () {
  12747. keyboardModel.toEditing();
  12748. clearSelection();
  12749. };
  12750. var toReading = function () {
  12751. keyboardModel.toReading();
  12752. };
  12753. var onToolbarTouch = function (_event) {
  12754. keyboardModel.onToolbarTouch();
  12755. };
  12756. var onOrientation = onChange(outerWindow, {
  12757. onChange: noop,
  12758. onReady: structure.refresh
  12759. });
  12760. onOrientation.onAdjustment(function () {
  12761. structure.refresh();
  12762. });
  12763. var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () {
  12764. if (structure.isExpanding()) {
  12765. structure.refresh();
  12766. }
  12767. });
  12768. var onScroll = register(toolstrip, socket, outerBody, outerWindow, structure, cWin);
  12769. var unfocusedSelection = FakeSelection(cWin, contentElement);
  12770. var refreshSelection = function () {
  12771. if (unfocusedSelection.isActive()) {
  12772. unfocusedSelection.update();
  12773. }
  12774. };
  12775. var highlightSelection = function () {
  12776. unfocusedSelection.update();
  12777. };
  12778. var clearSelection = function () {
  12779. unfocusedSelection.clear();
  12780. };
  12781. var scrollIntoView$1 = function (top, bottom) {
  12782. scrollIntoView(cWin, socket, dropup, top, bottom);
  12783. };
  12784. var syncHeight = function () {
  12785. set$5(contentElement, 'height', contentElement.dom.contentWindow.document.body.scrollHeight + 'px');
  12786. };
  12787. var setViewportOffset = function (newYOffset) {
  12788. structure.setViewportOffset(newYOffset);
  12789. moveOnlyTop(socket, newYOffset).get(identity);
  12790. };
  12791. var destroy = function () {
  12792. structure.restore();
  12793. onOrientation.destroy();
  12794. onScroll.unbind();
  12795. onResize.unbind();
  12796. keyboardModel.destroy();
  12797. unfocusedSelection.destroy();
  12798. input(body(), blur$1);
  12799. };
  12800. return {
  12801. toEditing: toEditing,
  12802. toReading: toReading,
  12803. onToolbarTouch: onToolbarTouch,
  12804. refreshSelection: refreshSelection,
  12805. clearSelection: clearSelection,
  12806. highlightSelection: highlightSelection,
  12807. scrollIntoView: scrollIntoView$1,
  12808. updateToolbarPadding: noop,
  12809. setViewportOffset: setViewportOffset,
  12810. syncHeight: syncHeight,
  12811. refreshStructure: structure.refresh,
  12812. destroy: destroy
  12813. };
  12814. };
  12815. var create = function (platform, mask) {
  12816. var meta = tag();
  12817. var priorState = value();
  12818. var scrollEvents = value();
  12819. var iosApi = api$2();
  12820. var iosEvents = api$2();
  12821. var enter = function () {
  12822. mask.hide();
  12823. var doc = SugarElement.fromDom(document);
  12824. getActiveApi(platform.editor).each(function (editorApi) {
  12825. priorState.set({
  12826. socketHeight: getRaw(platform.socket, 'height'),
  12827. iframeHeight: getRaw(editorApi.frame, 'height'),
  12828. outerScroll: document.body.scrollTop
  12829. });
  12830. scrollEvents.set({ exclusives: exclusive(doc, '.' + scrollable) });
  12831. add$1(platform.container, resolve('fullscreen-maximized'));
  12832. clobberStyles(platform.container, editorApi.body);
  12833. meta.maximize();
  12834. set$5(platform.socket, 'overflow', 'scroll');
  12835. set$5(platform.socket, '-webkit-overflow-scrolling', 'touch');
  12836. focus$3(editorApi.body);
  12837. iosApi.set(setup({
  12838. cWin: editorApi.win,
  12839. ceBody: editorApi.body,
  12840. socket: platform.socket,
  12841. toolstrip: platform.toolstrip,
  12842. dropup: platform.dropup.element,
  12843. contentElement: editorApi.frame,
  12844. outerBody: platform.body,
  12845. outerWindow: platform.win,
  12846. keyboardType: stubborn
  12847. }));
  12848. iosApi.run(function (api) {
  12849. api.syncHeight();
  12850. });
  12851. iosEvents.set(initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  12852. });
  12853. };
  12854. var exit = function () {
  12855. meta.restore();
  12856. iosEvents.clear();
  12857. iosApi.clear();
  12858. mask.show();
  12859. priorState.on(function (s) {
  12860. s.socketHeight.each(function (h) {
  12861. set$5(platform.socket, 'height', h);
  12862. });
  12863. s.iframeHeight.each(function (h) {
  12864. set$5(platform.editor.getFrame(), 'height', h);
  12865. });
  12866. document.body.scrollTop = s.scrollTop;
  12867. });
  12868. priorState.clear();
  12869. scrollEvents.on(function (s) {
  12870. s.exclusives.unbind();
  12871. });
  12872. scrollEvents.clear();
  12873. remove$3(platform.container, resolve('fullscreen-maximized'));
  12874. restoreStyles();
  12875. deregister(platform.toolbar);
  12876. remove$2(platform.socket, 'overflow');
  12877. remove$2(platform.socket, '-webkit-overflow-scrolling');
  12878. blur$1(platform.editor.getFrame());
  12879. getActiveApi(platform.editor).each(function (editorApi) {
  12880. editorApi.clearSelection();
  12881. });
  12882. };
  12883. var refreshStructure = function () {
  12884. iosApi.run(function (api) {
  12885. api.refreshStructure();
  12886. });
  12887. };
  12888. return {
  12889. enter: enter,
  12890. refreshStructure: refreshStructure,
  12891. exit: exit
  12892. };
  12893. };
  12894. var produce = function (raw) {
  12895. var mobile = asRawOrDie$1('Getting IosWebapp schema', MobileSchema, raw);
  12896. set$5(mobile.toolstrip, 'width', '100%');
  12897. set$5(mobile.container, 'position', 'relative');
  12898. var onView = function () {
  12899. mobile.setReadOnly(mobile.readOnlyOnInit());
  12900. mode.enter();
  12901. };
  12902. var mask = build$1(sketch(onView, mobile.translate));
  12903. mobile.alloy.add(mask);
  12904. var maskApi = {
  12905. show: function () {
  12906. mobile.alloy.add(mask);
  12907. },
  12908. hide: function () {
  12909. mobile.alloy.remove(mask);
  12910. }
  12911. };
  12912. var mode = create(mobile, maskApi);
  12913. return {
  12914. setReadOnly: mobile.setReadOnly,
  12915. refreshStructure: mode.refreshStructure,
  12916. enter: mode.enter,
  12917. exit: mode.exit,
  12918. destroy: noop
  12919. };
  12920. };
  12921. function IosRealm (scrollIntoView) {
  12922. var alloy = OuterContainer({ classes: [resolve('ios-container')] });
  12923. var toolbar = ScrollingToolbar();
  12924. var webapp = api$2();
  12925. var switchToEdit = makeEditSwitch(webapp);
  12926. var socket = makeSocket();
  12927. var dropup = build(function () {
  12928. webapp.run(function (w) {
  12929. w.refreshStructure();
  12930. });
  12931. }, scrollIntoView);
  12932. alloy.add(toolbar.wrapper);
  12933. alloy.add(socket);
  12934. alloy.add(dropup.component);
  12935. var setToolbarGroups = function (rawGroups) {
  12936. var groups = toolbar.createGroups(rawGroups);
  12937. toolbar.setGroups(groups);
  12938. };
  12939. var setContextToolbar = function (rawGroups) {
  12940. var groups = toolbar.createGroups(rawGroups);
  12941. toolbar.setContextToolbar(groups);
  12942. };
  12943. var focusToolbar = function () {
  12944. toolbar.focus();
  12945. };
  12946. var restoreToolbar = function () {
  12947. toolbar.restoreToolbar();
  12948. };
  12949. var init = function (spec) {
  12950. webapp.set(produce(spec));
  12951. };
  12952. var exit = function () {
  12953. webapp.run(function (w) {
  12954. Replacing.remove(socket, switchToEdit);
  12955. w.exit();
  12956. });
  12957. };
  12958. var updateMode$1 = function (readOnly) {
  12959. updateMode(socket, switchToEdit, readOnly, alloy.root);
  12960. };
  12961. return {
  12962. system: alloy,
  12963. element: alloy.element,
  12964. init: init,
  12965. exit: exit,
  12966. setToolbarGroups: setToolbarGroups,
  12967. setContextToolbar: setContextToolbar,
  12968. focusToolbar: focusToolbar,
  12969. restoreToolbar: restoreToolbar,
  12970. updateMode: updateMode$1,
  12971. socket: socket,
  12972. dropup: dropup
  12973. };
  12974. }
  12975. var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12976. var derive = function (editor) {
  12977. var base = Optional.from(getSkinUrl(editor)).getOrThunk(function () {
  12978. return global$1.baseURL + '/skins/ui/oxide';
  12979. });
  12980. return {
  12981. content: base + '/content.mobile.min.css',
  12982. ui: base + '/skin.mobile.min.css'
  12983. };
  12984. };
  12985. var fireChange = function (realm, command, state) {
  12986. realm.system.broadcastOn([formatChanged], {
  12987. command: command,
  12988. state: state
  12989. });
  12990. };
  12991. var init = function (realm, editor) {
  12992. var allFormats = keys(editor.formatter.get());
  12993. each$1(allFormats, function (command) {
  12994. editor.formatter.formatChanged(command, function (state) {
  12995. fireChange(realm, command, state);
  12996. });
  12997. });
  12998. each$1([
  12999. 'ul',
  13000. 'ol'
  13001. ], function (command) {
  13002. editor.selection.selectorChanged(command, function (state, _data) {
  13003. fireChange(realm, command, state);
  13004. });
  13005. });
  13006. };
  13007. var fireSkinLoaded = function (editor) {
  13008. return function () {
  13009. var done = function () {
  13010. editor._skinLoaded = true;
  13011. editor.fire('SkinLoaded');
  13012. };
  13013. if (editor.initialized) {
  13014. done();
  13015. } else {
  13016. editor.on('init', done);
  13017. }
  13018. };
  13019. };
  13020. var READING = 'toReading';
  13021. var EDITING = 'toEditing';
  13022. var renderMobileTheme = function (editor) {
  13023. var renderUI = function () {
  13024. var targetNode = editor.getElement();
  13025. var cssUrls = derive(editor);
  13026. if (isSkinDisabled(editor) === false) {
  13027. var styleSheetLoader_1 = global$5.DOM.styleSheetLoader;
  13028. editor.contentCSS.push(cssUrls.content);
  13029. styleSheetLoader_1.load(cssUrls.ui, fireSkinLoaded(editor));
  13030. editor.on('remove', function () {
  13031. return styleSheetLoader_1.unload(cssUrls.ui);
  13032. });
  13033. } else {
  13034. fireSkinLoaded(editor)();
  13035. }
  13036. var doScrollIntoView = function () {
  13037. editor.fire('ScrollIntoView');
  13038. };
  13039. var realm = detect$1().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  13040. var original = SugarElement.fromDom(targetNode);
  13041. attachSystemAfter(original, realm.system);
  13042. var findFocusIn = function (elem) {
  13043. return search(elem).bind(function (focused) {
  13044. return realm.system.getByDom(focused).toOptional();
  13045. });
  13046. };
  13047. var outerWindow = targetNode.ownerDocument.defaultView;
  13048. var orientation = onChange(outerWindow, {
  13049. onChange: function () {
  13050. var alloy = realm.system;
  13051. alloy.broadcastOn([orientationChanged], { width: getActualWidth(outerWindow) });
  13052. },
  13053. onReady: noop
  13054. });
  13055. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  13056. if (ro === false) {
  13057. editor.selection.collapse();
  13058. }
  13059. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  13060. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  13061. editor.setMode(ro === true ? 'readonly' : 'design');
  13062. editor.fire(ro === true ? READING : EDITING);
  13063. realm.updateMode(ro);
  13064. };
  13065. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  13066. var dynamic = dynamicGroup.get();
  13067. var toolbars = {
  13068. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  13069. main: dynamic.backToMask.concat(mainGroups.get())
  13070. };
  13071. return toolbars;
  13072. };
  13073. var bindHandler = function (label, handler) {
  13074. editor.on(label, handler);
  13075. return {
  13076. unbind: function () {
  13077. editor.off(label);
  13078. }
  13079. };
  13080. };
  13081. editor.on('init', function () {
  13082. realm.init({
  13083. editor: {
  13084. getFrame: function () {
  13085. return SugarElement.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  13086. },
  13087. onDomChanged: function () {
  13088. return { unbind: noop };
  13089. },
  13090. onToReading: function (handler) {
  13091. return bindHandler(READING, handler);
  13092. },
  13093. onToEditing: function (handler) {
  13094. return bindHandler(EDITING, handler);
  13095. },
  13096. onScrollToCursor: function (handler) {
  13097. editor.on('ScrollIntoView', function (tinyEvent) {
  13098. handler(tinyEvent);
  13099. });
  13100. var unbind = function () {
  13101. editor.off('ScrollIntoView');
  13102. orientation.destroy();
  13103. };
  13104. return { unbind: unbind };
  13105. },
  13106. onTouchToolstrip: function () {
  13107. hideDropup();
  13108. },
  13109. onTouchContent: function () {
  13110. var toolbar = SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar')));
  13111. findFocusIn(toolbar).each(emitExecute);
  13112. realm.restoreToolbar();
  13113. hideDropup();
  13114. },
  13115. onTapContent: function (evt) {
  13116. var target = evt.target;
  13117. if (name$1(target) === 'img') {
  13118. editor.selection.select(target.dom);
  13119. evt.kill();
  13120. } else if (name$1(target) === 'a') {
  13121. var component = realm.system.getByDom(SugarElement.fromDom(editor.editorContainer));
  13122. component.each(function (container) {
  13123. if (Swapping.isAlpha(container)) {
  13124. openLink(target.dom);
  13125. }
  13126. });
  13127. }
  13128. }
  13129. },
  13130. container: SugarElement.fromDom(editor.editorContainer),
  13131. socket: SugarElement.fromDom(editor.contentAreaContainer),
  13132. toolstrip: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolstrip'))),
  13133. toolbar: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))),
  13134. dropup: realm.dropup,
  13135. alloy: realm.system,
  13136. translate: noop,
  13137. setReadOnly: function (ro) {
  13138. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  13139. },
  13140. readOnlyOnInit: function () {
  13141. return readOnlyOnInit();
  13142. }
  13143. });
  13144. var hideDropup = function () {
  13145. realm.dropup.disappear(function () {
  13146. realm.system.broadcastOn([dropupDismissed], {});
  13147. });
  13148. };
  13149. var backToMaskGroup = {
  13150. label: 'The first group',
  13151. scrollable: false,
  13152. items: [forToolbar('back', function () {
  13153. editor.selection.collapse();
  13154. realm.exit();
  13155. }, {}, editor)]
  13156. };
  13157. var backToReadOnlyGroup = {
  13158. label: 'Back to read only',
  13159. scrollable: false,
  13160. items: [forToolbar('readonly-back', function () {
  13161. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  13162. }, {}, editor)]
  13163. };
  13164. var readOnlyGroup = {
  13165. label: 'The read only mode group',
  13166. scrollable: true,
  13167. items: []
  13168. };
  13169. var features = setup$3(realm, editor);
  13170. var items = detect(editor, features);
  13171. var actionGroup = {
  13172. label: 'the action group',
  13173. scrollable: true,
  13174. items: items
  13175. };
  13176. var extraGroup = {
  13177. label: 'The extra group',
  13178. scrollable: false,
  13179. items: []
  13180. };
  13181. var mainGroups = Cell([
  13182. actionGroup,
  13183. extraGroup
  13184. ]);
  13185. var readOnlyGroups = Cell([
  13186. readOnlyGroup,
  13187. extraGroup
  13188. ]);
  13189. var dynamicGroup = Cell({
  13190. backToMask: [backToMaskGroup],
  13191. backToReadOnly: [backToReadOnlyGroup]
  13192. });
  13193. init(realm, editor);
  13194. });
  13195. editor.on('remove', function () {
  13196. realm.exit();
  13197. });
  13198. editor.on('detach', function () {
  13199. detachSystem(realm.system);
  13200. realm.system.destroy();
  13201. });
  13202. return {
  13203. iframeContainer: realm.socket.element.dom,
  13204. editorContainer: realm.element.dom
  13205. };
  13206. };
  13207. return {
  13208. getNotificationManagerImpl: function () {
  13209. return {
  13210. open: constant$1({
  13211. progressBar: { value: noop },
  13212. close: noop,
  13213. text: noop,
  13214. getEl: constant$1(null),
  13215. moveTo: noop,
  13216. moveRel: noop,
  13217. settings: {}
  13218. }),
  13219. close: noop,
  13220. reposition: noop,
  13221. getArgs: constant$1({})
  13222. };
  13223. },
  13224. renderUI: renderUI
  13225. };
  13226. };
  13227. function Theme () {
  13228. global$4.add('mobile', renderMobileTheme);
  13229. }
  13230. Theme();
  13231. }());