theme.js 444 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578
  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.5.1 (2020-10-01)
  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 __spreadArrays() {
  36. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  37. s += arguments[i].length;
  38. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  39. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  40. r[k] = a[j];
  41. return r;
  42. }
  43. var noop = function () {
  44. };
  45. var compose = function (fa, fb) {
  46. return function () {
  47. var args = [];
  48. for (var _i = 0; _i < arguments.length; _i++) {
  49. args[_i] = arguments[_i];
  50. }
  51. return fa(fb.apply(null, args));
  52. };
  53. };
  54. var compose1 = function (fbc, fab) {
  55. return function (a) {
  56. return fbc(fab(a));
  57. };
  58. };
  59. var constant = function (value) {
  60. return function () {
  61. return value;
  62. };
  63. };
  64. var identity = function (x) {
  65. return x;
  66. };
  67. function curry(fn) {
  68. var initialArgs = [];
  69. for (var _i = 1; _i < arguments.length; _i++) {
  70. initialArgs[_i - 1] = arguments[_i];
  71. }
  72. return function () {
  73. var restArgs = [];
  74. for (var _i = 0; _i < arguments.length; _i++) {
  75. restArgs[_i] = arguments[_i];
  76. }
  77. var all = initialArgs.concat(restArgs);
  78. return fn.apply(null, all);
  79. };
  80. }
  81. var not = function (f) {
  82. return function (t) {
  83. return !f(t);
  84. };
  85. };
  86. var die = function (msg) {
  87. return function () {
  88. throw new Error(msg);
  89. };
  90. };
  91. var apply = function (f) {
  92. return f();
  93. };
  94. var never = constant(false);
  95. var always = constant(true);
  96. var cached = function (f) {
  97. var called = false;
  98. var r;
  99. return function () {
  100. var args = [];
  101. for (var _i = 0; _i < arguments.length; _i++) {
  102. args[_i] = arguments[_i];
  103. }
  104. if (!called) {
  105. called = true;
  106. r = f.apply(null, args);
  107. }
  108. return r;
  109. };
  110. };
  111. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  112. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  113. var isiPhone = os.isiOS() && !isiPad;
  114. var isMobile = os.isiOS() || os.isAndroid();
  115. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  116. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  117. var isPhone = isiPhone || isMobile && !isTablet;
  118. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  119. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  120. return {
  121. isiPad: constant(isiPad),
  122. isiPhone: constant(isiPhone),
  123. isTablet: constant(isTablet),
  124. isPhone: constant(isPhone),
  125. isTouch: constant(isTouch),
  126. isAndroid: os.isAndroid,
  127. isiOS: os.isiOS,
  128. isWebView: constant(iOSwebview),
  129. isDesktop: constant(isDesktop)
  130. };
  131. };
  132. var none = function () {
  133. return NONE;
  134. };
  135. var NONE = function () {
  136. var eq = function (o) {
  137. return o.isNone();
  138. };
  139. var call = function (thunk) {
  140. return thunk();
  141. };
  142. var id = function (n) {
  143. return n;
  144. };
  145. var me = {
  146. fold: function (n, _s) {
  147. return n();
  148. },
  149. is: never,
  150. isSome: never,
  151. isNone: always,
  152. getOr: id,
  153. getOrThunk: call,
  154. getOrDie: function (msg) {
  155. throw new Error(msg || 'error: getOrDie called on none.');
  156. },
  157. getOrNull: constant(null),
  158. getOrUndefined: constant(undefined),
  159. or: id,
  160. orThunk: call,
  161. map: none,
  162. each: noop,
  163. bind: none,
  164. exists: never,
  165. forall: always,
  166. filter: none,
  167. equals: eq,
  168. equals_: eq,
  169. toArray: function () {
  170. return [];
  171. },
  172. toString: constant('none()')
  173. };
  174. return me;
  175. }();
  176. var some = function (a) {
  177. var constant_a = constant(a);
  178. var self = function () {
  179. return me;
  180. };
  181. var bind = function (f) {
  182. return f(a);
  183. };
  184. var me = {
  185. fold: function (n, s) {
  186. return s(a);
  187. },
  188. is: function (v) {
  189. return a === v;
  190. },
  191. isSome: always,
  192. isNone: never,
  193. getOr: constant_a,
  194. getOrThunk: constant_a,
  195. getOrDie: constant_a,
  196. getOrNull: constant_a,
  197. getOrUndefined: constant_a,
  198. or: self,
  199. orThunk: self,
  200. map: function (f) {
  201. return some(f(a));
  202. },
  203. each: function (f) {
  204. f(a);
  205. },
  206. bind: bind,
  207. exists: bind,
  208. forall: bind,
  209. filter: function (f) {
  210. return f(a) ? me : NONE;
  211. },
  212. toArray: function () {
  213. return [a];
  214. },
  215. toString: function () {
  216. return 'some(' + a + ')';
  217. },
  218. equals: function (o) {
  219. return o.is(a);
  220. },
  221. equals_: function (o, elementEq) {
  222. return o.fold(never, function (b) {
  223. return elementEq(a, b);
  224. });
  225. }
  226. };
  227. return me;
  228. };
  229. var from = function (value) {
  230. return value === null || value === undefined ? NONE : some(value);
  231. };
  232. var Optional = {
  233. some: some,
  234. none: none,
  235. from: from
  236. };
  237. var typeOf = function (x) {
  238. var t = typeof x;
  239. if (x === null) {
  240. return 'null';
  241. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  242. return 'array';
  243. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  244. return 'string';
  245. } else {
  246. return t;
  247. }
  248. };
  249. var isType = function (type) {
  250. return function (value) {
  251. return typeOf(value) === type;
  252. };
  253. };
  254. var isSimpleType = function (type) {
  255. return function (value) {
  256. return typeof value === type;
  257. };
  258. };
  259. var isString = isType('string');
  260. var isObject = isType('object');
  261. var isArray = isType('array');
  262. var isBoolean = isSimpleType('boolean');
  263. var isNullable = function (a) {
  264. return a === null || a === undefined;
  265. };
  266. var isNonNullable = function (a) {
  267. return !isNullable(a);
  268. };
  269. var isFunction = isSimpleType('function');
  270. var isNumber = isSimpleType('number');
  271. var nativeSlice = Array.prototype.slice;
  272. var nativeIndexOf = Array.prototype.indexOf;
  273. var nativePush = Array.prototype.push;
  274. var rawIndexOf = function (ts, t) {
  275. return nativeIndexOf.call(ts, t);
  276. };
  277. var contains = function (xs, x) {
  278. return rawIndexOf(xs, x) > -1;
  279. };
  280. var exists = function (xs, pred) {
  281. for (var i = 0, len = xs.length; i < len; i++) {
  282. var x = xs[i];
  283. if (pred(x, i)) {
  284. return true;
  285. }
  286. }
  287. return false;
  288. };
  289. var map = function (xs, f) {
  290. var len = xs.length;
  291. var r = new Array(len);
  292. for (var i = 0; i < len; i++) {
  293. var x = xs[i];
  294. r[i] = f(x, i);
  295. }
  296. return r;
  297. };
  298. var each = function (xs, f) {
  299. for (var i = 0, len = xs.length; i < len; i++) {
  300. var x = xs[i];
  301. f(x, i);
  302. }
  303. };
  304. var eachr = function (xs, f) {
  305. for (var i = xs.length - 1; i >= 0; i--) {
  306. var x = xs[i];
  307. f(x, i);
  308. }
  309. };
  310. var filter = function (xs, pred) {
  311. var r = [];
  312. for (var i = 0, len = xs.length; i < len; i++) {
  313. var x = xs[i];
  314. if (pred(x, i)) {
  315. r.push(x);
  316. }
  317. }
  318. return r;
  319. };
  320. var foldr = function (xs, f, acc) {
  321. eachr(xs, function (x) {
  322. acc = f(acc, x);
  323. });
  324. return acc;
  325. };
  326. var foldl = function (xs, f, acc) {
  327. each(xs, function (x) {
  328. acc = f(acc, x);
  329. });
  330. return acc;
  331. };
  332. var findUntil = function (xs, pred, until) {
  333. for (var i = 0, len = xs.length; i < len; i++) {
  334. var x = xs[i];
  335. if (pred(x, i)) {
  336. return Optional.some(x);
  337. } else if (until(x, i)) {
  338. break;
  339. }
  340. }
  341. return Optional.none();
  342. };
  343. var find = function (xs, pred) {
  344. return findUntil(xs, pred, never);
  345. };
  346. var findIndex = function (xs, pred) {
  347. for (var i = 0, len = xs.length; i < len; i++) {
  348. var x = xs[i];
  349. if (pred(x, i)) {
  350. return Optional.some(i);
  351. }
  352. }
  353. return Optional.none();
  354. };
  355. var flatten = function (xs) {
  356. var r = [];
  357. for (var i = 0, len = xs.length; i < len; ++i) {
  358. if (!isArray(xs[i])) {
  359. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  360. }
  361. nativePush.apply(r, xs[i]);
  362. }
  363. return r;
  364. };
  365. var bind = function (xs, f) {
  366. return flatten(map(xs, f));
  367. };
  368. var forall = function (xs, pred) {
  369. for (var i = 0, len = xs.length; i < len; ++i) {
  370. var x = xs[i];
  371. if (pred(x, i) !== true) {
  372. return false;
  373. }
  374. }
  375. return true;
  376. };
  377. var reverse = function (xs) {
  378. var r = nativeSlice.call(xs, 0);
  379. r.reverse();
  380. return r;
  381. };
  382. var difference = function (a1, a2) {
  383. return filter(a1, function (x) {
  384. return !contains(a2, x);
  385. });
  386. };
  387. var pure = function (x) {
  388. return [x];
  389. };
  390. var sort = function (xs, comparator) {
  391. var copy = nativeSlice.call(xs, 0);
  392. copy.sort(comparator);
  393. return copy;
  394. };
  395. var head = function (xs) {
  396. return xs.length === 0 ? Optional.none() : Optional.some(xs[0]);
  397. };
  398. var findMap = function (arr, f) {
  399. for (var i = 0; i < arr.length; i++) {
  400. var r = f(arr[i], i);
  401. if (r.isSome()) {
  402. return r;
  403. }
  404. }
  405. return Optional.none();
  406. };
  407. var firstMatch = function (regexes, s) {
  408. for (var i = 0; i < regexes.length; i++) {
  409. var x = regexes[i];
  410. if (x.test(s)) {
  411. return x;
  412. }
  413. }
  414. return undefined;
  415. };
  416. var find$1 = function (regexes, agent) {
  417. var r = firstMatch(regexes, agent);
  418. if (!r) {
  419. return {
  420. major: 0,
  421. minor: 0
  422. };
  423. }
  424. var group = function (i) {
  425. return Number(agent.replace(r, '$' + i));
  426. };
  427. return nu(group(1), group(2));
  428. };
  429. var detect = function (versionRegexes, agent) {
  430. var cleanedAgent = String(agent).toLowerCase();
  431. if (versionRegexes.length === 0) {
  432. return unknown();
  433. }
  434. return find$1(versionRegexes, cleanedAgent);
  435. };
  436. var unknown = function () {
  437. return nu(0, 0);
  438. };
  439. var nu = function (major, minor) {
  440. return {
  441. major: major,
  442. minor: minor
  443. };
  444. };
  445. var Version = {
  446. nu: nu,
  447. detect: detect,
  448. unknown: unknown
  449. };
  450. var detect$1 = function (candidates, userAgent) {
  451. var agent = String(userAgent).toLowerCase();
  452. return find(candidates, function (candidate) {
  453. return candidate.search(agent);
  454. });
  455. };
  456. var detectBrowser = function (browsers, userAgent) {
  457. return detect$1(browsers, userAgent).map(function (browser) {
  458. var version = Version.detect(browser.versionRegexes, userAgent);
  459. return {
  460. current: browser.name,
  461. version: version
  462. };
  463. });
  464. };
  465. var detectOs = function (oses, userAgent) {
  466. return detect$1(oses, userAgent).map(function (os) {
  467. var version = Version.detect(os.versionRegexes, userAgent);
  468. return {
  469. current: os.name,
  470. version: version
  471. };
  472. });
  473. };
  474. var UaString = {
  475. detectBrowser: detectBrowser,
  476. detectOs: detectOs
  477. };
  478. var checkRange = function (str, substr, start) {
  479. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  480. };
  481. var supplant = function (str, obj) {
  482. var isStringOrNumber = function (a) {
  483. var t = typeof a;
  484. return t === 'string' || t === 'number';
  485. };
  486. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  487. var value = obj[key];
  488. return isStringOrNumber(value) ? value.toString() : fullMatch;
  489. });
  490. };
  491. var contains$1 = function (str, substr) {
  492. return str.indexOf(substr) !== -1;
  493. };
  494. var endsWith = function (str, suffix) {
  495. return checkRange(str, suffix, str.length - suffix.length);
  496. };
  497. var blank = function (r) {
  498. return function (s) {
  499. return s.replace(r, '');
  500. };
  501. };
  502. var trim = blank(/^\s+|\s+$/g);
  503. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  504. var checkContains = function (target) {
  505. return function (uastring) {
  506. return contains$1(uastring, target);
  507. };
  508. };
  509. var browsers = [
  510. {
  511. name: 'Edge',
  512. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  513. search: function (uastring) {
  514. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  515. }
  516. },
  517. {
  518. name: 'Chrome',
  519. versionRegexes: [
  520. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  521. normalVersionRegex
  522. ],
  523. search: function (uastring) {
  524. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  525. }
  526. },
  527. {
  528. name: 'IE',
  529. versionRegexes: [
  530. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  531. /.*?rv:([0-9]+)\.([0-9]+).*/
  532. ],
  533. search: function (uastring) {
  534. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  535. }
  536. },
  537. {
  538. name: 'Opera',
  539. versionRegexes: [
  540. normalVersionRegex,
  541. /.*?opera\/([0-9]+)\.([0-9]+).*/
  542. ],
  543. search: checkContains('opera')
  544. },
  545. {
  546. name: 'Firefox',
  547. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  548. search: checkContains('firefox')
  549. },
  550. {
  551. name: 'Safari',
  552. versionRegexes: [
  553. normalVersionRegex,
  554. /.*?cpu os ([0-9]+)_([0-9]+).*/
  555. ],
  556. search: function (uastring) {
  557. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  558. }
  559. }
  560. ];
  561. var oses = [
  562. {
  563. name: 'Windows',
  564. search: checkContains('win'),
  565. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  566. },
  567. {
  568. name: 'iOS',
  569. search: function (uastring) {
  570. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  571. },
  572. versionRegexes: [
  573. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  574. /.*cpu os ([0-9]+)_([0-9]+).*/,
  575. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  576. ]
  577. },
  578. {
  579. name: 'Android',
  580. search: checkContains('android'),
  581. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  582. },
  583. {
  584. name: 'OSX',
  585. search: checkContains('mac os x'),
  586. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  587. },
  588. {
  589. name: 'Linux',
  590. search: checkContains('linux'),
  591. versionRegexes: []
  592. },
  593. {
  594. name: 'Solaris',
  595. search: checkContains('sunos'),
  596. versionRegexes: []
  597. },
  598. {
  599. name: 'FreeBSD',
  600. search: checkContains('freebsd'),
  601. versionRegexes: []
  602. },
  603. {
  604. name: 'ChromeOS',
  605. search: checkContains('cros'),
  606. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  607. }
  608. ];
  609. var PlatformInfo = {
  610. browsers: constant(browsers),
  611. oses: constant(oses)
  612. };
  613. var edge = 'Edge';
  614. var chrome = 'Chrome';
  615. var ie = 'IE';
  616. var opera = 'Opera';
  617. var firefox = 'Firefox';
  618. var safari = 'Safari';
  619. var unknown$1 = function () {
  620. return nu$1({
  621. current: undefined,
  622. version: Version.unknown()
  623. });
  624. };
  625. var nu$1 = function (info) {
  626. var current = info.current;
  627. var version = info.version;
  628. var isBrowser = function (name) {
  629. return function () {
  630. return current === name;
  631. };
  632. };
  633. return {
  634. current: current,
  635. version: version,
  636. isEdge: isBrowser(edge),
  637. isChrome: isBrowser(chrome),
  638. isIE: isBrowser(ie),
  639. isOpera: isBrowser(opera),
  640. isFirefox: isBrowser(firefox),
  641. isSafari: isBrowser(safari)
  642. };
  643. };
  644. var Browser = {
  645. unknown: unknown$1,
  646. nu: nu$1,
  647. edge: constant(edge),
  648. chrome: constant(chrome),
  649. ie: constant(ie),
  650. opera: constant(opera),
  651. firefox: constant(firefox),
  652. safari: constant(safari)
  653. };
  654. var windows = 'Windows';
  655. var ios = 'iOS';
  656. var android = 'Android';
  657. var linux = 'Linux';
  658. var osx = 'OSX';
  659. var solaris = 'Solaris';
  660. var freebsd = 'FreeBSD';
  661. var chromeos = 'ChromeOS';
  662. var unknown$2 = function () {
  663. return nu$2({
  664. current: undefined,
  665. version: Version.unknown()
  666. });
  667. };
  668. var nu$2 = function (info) {
  669. var current = info.current;
  670. var version = info.version;
  671. var isOS = function (name) {
  672. return function () {
  673. return current === name;
  674. };
  675. };
  676. return {
  677. current: current,
  678. version: version,
  679. isWindows: isOS(windows),
  680. isiOS: isOS(ios),
  681. isAndroid: isOS(android),
  682. isOSX: isOS(osx),
  683. isLinux: isOS(linux),
  684. isSolaris: isOS(solaris),
  685. isFreeBSD: isOS(freebsd),
  686. isChromeOS: isOS(chromeos)
  687. };
  688. };
  689. var OperatingSystem = {
  690. unknown: unknown$2,
  691. nu: nu$2,
  692. windows: constant(windows),
  693. ios: constant(ios),
  694. android: constant(android),
  695. linux: constant(linux),
  696. osx: constant(osx),
  697. solaris: constant(solaris),
  698. freebsd: constant(freebsd),
  699. chromeos: constant(chromeos)
  700. };
  701. var detect$2 = function (userAgent, mediaMatch) {
  702. var browsers = PlatformInfo.browsers();
  703. var oses = PlatformInfo.oses();
  704. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  705. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  706. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  707. return {
  708. browser: browser,
  709. os: os,
  710. deviceType: deviceType
  711. };
  712. };
  713. var PlatformDetection = { detect: detect$2 };
  714. var mediaMatch = function (query) {
  715. return window.matchMedia(query).matches;
  716. };
  717. var platform = cached(function () {
  718. return PlatformDetection.detect(navigator.userAgent, mediaMatch);
  719. });
  720. var detect$3 = function () {
  721. return platform();
  722. };
  723. var constant$1 = constant;
  724. var touchstart = constant$1('touchstart');
  725. var touchmove = constant$1('touchmove');
  726. var touchend = constant$1('touchend');
  727. var mousedown = constant$1('mousedown');
  728. var mousemove = constant$1('mousemove');
  729. var mouseup = constant$1('mouseup');
  730. var mouseover = constant$1('mouseover');
  731. var keydown = constant$1('keydown');
  732. var keyup = constant$1('keyup');
  733. var input = constant$1('input');
  734. var change = constant$1('change');
  735. var click = constant$1('click');
  736. var transitionend = constant$1('transitionend');
  737. var selectstart = constant$1('selectstart');
  738. var prefixName = function (name) {
  739. return constant('alloy.' + name);
  740. };
  741. var alloy = { tap: prefixName('tap') };
  742. var focus = prefixName('focus');
  743. var postBlur = prefixName('blur.post');
  744. var postPaste = prefixName('paste.post');
  745. var receive = prefixName('receive');
  746. var execute = prefixName('execute');
  747. var focusItem = prefixName('focus.item');
  748. var tap = alloy.tap;
  749. var longpress = prefixName('longpress');
  750. var systemInit = prefixName('system.init');
  751. var attachedToDom = prefixName('system.attached');
  752. var detachedFromDom = prefixName('system.detached');
  753. var focusShifted = prefixName('focusmanager.shifted');
  754. var highlight = prefixName('highlight');
  755. var dehighlight = prefixName('dehighlight');
  756. var emit = function (component, event) {
  757. dispatchWith(component, component.element, event, {});
  758. };
  759. var emitWith = function (component, event, properties) {
  760. dispatchWith(component, component.element, event, properties);
  761. };
  762. var emitExecute = function (component) {
  763. emit(component, execute());
  764. };
  765. var dispatch = function (component, target, event) {
  766. dispatchWith(component, target, event, {});
  767. };
  768. var dispatchWith = function (component, target, event, properties) {
  769. var data = __assign({ target: target }, properties);
  770. component.getSystem().triggerEvent(event, target, data);
  771. };
  772. var dispatchEvent = function (component, target, event, simulatedEvent) {
  773. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  774. };
  775. var dispatchFocus = function (component, target) {
  776. component.getSystem().triggerFocus(target, component.element);
  777. };
  778. var DOCUMENT = 9;
  779. var DOCUMENT_FRAGMENT = 11;
  780. var ELEMENT = 1;
  781. var TEXT = 3;
  782. var fromHtml = function (html, scope) {
  783. var doc = scope || document;
  784. var div = doc.createElement('div');
  785. div.innerHTML = html;
  786. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  787. console.error('HTML does not have a single root node', html);
  788. throw new Error('HTML must have a single root node');
  789. }
  790. return fromDom(div.childNodes[0]);
  791. };
  792. var fromTag = function (tag, scope) {
  793. var doc = scope || document;
  794. var node = doc.createElement(tag);
  795. return fromDom(node);
  796. };
  797. var fromText = function (text, scope) {
  798. var doc = scope || document;
  799. var node = doc.createTextNode(text);
  800. return fromDom(node);
  801. };
  802. var fromDom = function (node) {
  803. if (node === null || node === undefined) {
  804. throw new Error('Node cannot be null or undefined');
  805. }
  806. return { dom: node };
  807. };
  808. var fromPoint = function (docElm, x, y) {
  809. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  810. };
  811. var SugarElement = {
  812. fromHtml: fromHtml,
  813. fromTag: fromTag,
  814. fromText: fromText,
  815. fromDom: fromDom,
  816. fromPoint: fromPoint
  817. };
  818. var is = function (element, selector) {
  819. var dom = element.dom;
  820. if (dom.nodeType !== ELEMENT) {
  821. return false;
  822. } else {
  823. var elem = dom;
  824. if (elem.matches !== undefined) {
  825. return elem.matches(selector);
  826. } else if (elem.msMatchesSelector !== undefined) {
  827. return elem.msMatchesSelector(selector);
  828. } else if (elem.webkitMatchesSelector !== undefined) {
  829. return elem.webkitMatchesSelector(selector);
  830. } else if (elem.mozMatchesSelector !== undefined) {
  831. return elem.mozMatchesSelector(selector);
  832. } else {
  833. throw new Error('Browser lacks native selectors');
  834. }
  835. }
  836. };
  837. var bypassSelector = function (dom) {
  838. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  839. };
  840. var all = function (selector, scope) {
  841. var base = scope === undefined ? document : scope.dom;
  842. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
  843. };
  844. var one = function (selector, scope) {
  845. var base = scope === undefined ? document : scope.dom;
  846. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  847. };
  848. var eq = function (e1, e2) {
  849. return e1.dom === e2.dom;
  850. };
  851. var Global = typeof window !== 'undefined' ? window : Function('return this;')();
  852. var name = function (element) {
  853. var r = element.dom.nodeName;
  854. return r.toLowerCase();
  855. };
  856. var type = function (element) {
  857. return element.dom.nodeType;
  858. };
  859. var isType$1 = function (t) {
  860. return function (element) {
  861. return type(element) === t;
  862. };
  863. };
  864. var isElement = isType$1(ELEMENT);
  865. var isText = isType$1(TEXT);
  866. var isDocument = isType$1(DOCUMENT);
  867. var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT);
  868. var owner = function (element) {
  869. return SugarElement.fromDom(element.dom.ownerDocument);
  870. };
  871. var documentOrOwner = function (dos) {
  872. return isDocument(dos) ? dos : owner(dos);
  873. };
  874. var defaultView = function (element) {
  875. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  876. };
  877. var parent = function (element) {
  878. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  879. };
  880. var parents = function (element, isRoot) {
  881. var stop = isFunction(isRoot) ? isRoot : never;
  882. var dom = element.dom;
  883. var ret = [];
  884. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  885. var rawParent = dom.parentNode;
  886. var p = SugarElement.fromDom(rawParent);
  887. ret.push(p);
  888. if (stop(p) === true) {
  889. break;
  890. } else {
  891. dom = rawParent;
  892. }
  893. }
  894. return ret;
  895. };
  896. var siblings = function (element) {
  897. var filterSelf = function (elements) {
  898. return filter(elements, function (x) {
  899. return !eq(element, x);
  900. });
  901. };
  902. return parent(element).map(children).map(filterSelf).getOr([]);
  903. };
  904. var nextSibling = function (element) {
  905. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  906. };
  907. var children = function (element) {
  908. return map(element.dom.childNodes, SugarElement.fromDom);
  909. };
  910. var child = function (element, index) {
  911. var cs = element.dom.childNodes;
  912. return Optional.from(cs[index]).map(SugarElement.fromDom);
  913. };
  914. var firstChild = function (element) {
  915. return child(element, 0);
  916. };
  917. var before = function (marker, element) {
  918. var parent$1 = parent(marker);
  919. parent$1.each(function (v) {
  920. v.dom.insertBefore(element.dom, marker.dom);
  921. });
  922. };
  923. var after = function (marker, element) {
  924. var sibling = nextSibling(marker);
  925. sibling.fold(function () {
  926. var parent$1 = parent(marker);
  927. parent$1.each(function (v) {
  928. append(v, element);
  929. });
  930. }, function (v) {
  931. before(v, element);
  932. });
  933. };
  934. var prepend = function (parent, element) {
  935. var firstChild$1 = firstChild(parent);
  936. firstChild$1.fold(function () {
  937. append(parent, element);
  938. }, function (v) {
  939. parent.dom.insertBefore(element.dom, v.dom);
  940. });
  941. };
  942. var append = function (parent, element) {
  943. parent.dom.appendChild(element.dom);
  944. };
  945. var appendAt = function (parent, element, index) {
  946. child(parent, index).fold(function () {
  947. append(parent, element);
  948. }, function (v) {
  949. before(v, element);
  950. });
  951. };
  952. var append$1 = function (parent, elements) {
  953. each(elements, function (x) {
  954. append(parent, x);
  955. });
  956. };
  957. var empty = function (element) {
  958. element.dom.textContent = '';
  959. each(children(element), function (rogue) {
  960. remove(rogue);
  961. });
  962. };
  963. var remove = function (element) {
  964. var dom = element.dom;
  965. if (dom.parentNode !== null) {
  966. dom.parentNode.removeChild(dom);
  967. }
  968. };
  969. var isShadowRoot = function (dos) {
  970. return isDocumentFragment(dos);
  971. };
  972. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  973. var isSupported = constant(supported);
  974. var getRootNode = supported ? function (e) {
  975. return SugarElement.fromDom(e.dom.getRootNode());
  976. } : documentOrOwner;
  977. var getShadowRoot = function (e) {
  978. var r = getRootNode(e);
  979. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  980. };
  981. var getShadowHost = function (e) {
  982. return SugarElement.fromDom(e.dom.host);
  983. };
  984. var getOriginalEventTarget = function (event) {
  985. if (isSupported() && isNonNullable(event.target)) {
  986. var el = SugarElement.fromDom(event.target);
  987. if (isElement(el) && isOpenShadowHost(el)) {
  988. if (event.composed && event.composedPath) {
  989. var composedPath = event.composedPath();
  990. if (composedPath) {
  991. return head(composedPath);
  992. }
  993. }
  994. }
  995. }
  996. return Optional.from(event.target);
  997. };
  998. var isOpenShadowHost = function (element) {
  999. return isNonNullable(element.dom.shadowRoot);
  1000. };
  1001. var inBody = function (element) {
  1002. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1003. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1004. return false;
  1005. }
  1006. var doc = dom.ownerDocument;
  1007. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1008. return doc.body.contains(dom);
  1009. }, compose1(inBody, getShadowHost));
  1010. };
  1011. var body = function () {
  1012. return getBody(SugarElement.fromDom(document));
  1013. };
  1014. var getBody = function (doc) {
  1015. var b = doc.dom.body;
  1016. if (b === null || b === undefined) {
  1017. throw new Error('Body is not available yet');
  1018. }
  1019. return SugarElement.fromDom(b);
  1020. };
  1021. var fireDetaching = function (component) {
  1022. emit(component, detachedFromDom());
  1023. var children = component.components();
  1024. each(children, fireDetaching);
  1025. };
  1026. var fireAttaching = function (component) {
  1027. var children = component.components();
  1028. each(children, fireAttaching);
  1029. emit(component, attachedToDom());
  1030. };
  1031. var attach = function (parent, child) {
  1032. append(parent.element, child.element);
  1033. };
  1034. var detachChildren = function (component) {
  1035. each(component.components(), function (childComp) {
  1036. return remove(childComp.element);
  1037. });
  1038. empty(component.element);
  1039. component.syncComponents();
  1040. };
  1041. var replaceChildren = function (component, newChildren) {
  1042. var subs = component.components();
  1043. detachChildren(component);
  1044. var deleted = difference(subs, newChildren);
  1045. each(deleted, function (comp) {
  1046. fireDetaching(comp);
  1047. component.getSystem().removeFromWorld(comp);
  1048. });
  1049. each(newChildren, function (childComp) {
  1050. if (!childComp.getSystem().isConnected()) {
  1051. component.getSystem().addToWorld(childComp);
  1052. attach(component, childComp);
  1053. if (inBody(component.element)) {
  1054. fireAttaching(childComp);
  1055. }
  1056. } else {
  1057. attach(component, childComp);
  1058. }
  1059. component.syncComponents();
  1060. });
  1061. };
  1062. var attach$1 = function (parent, child) {
  1063. attachWith(parent, child, append);
  1064. };
  1065. var attachWith = function (parent, child, insertion) {
  1066. parent.getSystem().addToWorld(child);
  1067. insertion(parent.element, child.element);
  1068. if (inBody(parent.element)) {
  1069. fireAttaching(child);
  1070. }
  1071. parent.syncComponents();
  1072. };
  1073. var doDetach = function (component) {
  1074. fireDetaching(component);
  1075. remove(component.element);
  1076. component.getSystem().removeFromWorld(component);
  1077. };
  1078. var detach = function (component) {
  1079. var parent$1 = parent(component.element).bind(function (p) {
  1080. return component.getSystem().getByDom(p).toOptional();
  1081. });
  1082. doDetach(component);
  1083. parent$1.each(function (p) {
  1084. p.syncComponents();
  1085. });
  1086. };
  1087. var attachSystemAfter = function (element, guiSystem) {
  1088. attachSystemWith(element, guiSystem, after);
  1089. };
  1090. var attachSystemWith = function (element, guiSystem, inserter) {
  1091. inserter(element, guiSystem.element);
  1092. var children$1 = children(guiSystem.element);
  1093. each(children$1, function (child) {
  1094. guiSystem.getByDom(child).each(fireAttaching);
  1095. });
  1096. };
  1097. var detachSystem = function (guiSystem) {
  1098. var children$1 = children(guiSystem.element);
  1099. each(children$1, function (child) {
  1100. guiSystem.getByDom(child).each(fireDetaching);
  1101. });
  1102. remove(guiSystem.element);
  1103. };
  1104. var keys = Object.keys;
  1105. var hasOwnProperty = Object.hasOwnProperty;
  1106. var each$1 = function (obj, f) {
  1107. var props = keys(obj);
  1108. for (var k = 0, len = props.length; k < len; k++) {
  1109. var i = props[k];
  1110. var x = obj[i];
  1111. f(x, i);
  1112. }
  1113. };
  1114. var map$1 = function (obj, f) {
  1115. return tupleMap(obj, function (x, i) {
  1116. return {
  1117. k: i,
  1118. v: f(x, i)
  1119. };
  1120. });
  1121. };
  1122. var tupleMap = function (obj, f) {
  1123. var r = {};
  1124. each$1(obj, function (x, i) {
  1125. var tuple = f(x, i);
  1126. r[tuple.k] = tuple.v;
  1127. });
  1128. return r;
  1129. };
  1130. var objAcc = function (r) {
  1131. return function (x, i) {
  1132. r[i] = x;
  1133. };
  1134. };
  1135. var internalFilter = function (obj, pred, onTrue, onFalse) {
  1136. var r = {};
  1137. each$1(obj, function (x, i) {
  1138. (pred(x, i) ? onTrue : onFalse)(x, i);
  1139. });
  1140. return r;
  1141. };
  1142. var filter$1 = function (obj, pred) {
  1143. var t = {};
  1144. internalFilter(obj, pred, objAcc(t), noop);
  1145. return t;
  1146. };
  1147. var mapToArray = function (obj, f) {
  1148. var r = [];
  1149. each$1(obj, function (value, name) {
  1150. r.push(f(value, name));
  1151. });
  1152. return r;
  1153. };
  1154. var find$2 = function (obj, pred) {
  1155. var props = keys(obj);
  1156. for (var k = 0, len = props.length; k < len; k++) {
  1157. var i = props[k];
  1158. var x = obj[i];
  1159. if (pred(x, i, obj)) {
  1160. return Optional.some(x);
  1161. }
  1162. }
  1163. return Optional.none();
  1164. };
  1165. var values = function (obj) {
  1166. return mapToArray(obj, function (v) {
  1167. return v;
  1168. });
  1169. };
  1170. var get = function (obj, key) {
  1171. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  1172. };
  1173. var has = function (obj, key) {
  1174. return hasOwnProperty.call(obj, key);
  1175. };
  1176. var hasNonNullableKey = function (obj, key) {
  1177. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  1178. };
  1179. var rawSet = function (dom, key, value) {
  1180. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1181. dom.setAttribute(key, value + '');
  1182. } else {
  1183. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1184. throw new Error('Attribute value was not simple');
  1185. }
  1186. };
  1187. var set = function (element, key, value) {
  1188. rawSet(element.dom, key, value);
  1189. };
  1190. var setAll = function (element, attrs) {
  1191. var dom = element.dom;
  1192. each$1(attrs, function (v, k) {
  1193. rawSet(dom, k, v);
  1194. });
  1195. };
  1196. var get$1 = function (element, key) {
  1197. var v = element.dom.getAttribute(key);
  1198. return v === null ? undefined : v;
  1199. };
  1200. var getOpt = function (element, key) {
  1201. return Optional.from(get$1(element, key));
  1202. };
  1203. var has$1 = function (element, key) {
  1204. var dom = element.dom;
  1205. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1206. };
  1207. var remove$1 = function (element, key) {
  1208. element.dom.removeAttribute(key);
  1209. };
  1210. var read = function (element, attr) {
  1211. var value = get$1(element, attr);
  1212. return value === undefined || value === '' ? [] : value.split(' ');
  1213. };
  1214. var add = function (element, attr, id) {
  1215. var old = read(element, attr);
  1216. var nu = old.concat([id]);
  1217. set(element, attr, nu.join(' '));
  1218. return true;
  1219. };
  1220. var remove$2 = function (element, attr, id) {
  1221. var nu = filter(read(element, attr), function (v) {
  1222. return v !== id;
  1223. });
  1224. if (nu.length > 0) {
  1225. set(element, attr, nu.join(' '));
  1226. } else {
  1227. remove$1(element, attr);
  1228. }
  1229. return false;
  1230. };
  1231. var supports = function (element) {
  1232. return element.dom.classList !== undefined;
  1233. };
  1234. var get$2 = function (element) {
  1235. return read(element, 'class');
  1236. };
  1237. var add$1 = function (element, clazz) {
  1238. return add(element, 'class', clazz);
  1239. };
  1240. var remove$3 = function (element, clazz) {
  1241. return remove$2(element, 'class', clazz);
  1242. };
  1243. var add$2 = function (element, clazz) {
  1244. if (supports(element)) {
  1245. element.dom.classList.add(clazz);
  1246. } else {
  1247. add$1(element, clazz);
  1248. }
  1249. };
  1250. var cleanClass = function (element) {
  1251. var classList = supports(element) ? element.dom.classList : get$2(element);
  1252. if (classList.length === 0) {
  1253. remove$1(element, 'class');
  1254. }
  1255. };
  1256. var remove$4 = function (element, clazz) {
  1257. if (supports(element)) {
  1258. var classList = element.dom.classList;
  1259. classList.remove(clazz);
  1260. } else {
  1261. remove$3(element, clazz);
  1262. }
  1263. cleanClass(element);
  1264. };
  1265. var has$2 = function (element, clazz) {
  1266. return supports(element) && element.dom.classList.contains(clazz);
  1267. };
  1268. var swap = function (element, addCls, removeCls) {
  1269. remove$4(element, removeCls);
  1270. add$2(element, addCls);
  1271. };
  1272. var toAlpha = function (component, swapConfig, _swapState) {
  1273. swap(component.element, swapConfig.alpha, swapConfig.omega);
  1274. };
  1275. var toOmega = function (component, swapConfig, _swapState) {
  1276. swap(component.element, swapConfig.omega, swapConfig.alpha);
  1277. };
  1278. var clear = function (component, swapConfig, _swapState) {
  1279. remove$4(component.element, swapConfig.alpha);
  1280. remove$4(component.element, swapConfig.omega);
  1281. };
  1282. var isAlpha = function (component, swapConfig, _swapState) {
  1283. return has$2(component.element, swapConfig.alpha);
  1284. };
  1285. var isOmega = function (component, swapConfig, _swapState) {
  1286. return has$2(component.element, swapConfig.omega);
  1287. };
  1288. var SwapApis = /*#__PURE__*/Object.freeze({
  1289. __proto__: null,
  1290. toAlpha: toAlpha,
  1291. toOmega: toOmega,
  1292. isAlpha: isAlpha,
  1293. isOmega: isOmega,
  1294. clear: clear
  1295. });
  1296. var value = function (o) {
  1297. var is = function (v) {
  1298. return o === v;
  1299. };
  1300. var or = function (_opt) {
  1301. return value(o);
  1302. };
  1303. var orThunk = function (_f) {
  1304. return value(o);
  1305. };
  1306. var map = function (f) {
  1307. return value(f(o));
  1308. };
  1309. var mapError = function (_f) {
  1310. return value(o);
  1311. };
  1312. var each = function (f) {
  1313. f(o);
  1314. };
  1315. var bind = function (f) {
  1316. return f(o);
  1317. };
  1318. var fold = function (_, onValue) {
  1319. return onValue(o);
  1320. };
  1321. var exists = function (f) {
  1322. return f(o);
  1323. };
  1324. var forall = function (f) {
  1325. return f(o);
  1326. };
  1327. var toOptional = function () {
  1328. return Optional.some(o);
  1329. };
  1330. return {
  1331. is: is,
  1332. isValue: always,
  1333. isError: never,
  1334. getOr: constant(o),
  1335. getOrThunk: constant(o),
  1336. getOrDie: constant(o),
  1337. or: or,
  1338. orThunk: orThunk,
  1339. fold: fold,
  1340. map: map,
  1341. mapError: mapError,
  1342. each: each,
  1343. bind: bind,
  1344. exists: exists,
  1345. forall: forall,
  1346. toOptional: toOptional
  1347. };
  1348. };
  1349. var error = function (message) {
  1350. var getOrThunk = function (f) {
  1351. return f();
  1352. };
  1353. var getOrDie = function () {
  1354. return die(String(message))();
  1355. };
  1356. var or = function (opt) {
  1357. return opt;
  1358. };
  1359. var orThunk = function (f) {
  1360. return f();
  1361. };
  1362. var map = function (_f) {
  1363. return error(message);
  1364. };
  1365. var mapError = function (f) {
  1366. return error(f(message));
  1367. };
  1368. var bind = function (_f) {
  1369. return error(message);
  1370. };
  1371. var fold = function (onError, _) {
  1372. return onError(message);
  1373. };
  1374. return {
  1375. is: never,
  1376. isValue: never,
  1377. isError: always,
  1378. getOr: identity,
  1379. getOrThunk: getOrThunk,
  1380. getOrDie: getOrDie,
  1381. or: or,
  1382. orThunk: orThunk,
  1383. fold: fold,
  1384. map: map,
  1385. mapError: mapError,
  1386. each: noop,
  1387. bind: bind,
  1388. exists: never,
  1389. forall: always,
  1390. toOptional: Optional.none
  1391. };
  1392. };
  1393. var fromOption = function (opt, err) {
  1394. return opt.fold(function () {
  1395. return error(err);
  1396. }, value);
  1397. };
  1398. var Result = {
  1399. value: value,
  1400. error: error,
  1401. fromOption: fromOption
  1402. };
  1403. var SimpleResultType;
  1404. (function (SimpleResultType) {
  1405. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1406. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1407. }(SimpleResultType || (SimpleResultType = {})));
  1408. var fold = function (res, onError, onValue) {
  1409. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1410. };
  1411. var partition = function (results) {
  1412. var values = [];
  1413. var errors = [];
  1414. each(results, function (obj) {
  1415. fold(obj, function (err) {
  1416. return errors.push(err);
  1417. }, function (val) {
  1418. return values.push(val);
  1419. });
  1420. });
  1421. return {
  1422. values: values,
  1423. errors: errors
  1424. };
  1425. };
  1426. var mapError = function (res, f) {
  1427. if (res.stype === SimpleResultType.Error) {
  1428. return {
  1429. stype: SimpleResultType.Error,
  1430. serror: f(res.serror)
  1431. };
  1432. } else {
  1433. return res;
  1434. }
  1435. };
  1436. var map$2 = function (res, f) {
  1437. if (res.stype === SimpleResultType.Value) {
  1438. return {
  1439. stype: SimpleResultType.Value,
  1440. svalue: f(res.svalue)
  1441. };
  1442. } else {
  1443. return res;
  1444. }
  1445. };
  1446. var bind$1 = function (res, f) {
  1447. if (res.stype === SimpleResultType.Value) {
  1448. return f(res.svalue);
  1449. } else {
  1450. return res;
  1451. }
  1452. };
  1453. var bindError = function (res, f) {
  1454. if (res.stype === SimpleResultType.Error) {
  1455. return f(res.serror);
  1456. } else {
  1457. return res;
  1458. }
  1459. };
  1460. var svalue = function (v) {
  1461. return {
  1462. stype: SimpleResultType.Value,
  1463. svalue: v
  1464. };
  1465. };
  1466. var serror = function (e) {
  1467. return {
  1468. stype: SimpleResultType.Error,
  1469. serror: e
  1470. };
  1471. };
  1472. var toResult = function (res) {
  1473. return fold(res, Result.error, Result.value);
  1474. };
  1475. var fromResult = function (res) {
  1476. return res.fold(serror, svalue);
  1477. };
  1478. var SimpleResult = {
  1479. fromResult: fromResult,
  1480. toResult: toResult,
  1481. svalue: svalue,
  1482. partition: partition,
  1483. serror: serror,
  1484. bind: bind$1,
  1485. bindError: bindError,
  1486. map: map$2,
  1487. mapError: mapError,
  1488. fold: fold
  1489. };
  1490. var generate = function (cases) {
  1491. if (!isArray(cases)) {
  1492. throw new Error('cases must be an array');
  1493. }
  1494. if (cases.length === 0) {
  1495. throw new Error('there must be at least one case');
  1496. }
  1497. var constructors = [];
  1498. var adt = {};
  1499. each(cases, function (acase, count) {
  1500. var keys$1 = keys(acase);
  1501. if (keys$1.length !== 1) {
  1502. throw new Error('one and only one name per case');
  1503. }
  1504. var key = keys$1[0];
  1505. var value = acase[key];
  1506. if (adt[key] !== undefined) {
  1507. throw new Error('duplicate key detected:' + key);
  1508. } else if (key === 'cata') {
  1509. throw new Error('cannot have a case named cata (sorry)');
  1510. } else if (!isArray(value)) {
  1511. throw new Error('case arguments must be an array');
  1512. }
  1513. constructors.push(key);
  1514. adt[key] = function () {
  1515. var argLength = arguments.length;
  1516. if (argLength !== value.length) {
  1517. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1518. }
  1519. var args = new Array(argLength);
  1520. for (var i = 0; i < args.length; i++) {
  1521. args[i] = arguments[i];
  1522. }
  1523. var match = function (branches) {
  1524. var branchKeys = keys(branches);
  1525. if (constructors.length !== branchKeys.length) {
  1526. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1527. }
  1528. var allReqd = forall(constructors, function (reqKey) {
  1529. return contains(branchKeys, reqKey);
  1530. });
  1531. if (!allReqd) {
  1532. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1533. }
  1534. return branches[key].apply(null, args);
  1535. };
  1536. return {
  1537. fold: function () {
  1538. if (arguments.length !== cases.length) {
  1539. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  1540. }
  1541. var target = arguments[count];
  1542. return target.apply(null, args);
  1543. },
  1544. match: match,
  1545. log: function (label) {
  1546. console.log(label, {
  1547. constructors: constructors,
  1548. constructor: key,
  1549. params: args
  1550. });
  1551. }
  1552. };
  1553. };
  1554. });
  1555. return adt;
  1556. };
  1557. var Adt = { generate: generate };
  1558. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  1559. var shallow = function (old, nu) {
  1560. return nu;
  1561. };
  1562. var deep = function (old, nu) {
  1563. var bothObjects = isObject(old) && isObject(nu);
  1564. return bothObjects ? deepMerge(old, nu) : nu;
  1565. };
  1566. var baseMerge = function (merger) {
  1567. return function () {
  1568. var objects = new Array(arguments.length);
  1569. for (var i = 0; i < objects.length; i++) {
  1570. objects[i] = arguments[i];
  1571. }
  1572. if (objects.length === 0) {
  1573. throw new Error('Can\'t merge zero objects');
  1574. }
  1575. var ret = {};
  1576. for (var j = 0; j < objects.length; j++) {
  1577. var curObject = objects[j];
  1578. for (var key in curObject) {
  1579. if (hasOwnProperty$1.call(curObject, key)) {
  1580. ret[key] = merger(ret[key], curObject[key]);
  1581. }
  1582. }
  1583. }
  1584. return ret;
  1585. };
  1586. };
  1587. var deepMerge = baseMerge(deep);
  1588. var merge = baseMerge(shallow);
  1589. var adt = Adt.generate([
  1590. { strict: [] },
  1591. { defaultedThunk: ['fallbackThunk'] },
  1592. { asOption: [] },
  1593. { asDefaultedOptionThunk: ['fallbackThunk'] },
  1594. { mergeWithThunk: ['baseThunk'] }
  1595. ]);
  1596. var defaulted = function (fallback) {
  1597. return adt.defaultedThunk(constant(fallback));
  1598. };
  1599. var mergeWith = function (base) {
  1600. return adt.mergeWithThunk(constant(base));
  1601. };
  1602. var strict = adt.strict;
  1603. var asOption = adt.asOption;
  1604. var defaultedThunk = adt.defaultedThunk;
  1605. var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
  1606. var mergeWithThunk = adt.mergeWithThunk;
  1607. var comparison = Adt.generate([
  1608. {
  1609. bothErrors: [
  1610. 'error1',
  1611. 'error2'
  1612. ]
  1613. },
  1614. {
  1615. firstError: [
  1616. 'error1',
  1617. 'value2'
  1618. ]
  1619. },
  1620. {
  1621. secondError: [
  1622. 'value1',
  1623. 'error2'
  1624. ]
  1625. },
  1626. {
  1627. bothValues: [
  1628. 'value1',
  1629. 'value2'
  1630. ]
  1631. }
  1632. ]);
  1633. var partition$1 = function (results) {
  1634. var errors = [];
  1635. var values = [];
  1636. each(results, function (result) {
  1637. result.fold(function (err) {
  1638. errors.push(err);
  1639. }, function (value) {
  1640. values.push(value);
  1641. });
  1642. });
  1643. return {
  1644. errors: errors,
  1645. values: values
  1646. };
  1647. };
  1648. var exclude = function (obj, fields) {
  1649. var r = {};
  1650. each$1(obj, function (v, k) {
  1651. if (!contains(fields, k)) {
  1652. r[k] = v;
  1653. }
  1654. });
  1655. return r;
  1656. };
  1657. var wrap = function (key, value) {
  1658. var _a;
  1659. return _a = {}, _a[key] = value, _a;
  1660. };
  1661. var wrapAll = function (keyvalues) {
  1662. var r = {};
  1663. each(keyvalues, function (kv) {
  1664. r[kv.key] = kv.value;
  1665. });
  1666. return r;
  1667. };
  1668. var exclude$1 = function (obj, fields) {
  1669. return exclude(obj, fields);
  1670. };
  1671. var wrap$1 = function (key, value) {
  1672. return wrap(key, value);
  1673. };
  1674. var wrapAll$1 = function (keyvalues) {
  1675. return wrapAll(keyvalues);
  1676. };
  1677. var mergeValues = function (values, base) {
  1678. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  1679. };
  1680. var mergeErrors = function (errors) {
  1681. return Result.error(flatten(errors));
  1682. };
  1683. var consolidate = function (objs, base) {
  1684. var partitions = partition$1(objs);
  1685. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  1686. };
  1687. var mergeValues$1 = function (values, base) {
  1688. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  1689. };
  1690. var mergeErrors$1 = function (errors) {
  1691. return compose(SimpleResult.serror, flatten)(errors);
  1692. };
  1693. var consolidateObj = function (objects, base) {
  1694. var partition = SimpleResult.partition(objects);
  1695. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1696. };
  1697. var consolidateArr = function (objects) {
  1698. var partitions = SimpleResult.partition(objects);
  1699. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1700. };
  1701. var ResultCombine = {
  1702. consolidateObj: consolidateObj,
  1703. consolidateArr: consolidateArr
  1704. };
  1705. var formatObj = function (input) {
  1706. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1707. };
  1708. var formatErrors = function (errors) {
  1709. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1710. path: [],
  1711. getErrorInfo: function () {
  1712. return '... (only showing first ten failures)';
  1713. }
  1714. }]) : errors;
  1715. return map(es, function (e) {
  1716. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1717. });
  1718. };
  1719. var nu$3 = function (path, getErrorInfo) {
  1720. return SimpleResult.serror([{
  1721. path: path,
  1722. getErrorInfo: getErrorInfo
  1723. }]);
  1724. };
  1725. var missingStrict = function (path, key, obj) {
  1726. return nu$3(path, function () {
  1727. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  1728. });
  1729. };
  1730. var missingKey = function (path, key) {
  1731. return nu$3(path, function () {
  1732. return 'Choice schema did not contain choice key: "' + key + '"';
  1733. });
  1734. };
  1735. var missingBranch = function (path, branches, branch) {
  1736. return nu$3(path, function () {
  1737. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1738. });
  1739. };
  1740. var unsupportedFields = function (path, unsupported) {
  1741. return nu$3(path, function () {
  1742. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1743. });
  1744. };
  1745. var custom = function (path, err) {
  1746. return nu$3(path, function () {
  1747. return err;
  1748. });
  1749. };
  1750. var adt$1 = Adt.generate([
  1751. {
  1752. field: [
  1753. 'key',
  1754. 'okey',
  1755. 'presence',
  1756. 'prop'
  1757. ]
  1758. },
  1759. {
  1760. state: [
  1761. 'okey',
  1762. 'instantiator'
  1763. ]
  1764. }
  1765. ]);
  1766. var strictAccess = function (path, obj, key) {
  1767. return get(obj, key).fold(function () {
  1768. return missingStrict(path, key, obj);
  1769. }, SimpleResult.svalue);
  1770. };
  1771. var fallbackAccess = function (obj, key, fallbackThunk) {
  1772. var v = get(obj, key).fold(function () {
  1773. return fallbackThunk(obj);
  1774. }, identity);
  1775. return SimpleResult.svalue(v);
  1776. };
  1777. var optionAccess = function (obj, key) {
  1778. return SimpleResult.svalue(get(obj, key));
  1779. };
  1780. var optionDefaultedAccess = function (obj, key, fallback) {
  1781. var opt = get(obj, key).map(function (val) {
  1782. return val === true ? fallback(obj) : val;
  1783. });
  1784. return SimpleResult.svalue(opt);
  1785. };
  1786. var cExtractOne = function (path, obj, field, strength) {
  1787. return field.fold(function (key, okey, presence, prop) {
  1788. var bundle = function (av) {
  1789. var result = prop.extract(path.concat([key]), strength, av);
  1790. return SimpleResult.map(result, function (res) {
  1791. return wrap(okey, strength(res));
  1792. });
  1793. };
  1794. var bundleAsOption = function (optValue) {
  1795. return optValue.fold(function () {
  1796. var outcome = wrap(okey, strength(Optional.none()));
  1797. return SimpleResult.svalue(outcome);
  1798. }, function (ov) {
  1799. var result = prop.extract(path.concat([key]), strength, ov);
  1800. return SimpleResult.map(result, function (res) {
  1801. return wrap(okey, strength(Optional.some(res)));
  1802. });
  1803. });
  1804. };
  1805. return function () {
  1806. return presence.fold(function () {
  1807. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1808. }, function (fallbackThunk) {
  1809. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1810. }, function () {
  1811. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1812. }, function (fallbackThunk) {
  1813. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1814. }, function (baseThunk) {
  1815. var base = baseThunk(obj);
  1816. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1817. return deepMerge(base, v);
  1818. });
  1819. return SimpleResult.bind(result, bundle);
  1820. });
  1821. }();
  1822. }, function (okey, instantiator) {
  1823. var state = instantiator(obj);
  1824. return SimpleResult.svalue(wrap(okey, strength(state)));
  1825. });
  1826. };
  1827. var cExtract = function (path, obj, fields, strength) {
  1828. var results = map(fields, function (field) {
  1829. return cExtractOne(path, obj, field, strength);
  1830. });
  1831. return ResultCombine.consolidateObj(results, {});
  1832. };
  1833. var value$1 = function (validator) {
  1834. var extract = function (path, strength, val) {
  1835. return SimpleResult.bindError(validator(val, strength), function (err) {
  1836. return custom(path, err);
  1837. });
  1838. };
  1839. var toString = function () {
  1840. return 'val';
  1841. };
  1842. return {
  1843. extract: extract,
  1844. toString: toString
  1845. };
  1846. };
  1847. var getSetKeys = function (obj) {
  1848. return keys(filter$1(obj, function (value) {
  1849. return value !== undefined && value !== null;
  1850. }));
  1851. };
  1852. var objOfOnly = function (fields) {
  1853. var delegate = objOf(fields);
  1854. var fieldNames = foldr(fields, function (acc, f) {
  1855. return f.fold(function (key) {
  1856. return deepMerge(acc, wrap$1(key, true));
  1857. }, constant(acc));
  1858. }, {});
  1859. var extract = function (path, strength, o) {
  1860. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1861. var extra = filter(keys, function (k) {
  1862. return !hasNonNullableKey(fieldNames, k);
  1863. });
  1864. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1865. };
  1866. return {
  1867. extract: extract,
  1868. toString: delegate.toString
  1869. };
  1870. };
  1871. var objOf = function (fields) {
  1872. var extract = function (path, strength, o) {
  1873. return cExtract(path, o, fields, strength);
  1874. };
  1875. var toString = function () {
  1876. var fieldStrings = map(fields, function (field) {
  1877. return field.fold(function (key, okey, presence, prop) {
  1878. return key + ' -> ' + prop.toString();
  1879. }, function (okey, _instantiator) {
  1880. return 'state(' + okey + ')';
  1881. });
  1882. });
  1883. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1884. };
  1885. return {
  1886. extract: extract,
  1887. toString: toString
  1888. };
  1889. };
  1890. var arrOf = function (prop) {
  1891. var extract = function (path, strength, array) {
  1892. var results = map(array, function (a, i) {
  1893. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1894. });
  1895. return ResultCombine.consolidateArr(results);
  1896. };
  1897. var toString = function () {
  1898. return 'array(' + prop.toString() + ')';
  1899. };
  1900. return {
  1901. extract: extract,
  1902. toString: toString
  1903. };
  1904. };
  1905. var setOf = function (validator, prop) {
  1906. var validateKeys = function (path, keys) {
  1907. return arrOf(value$1(validator)).extract(path, identity, keys);
  1908. };
  1909. var extract = function (path, strength, o) {
  1910. var keys$1 = keys(o);
  1911. var validatedKeys = validateKeys(path, keys$1);
  1912. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1913. var schema = map(validKeys, function (vk) {
  1914. return adt$1.field(vk, vk, strict(), prop);
  1915. });
  1916. return objOf(schema).extract(path, strength, o);
  1917. });
  1918. };
  1919. var toString = function () {
  1920. return 'setOf(' + prop.toString() + ')';
  1921. };
  1922. return {
  1923. extract: extract,
  1924. toString: toString
  1925. };
  1926. };
  1927. var anyValue = constant(value$1(SimpleResult.svalue));
  1928. var state = adt$1.state;
  1929. var field = adt$1.field;
  1930. var chooseFrom = function (path, strength, input, branches, ch) {
  1931. var fields = get(branches, ch);
  1932. return fields.fold(function () {
  1933. return missingBranch(path, branches, ch);
  1934. }, function (vp) {
  1935. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1936. });
  1937. };
  1938. var choose = function (key, branches) {
  1939. var extract = function (path, strength, input) {
  1940. var choice = get(input, key);
  1941. return choice.fold(function () {
  1942. return missingKey(path, key);
  1943. }, function (chosen) {
  1944. return chooseFrom(path, strength, input, branches, chosen);
  1945. });
  1946. };
  1947. var toString = function () {
  1948. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1949. };
  1950. return {
  1951. extract: extract,
  1952. toString: toString
  1953. };
  1954. };
  1955. var _anyValue = value$1(SimpleResult.svalue);
  1956. var valueOf = function (validator) {
  1957. return value$1(function (v) {
  1958. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1959. });
  1960. };
  1961. var setOf$1 = function (validator, prop) {
  1962. return setOf(function (v) {
  1963. return SimpleResult.fromResult(validator(v));
  1964. }, prop);
  1965. };
  1966. var extract = function (label, prop, strength, obj) {
  1967. var res = prop.extract([label], strength, obj);
  1968. return SimpleResult.mapError(res, function (errs) {
  1969. return {
  1970. input: obj,
  1971. errors: errs
  1972. };
  1973. });
  1974. };
  1975. var asRaw = function (label, prop, obj) {
  1976. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1977. };
  1978. var getOrDie = function (extraction) {
  1979. return extraction.fold(function (errInfo) {
  1980. throw new Error(formatError(errInfo));
  1981. }, identity);
  1982. };
  1983. var asRawOrDie = function (label, prop, obj) {
  1984. return getOrDie(asRaw(label, prop, obj));
  1985. };
  1986. var formatError = function (errInfo) {
  1987. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1988. };
  1989. var choose$1 = function (key, branches) {
  1990. return choose(key, map$1(branches, objOf));
  1991. };
  1992. var anyValue$1 = constant(_anyValue);
  1993. var typedValue = function (validator, expectedType) {
  1994. return value$1(function (a) {
  1995. var actualType = typeof a;
  1996. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1997. });
  1998. };
  1999. var functionProcessor = typedValue(isFunction, 'function');
  2000. var strict$1 = function (key) {
  2001. return field(key, key, strict(), anyValue());
  2002. };
  2003. var strictOf = function (key, schema) {
  2004. return field(key, key, strict(), schema);
  2005. };
  2006. var strictFunction = function (key) {
  2007. return strictOf(key, functionProcessor);
  2008. };
  2009. var forbid = function (key, message) {
  2010. return field(key, key, asOption(), value$1(function (_v) {
  2011. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  2012. }));
  2013. };
  2014. var strictObjOf = function (key, objSchema) {
  2015. return field(key, key, strict(), objOf(objSchema));
  2016. };
  2017. var option = function (key) {
  2018. return field(key, key, asOption(), anyValue());
  2019. };
  2020. var optionOf = function (key, schema) {
  2021. return field(key, key, asOption(), schema);
  2022. };
  2023. var optionObjOf = function (key, objSchema) {
  2024. return optionOf(key, objOf(objSchema));
  2025. };
  2026. var optionObjOfOnly = function (key, objSchema) {
  2027. return optionOf(key, objOfOnly(objSchema));
  2028. };
  2029. var defaulted$1 = function (key, fallback) {
  2030. return field(key, key, defaulted(fallback), anyValue());
  2031. };
  2032. var defaultedOf = function (key, fallback, schema) {
  2033. return field(key, key, defaulted(fallback), schema);
  2034. };
  2035. var defaultedFunction = function (key, fallback) {
  2036. return defaultedOf(key, fallback, functionProcessor);
  2037. };
  2038. var defaultedObjOf = function (key, fallback, objSchema) {
  2039. return defaultedOf(key, fallback, objOf(objSchema));
  2040. };
  2041. var state$1 = function (okey, instantiator) {
  2042. return state(okey, instantiator);
  2043. };
  2044. var SwapSchema = [
  2045. strict$1('alpha'),
  2046. strict$1('omega')
  2047. ];
  2048. var ensureIsRoot = function (isRoot) {
  2049. return isFunction(isRoot) ? isRoot : never;
  2050. };
  2051. var ancestor = function (scope, transform, isRoot) {
  2052. var element = scope.dom;
  2053. var stop = ensureIsRoot(isRoot);
  2054. while (element.parentNode) {
  2055. element = element.parentNode;
  2056. var el = SugarElement.fromDom(element);
  2057. var transformed = transform(el);
  2058. if (transformed.isSome()) {
  2059. return transformed;
  2060. } else if (stop(el)) {
  2061. break;
  2062. }
  2063. }
  2064. return Optional.none();
  2065. };
  2066. var closest = function (scope, transform, isRoot) {
  2067. var current = transform(scope);
  2068. var stop = ensureIsRoot(isRoot);
  2069. return current.orThunk(function () {
  2070. return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  2071. });
  2072. };
  2073. var isSource = function (component, simulatedEvent) {
  2074. return eq(component.element, simulatedEvent.event.target);
  2075. };
  2076. var nu$4 = function (parts) {
  2077. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2078. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2079. }
  2080. return asRawOrDie('Extracting event.handler', objOfOnly([
  2081. defaulted$1('can', always),
  2082. defaulted$1('abort', never),
  2083. defaulted$1('run', noop)
  2084. ]), parts);
  2085. };
  2086. var all$1 = function (handlers, f) {
  2087. return function () {
  2088. var args = [];
  2089. for (var _i = 0; _i < arguments.length; _i++) {
  2090. args[_i] = arguments[_i];
  2091. }
  2092. return foldl(handlers, function (acc, handler) {
  2093. return acc && f(handler).apply(undefined, args);
  2094. }, true);
  2095. };
  2096. };
  2097. var any = function (handlers, f) {
  2098. return function () {
  2099. var args = [];
  2100. for (var _i = 0; _i < arguments.length; _i++) {
  2101. args[_i] = arguments[_i];
  2102. }
  2103. return foldl(handlers, function (acc, handler) {
  2104. return acc || f(handler).apply(undefined, args);
  2105. }, false);
  2106. };
  2107. };
  2108. var read$1 = function (handler) {
  2109. return isFunction(handler) ? {
  2110. can: constant(true),
  2111. abort: constant(false),
  2112. run: handler
  2113. } : handler;
  2114. };
  2115. var fuse = function (handlers) {
  2116. var can = all$1(handlers, function (handler) {
  2117. return handler.can;
  2118. });
  2119. var abort = any(handlers, function (handler) {
  2120. return handler.abort;
  2121. });
  2122. var run = function () {
  2123. var args = [];
  2124. for (var _i = 0; _i < arguments.length; _i++) {
  2125. args[_i] = arguments[_i];
  2126. }
  2127. each(handlers, function (handler) {
  2128. handler.run.apply(undefined, args);
  2129. });
  2130. };
  2131. return nu$4({
  2132. can: can,
  2133. abort: abort,
  2134. run: run
  2135. });
  2136. };
  2137. var derive = function (configs) {
  2138. return wrapAll$1(configs);
  2139. };
  2140. var abort = function (name, predicate) {
  2141. return {
  2142. key: name,
  2143. value: nu$4({ abort: predicate })
  2144. };
  2145. };
  2146. var can = function (name, predicate) {
  2147. return {
  2148. key: name,
  2149. value: nu$4({ can: predicate })
  2150. };
  2151. };
  2152. var run = function (name, handler) {
  2153. return {
  2154. key: name,
  2155. value: nu$4({ run: handler })
  2156. };
  2157. };
  2158. var runActionExtra = function (name, action, extra) {
  2159. return {
  2160. key: name,
  2161. value: nu$4({
  2162. run: function (component, simulatedEvent) {
  2163. action.apply(undefined, [
  2164. component,
  2165. simulatedEvent
  2166. ].concat(extra));
  2167. }
  2168. })
  2169. };
  2170. };
  2171. var runOnName = function (name) {
  2172. return function (handler) {
  2173. return run(name, handler);
  2174. };
  2175. };
  2176. var runOnSourceName = function (name) {
  2177. return function (handler) {
  2178. return {
  2179. key: name,
  2180. value: nu$4({
  2181. run: function (component, simulatedEvent) {
  2182. if (isSource(component, simulatedEvent)) {
  2183. handler(component, simulatedEvent);
  2184. }
  2185. }
  2186. })
  2187. };
  2188. };
  2189. };
  2190. var redirectToUid = function (name, uid) {
  2191. return run(name, function (component, simulatedEvent) {
  2192. component.getSystem().getByUid(uid).each(function (redirectee) {
  2193. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2194. });
  2195. });
  2196. };
  2197. var redirectToPart = function (name, detail, partName) {
  2198. var uid = detail.partUids[partName];
  2199. return redirectToUid(name, uid);
  2200. };
  2201. var cutter = function (name) {
  2202. return run(name, function (component, simulatedEvent) {
  2203. simulatedEvent.cut();
  2204. });
  2205. };
  2206. var stopper = function (name) {
  2207. return run(name, function (component, simulatedEvent) {
  2208. simulatedEvent.stop();
  2209. });
  2210. };
  2211. var runOnSource = function (name, f) {
  2212. return runOnSourceName(name)(f);
  2213. };
  2214. var runOnAttached = runOnSourceName(attachedToDom());
  2215. var runOnDetached = runOnSourceName(detachedFromDom());
  2216. var runOnInit = runOnSourceName(systemInit());
  2217. var runOnExecute = runOnName(execute());
  2218. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2219. var delegate = apiFunction.toString();
  2220. var endIndex = delegate.indexOf(')') + 1;
  2221. var openBracketIndex = delegate.indexOf('(');
  2222. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2223. f.toFunctionAnnotation = function () {
  2224. return {
  2225. name: apiName,
  2226. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2227. };
  2228. };
  2229. return f;
  2230. };
  2231. var cleanParameters = function (parameters) {
  2232. return map(parameters, function (p) {
  2233. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2234. });
  2235. };
  2236. var markAsExtraApi = function (f, extraName) {
  2237. var delegate = f.toString();
  2238. var endIndex = delegate.indexOf(')') + 1;
  2239. var openBracketIndex = delegate.indexOf('(');
  2240. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2241. f.toFunctionAnnotation = function () {
  2242. return {
  2243. name: extraName,
  2244. parameters: cleanParameters(parameters)
  2245. };
  2246. };
  2247. return f;
  2248. };
  2249. var markAsSketchApi = function (f, apiFunction) {
  2250. var delegate = apiFunction.toString();
  2251. var endIndex = delegate.indexOf(')') + 1;
  2252. var openBracketIndex = delegate.indexOf('(');
  2253. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2254. f.toFunctionAnnotation = function () {
  2255. return {
  2256. name: 'OVERRIDE',
  2257. parameters: cleanParameters(parameters.slice(1))
  2258. };
  2259. };
  2260. return f;
  2261. };
  2262. var nu$5 = function (s) {
  2263. return {
  2264. classes: s.classes !== undefined ? s.classes : [],
  2265. attributes: s.attributes !== undefined ? s.attributes : {},
  2266. styles: s.styles !== undefined ? s.styles : {}
  2267. };
  2268. };
  2269. var merge$1 = function (defnA, mod) {
  2270. return __assign(__assign({}, defnA), {
  2271. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2272. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2273. classes: defnA.classes.concat(mod.classes)
  2274. });
  2275. };
  2276. var executeEvent = function (bConfig, bState, executor) {
  2277. return runOnExecute(function (component) {
  2278. executor(component, bConfig, bState);
  2279. });
  2280. };
  2281. var loadEvent = function (bConfig, bState, f) {
  2282. return runOnInit(function (component, _simulatedEvent) {
  2283. f(component, bConfig, bState);
  2284. });
  2285. };
  2286. var create = function (schema, name, active, apis, extra, state) {
  2287. var configSchema = objOfOnly(schema);
  2288. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2289. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2290. };
  2291. var createModes = function (modes, name, active, apis, extra, state) {
  2292. var configSchema = modes;
  2293. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2294. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2295. };
  2296. var wrapApi = function (bName, apiFunction, apiName) {
  2297. var f = function (component) {
  2298. var rest = [];
  2299. for (var _i = 1; _i < arguments.length; _i++) {
  2300. rest[_i - 1] = arguments[_i];
  2301. }
  2302. var args = [component].concat(rest);
  2303. return component.config({ name: constant(bName) }).fold(function () {
  2304. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2305. }, function (info) {
  2306. var rest = Array.prototype.slice.call(args, 1);
  2307. return apiFunction.apply(undefined, [
  2308. component,
  2309. info.config,
  2310. info.state
  2311. ].concat(rest));
  2312. });
  2313. };
  2314. return markAsBehaviourApi(f, apiName, apiFunction);
  2315. };
  2316. var revokeBehaviour = function (name) {
  2317. return {
  2318. key: name,
  2319. value: undefined
  2320. };
  2321. };
  2322. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2323. var getConfig = function (info) {
  2324. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  2325. };
  2326. var wrappedApis = map$1(apis, function (apiF, apiName) {
  2327. return wrapApi(name, apiF, apiName);
  2328. });
  2329. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  2330. return markAsExtraApi(extraF, extraName);
  2331. });
  2332. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2333. revoke: curry(revokeBehaviour, name),
  2334. config: function (spec) {
  2335. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  2336. return {
  2337. key: name,
  2338. value: {
  2339. config: prepared,
  2340. me: me,
  2341. configAsRaw: cached(function () {
  2342. return asRawOrDie(name + '-config', configSchema, spec);
  2343. }),
  2344. initialConfig: spec,
  2345. state: state
  2346. }
  2347. };
  2348. },
  2349. schema: function () {
  2350. return schemaSchema;
  2351. },
  2352. exhibit: function (info, base) {
  2353. return getConfig(info).bind(function (behaviourInfo) {
  2354. return get(active, 'exhibit').map(function (exhibitor) {
  2355. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2356. });
  2357. }).getOr(nu$5({}));
  2358. },
  2359. name: function () {
  2360. return name;
  2361. },
  2362. handlers: function (info) {
  2363. return getConfig(info).map(function (behaviourInfo) {
  2364. var getEvents = get(active, 'events').getOr(function () {
  2365. return {};
  2366. });
  2367. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2368. }).getOr({});
  2369. }
  2370. });
  2371. return me;
  2372. };
  2373. var NoState = {
  2374. init: function () {
  2375. return nu$6({
  2376. readState: function () {
  2377. return 'No State required';
  2378. }
  2379. });
  2380. }
  2381. };
  2382. var nu$6 = function (spec) {
  2383. return spec;
  2384. };
  2385. var derive$1 = function (capabilities) {
  2386. return wrapAll$1(capabilities);
  2387. };
  2388. var simpleSchema = objOfOnly([
  2389. strict$1('fields'),
  2390. strict$1('name'),
  2391. defaulted$1('active', {}),
  2392. defaulted$1('apis', {}),
  2393. defaulted$1('state', NoState),
  2394. defaulted$1('extra', {})
  2395. ]);
  2396. var create$1 = function (data) {
  2397. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  2398. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2399. };
  2400. var modeSchema = objOfOnly([
  2401. strict$1('branchKey'),
  2402. strict$1('branches'),
  2403. strict$1('name'),
  2404. defaulted$1('active', {}),
  2405. defaulted$1('apis', {}),
  2406. defaulted$1('state', NoState),
  2407. defaulted$1('extra', {})
  2408. ]);
  2409. var createModes$1 = function (data) {
  2410. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  2411. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2412. };
  2413. var revoke = constant(undefined);
  2414. var Swapping = create$1({
  2415. fields: SwapSchema,
  2416. name: 'swapping',
  2417. apis: SwapApis
  2418. });
  2419. var Cell = function (initial) {
  2420. var value = initial;
  2421. var get = function () {
  2422. return value;
  2423. };
  2424. var set = function (v) {
  2425. value = v;
  2426. };
  2427. return {
  2428. get: get,
  2429. set: set
  2430. };
  2431. };
  2432. var getDocument = function () {
  2433. return SugarElement.fromDom(document);
  2434. };
  2435. var focus$1 = function (element) {
  2436. return element.dom.focus();
  2437. };
  2438. var blur = function (element) {
  2439. return element.dom.blur();
  2440. };
  2441. var hasFocus = function (element) {
  2442. var root = getRootNode(element).dom;
  2443. return element.dom === root.activeElement;
  2444. };
  2445. var active = function (root) {
  2446. if (root === void 0) {
  2447. root = getDocument();
  2448. }
  2449. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  2450. };
  2451. var search = function (element) {
  2452. return active(getRootNode(element)).filter(function (e) {
  2453. return element.dom.contains(e.dom);
  2454. });
  2455. };
  2456. var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2457. var global$2 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2458. var openLink = function (target) {
  2459. var link = document.createElement('a');
  2460. link.target = '_blank';
  2461. link.href = target.href;
  2462. link.rel = 'noreferrer noopener';
  2463. var nuEvt = document.createEvent('MouseEvents');
  2464. nuEvt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2465. document.body.appendChild(link);
  2466. link.dispatchEvent(nuEvt);
  2467. document.body.removeChild(link);
  2468. };
  2469. var DefaultStyleFormats = [
  2470. {
  2471. title: 'Headings',
  2472. items: [
  2473. {
  2474. title: 'Heading 1',
  2475. format: 'h1'
  2476. },
  2477. {
  2478. title: 'Heading 2',
  2479. format: 'h2'
  2480. },
  2481. {
  2482. title: 'Heading 3',
  2483. format: 'h3'
  2484. },
  2485. {
  2486. title: 'Heading 4',
  2487. format: 'h4'
  2488. },
  2489. {
  2490. title: 'Heading 5',
  2491. format: 'h5'
  2492. },
  2493. {
  2494. title: 'Heading 6',
  2495. format: 'h6'
  2496. }
  2497. ]
  2498. },
  2499. {
  2500. title: 'Inline',
  2501. items: [
  2502. {
  2503. title: 'Bold',
  2504. icon: 'bold',
  2505. format: 'bold'
  2506. },
  2507. {
  2508. title: 'Italic',
  2509. icon: 'italic',
  2510. format: 'italic'
  2511. },
  2512. {
  2513. title: 'Underline',
  2514. icon: 'underline',
  2515. format: 'underline'
  2516. },
  2517. {
  2518. title: 'Strikethrough',
  2519. icon: 'strikethrough',
  2520. format: 'strikethrough'
  2521. },
  2522. {
  2523. title: 'Superscript',
  2524. icon: 'superscript',
  2525. format: 'superscript'
  2526. },
  2527. {
  2528. title: 'Subscript',
  2529. icon: 'subscript',
  2530. format: 'subscript'
  2531. },
  2532. {
  2533. title: 'Code',
  2534. icon: 'code',
  2535. format: 'code'
  2536. }
  2537. ]
  2538. },
  2539. {
  2540. title: 'Blocks',
  2541. items: [
  2542. {
  2543. title: 'Paragraph',
  2544. format: 'p'
  2545. },
  2546. {
  2547. title: 'Blockquote',
  2548. format: 'blockquote'
  2549. },
  2550. {
  2551. title: 'Div',
  2552. format: 'div'
  2553. },
  2554. {
  2555. title: 'Pre',
  2556. format: 'pre'
  2557. }
  2558. ]
  2559. },
  2560. {
  2561. title: 'Alignment',
  2562. items: [
  2563. {
  2564. title: 'Left',
  2565. icon: 'alignleft',
  2566. format: 'alignleft'
  2567. },
  2568. {
  2569. title: 'Center',
  2570. icon: 'aligncenter',
  2571. format: 'aligncenter'
  2572. },
  2573. {
  2574. title: 'Right',
  2575. icon: 'alignright',
  2576. format: 'alignright'
  2577. },
  2578. {
  2579. title: 'Justify',
  2580. icon: 'alignjustify',
  2581. format: 'alignjustify'
  2582. }
  2583. ]
  2584. }
  2585. ];
  2586. var defaults = [
  2587. 'undo',
  2588. 'bold',
  2589. 'italic',
  2590. 'link',
  2591. 'image',
  2592. 'bullist',
  2593. 'styleselect'
  2594. ];
  2595. var isSkinDisabled = function (editor) {
  2596. return editor.getParam('skin') === false;
  2597. };
  2598. var readOnlyOnInit = function (_editor) {
  2599. return false;
  2600. };
  2601. var getToolbar = function (editor) {
  2602. return editor.getParam('toolbar', defaults, 'array');
  2603. };
  2604. var getStyleFormats = function (editor) {
  2605. return editor.getParam('style_formats', DefaultStyleFormats, 'array');
  2606. };
  2607. var getSkinUrl = function (editor) {
  2608. return editor.getParam('skin_url');
  2609. };
  2610. var formatChanged = 'formatChanged';
  2611. var orientationChanged = 'orientationChanged';
  2612. var dropupDismissed = 'dropupDismissed';
  2613. var fromHtml$1 = function (html, scope) {
  2614. var doc = scope || document;
  2615. var div = doc.createElement('div');
  2616. div.innerHTML = html;
  2617. return children(SugarElement.fromDom(div));
  2618. };
  2619. var get$3 = function (element) {
  2620. return element.dom.innerHTML;
  2621. };
  2622. var set$1 = function (element, content) {
  2623. var owner$1 = owner(element);
  2624. var docDom = owner$1.dom;
  2625. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2626. var contentElements = fromHtml$1(content, docDom);
  2627. append$1(fragment, contentElements);
  2628. empty(element);
  2629. append(element, fragment);
  2630. };
  2631. var getOuter = function (element) {
  2632. var container = SugarElement.fromTag('div');
  2633. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2634. append(container, clone);
  2635. return get$3(container);
  2636. };
  2637. var clone = function (original, isDeep) {
  2638. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2639. };
  2640. var shallow$1 = function (original) {
  2641. return clone(original, false);
  2642. };
  2643. var getHtml = function (element) {
  2644. var clone = shallow$1(element);
  2645. return getOuter(clone);
  2646. };
  2647. var element = function (elem) {
  2648. return getHtml(elem);
  2649. };
  2650. var chooseChannels = function (channels, message) {
  2651. return message.universal ? channels : filter(channels, function (ch) {
  2652. return contains(message.channels, ch);
  2653. });
  2654. };
  2655. var events = function (receiveConfig) {
  2656. return derive([run(receive(), function (component, message) {
  2657. var channelMap = receiveConfig.channels;
  2658. var channels = keys(channelMap);
  2659. var receivingData = message;
  2660. var targetChannels = chooseChannels(channels, receivingData);
  2661. each(targetChannels, function (ch) {
  2662. var channelInfo = channelMap[ch];
  2663. var channelSchema = channelInfo.schema;
  2664. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  2665. channelInfo.onReceive(component, data);
  2666. });
  2667. })]);
  2668. };
  2669. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2670. __proto__: null,
  2671. events: events
  2672. });
  2673. var unknown$3 = 'unknown';
  2674. var EventConfiguration;
  2675. (function (EventConfiguration) {
  2676. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2677. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2678. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2679. }(EventConfiguration || (EventConfiguration = {})));
  2680. var eventConfig = Cell({});
  2681. var makeEventLogger = function (eventName, initialTarget) {
  2682. var sequence = [];
  2683. var startTime = new Date().getTime();
  2684. return {
  2685. logEventCut: function (_name, target, purpose) {
  2686. sequence.push({
  2687. outcome: 'cut',
  2688. target: target,
  2689. purpose: purpose
  2690. });
  2691. },
  2692. logEventStopped: function (_name, target, purpose) {
  2693. sequence.push({
  2694. outcome: 'stopped',
  2695. target: target,
  2696. purpose: purpose
  2697. });
  2698. },
  2699. logNoParent: function (_name, target, purpose) {
  2700. sequence.push({
  2701. outcome: 'no-parent',
  2702. target: target,
  2703. purpose: purpose
  2704. });
  2705. },
  2706. logEventNoHandlers: function (_name, target) {
  2707. sequence.push({
  2708. outcome: 'no-handlers-left',
  2709. target: target
  2710. });
  2711. },
  2712. logEventResponse: function (_name, target, purpose) {
  2713. sequence.push({
  2714. outcome: 'response',
  2715. purpose: purpose,
  2716. target: target
  2717. });
  2718. },
  2719. write: function () {
  2720. var finishTime = new Date().getTime();
  2721. if (contains([
  2722. 'mousemove',
  2723. 'mouseover',
  2724. 'mouseout',
  2725. systemInit()
  2726. ], eventName)) {
  2727. return;
  2728. }
  2729. console.log(eventName, {
  2730. event: eventName,
  2731. time: finishTime - startTime,
  2732. target: initialTarget.dom,
  2733. sequence: map(sequence, function (s) {
  2734. if (!contains([
  2735. 'cut',
  2736. 'stopped',
  2737. 'response'
  2738. ], s.outcome)) {
  2739. return s.outcome;
  2740. } else {
  2741. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2742. }
  2743. })
  2744. });
  2745. }
  2746. };
  2747. };
  2748. var processEvent = function (eventName, initialTarget, f) {
  2749. var status = get(eventConfig.get(), eventName).orThunk(function () {
  2750. var patterns = keys(eventConfig.get());
  2751. return findMap(patterns, function (p) {
  2752. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  2753. });
  2754. }).getOr(EventConfiguration.NORMAL);
  2755. switch (status) {
  2756. case EventConfiguration.NORMAL:
  2757. return f(noLogger());
  2758. case EventConfiguration.LOGGING: {
  2759. var logger = makeEventLogger(eventName, initialTarget);
  2760. var output = f(logger);
  2761. logger.write();
  2762. return output;
  2763. }
  2764. case EventConfiguration.STOP:
  2765. return true;
  2766. }
  2767. };
  2768. var path = [
  2769. 'alloy/data/Fields',
  2770. 'alloy/debugging/Debugging'
  2771. ];
  2772. var getTrace = function () {
  2773. var err = new Error();
  2774. if (err.stack !== undefined) {
  2775. var lines = err.stack.split('\n');
  2776. return find(lines, function (line) {
  2777. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2778. return line.indexOf(p) > -1;
  2779. });
  2780. }).getOr(unknown$3);
  2781. } else {
  2782. return unknown$3;
  2783. }
  2784. };
  2785. var ignoreEvent = {
  2786. logEventCut: noop,
  2787. logEventStopped: noop,
  2788. logNoParent: noop,
  2789. logEventNoHandlers: noop,
  2790. logEventResponse: noop,
  2791. write: noop
  2792. };
  2793. var monitorEvent = function (eventName, initialTarget, f) {
  2794. return processEvent(eventName, initialTarget, f);
  2795. };
  2796. var noLogger = constant(ignoreEvent);
  2797. var menuFields = constant([
  2798. strict$1('menu'),
  2799. strict$1('selectedMenu')
  2800. ]);
  2801. var itemFields = constant([
  2802. strict$1('item'),
  2803. strict$1('selectedItem')
  2804. ]);
  2805. var schema = constant(objOf(itemFields().concat(menuFields())));
  2806. var itemSchema = constant(objOf(itemFields()));
  2807. var _initSize = strictObjOf('initSize', [
  2808. strict$1('numColumns'),
  2809. strict$1('numRows')
  2810. ]);
  2811. var itemMarkers = function () {
  2812. return strictOf('markers', itemSchema());
  2813. };
  2814. var tieredMenuMarkers = function () {
  2815. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2816. };
  2817. var markers = function (required) {
  2818. return strictObjOf('markers', map(required, strict$1));
  2819. };
  2820. var onPresenceHandler = function (label, fieldName, presence) {
  2821. var trace = getTrace();
  2822. return field(fieldName, fieldName, presence, valueOf(function (f) {
  2823. return Result.value(function () {
  2824. var args = [];
  2825. for (var _i = 0; _i < arguments.length; _i++) {
  2826. args[_i] = arguments[_i];
  2827. }
  2828. return f.apply(undefined, args);
  2829. });
  2830. }));
  2831. };
  2832. var onHandler = function (fieldName) {
  2833. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  2834. };
  2835. var onKeyboardHandler = function (fieldName) {
  2836. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Optional.none));
  2837. };
  2838. var onStrictHandler = function (fieldName) {
  2839. return onPresenceHandler('onHandler', fieldName, strict());
  2840. };
  2841. var onStrictKeyboardHandler = function (fieldName) {
  2842. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  2843. };
  2844. var output = function (name, value) {
  2845. return state$1(name, constant(value));
  2846. };
  2847. var snapshot = function (name) {
  2848. return state$1(name, identity);
  2849. };
  2850. var initSize = constant(_initSize);
  2851. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  2852. onStrictHandler('onReceive'),
  2853. defaulted$1('schema', anyValue$1())
  2854. ])))];
  2855. var Receiving = create$1({
  2856. fields: ReceivingSchema,
  2857. name: 'receiving',
  2858. active: ActiveReceiving
  2859. });
  2860. var SetupBehaviourCellState = function (initialState) {
  2861. var init = function () {
  2862. var cell = Cell(initialState);
  2863. var get = function () {
  2864. return cell.get();
  2865. };
  2866. var set = function (newState) {
  2867. return cell.set(newState);
  2868. };
  2869. var clear = function () {
  2870. return cell.set(initialState);
  2871. };
  2872. var readState = function () {
  2873. return cell.get();
  2874. };
  2875. return {
  2876. get: get,
  2877. set: set,
  2878. clear: clear,
  2879. readState: readState
  2880. };
  2881. };
  2882. return { init: init };
  2883. };
  2884. var updateAriaState = function (component, toggleConfig, toggleState) {
  2885. var ariaInfo = toggleConfig.aria;
  2886. ariaInfo.update(component, ariaInfo, toggleState.get());
  2887. };
  2888. var updateClass = function (component, toggleConfig, toggleState) {
  2889. toggleConfig.toggleClass.each(function (toggleClass) {
  2890. if (toggleState.get()) {
  2891. add$2(component.element, toggleClass);
  2892. } else {
  2893. remove$4(component.element, toggleClass);
  2894. }
  2895. });
  2896. };
  2897. var toggle = function (component, toggleConfig, toggleState) {
  2898. set$2(component, toggleConfig, toggleState, !toggleState.get());
  2899. };
  2900. var on = function (component, toggleConfig, toggleState) {
  2901. toggleState.set(true);
  2902. updateClass(component, toggleConfig, toggleState);
  2903. updateAriaState(component, toggleConfig, toggleState);
  2904. };
  2905. var off = function (component, toggleConfig, toggleState) {
  2906. toggleState.set(false);
  2907. updateClass(component, toggleConfig, toggleState);
  2908. updateAriaState(component, toggleConfig, toggleState);
  2909. };
  2910. var set$2 = function (component, toggleConfig, toggleState, state) {
  2911. var action = state ? on : off;
  2912. action(component, toggleConfig, toggleState);
  2913. };
  2914. var isOn = function (component, toggleConfig, toggleState) {
  2915. return toggleState.get();
  2916. };
  2917. var onLoad = function (component, toggleConfig, toggleState) {
  2918. set$2(component, toggleConfig, toggleState, toggleConfig.selected);
  2919. };
  2920. var ToggleApis = /*#__PURE__*/Object.freeze({
  2921. __proto__: null,
  2922. onLoad: onLoad,
  2923. toggle: toggle,
  2924. isOn: isOn,
  2925. on: on,
  2926. off: off,
  2927. set: set$2
  2928. });
  2929. var exhibit = function () {
  2930. return nu$5({});
  2931. };
  2932. var events$1 = function (toggleConfig, toggleState) {
  2933. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2934. var load = loadEvent(toggleConfig, toggleState, onLoad);
  2935. return derive(flatten([
  2936. toggleConfig.toggleOnExecute ? [execute] : [],
  2937. [load]
  2938. ]));
  2939. };
  2940. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2941. __proto__: null,
  2942. exhibit: exhibit,
  2943. events: events$1
  2944. });
  2945. var updatePressed = function (component, ariaInfo, status) {
  2946. set(component.element, 'aria-pressed', status);
  2947. if (ariaInfo.syncWithExpanded) {
  2948. updateExpanded(component, ariaInfo, status);
  2949. }
  2950. };
  2951. var updateSelected = function (component, ariaInfo, status) {
  2952. set(component.element, 'aria-selected', status);
  2953. };
  2954. var updateChecked = function (component, ariaInfo, status) {
  2955. set(component.element, 'aria-checked', status);
  2956. };
  2957. var updateExpanded = function (component, ariaInfo, status) {
  2958. set(component.element, 'aria-expanded', status);
  2959. };
  2960. var ToggleSchema = [
  2961. defaulted$1('selected', false),
  2962. option('toggleClass'),
  2963. defaulted$1('toggleOnExecute', true),
  2964. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  2965. pressed: [
  2966. defaulted$1('syncWithExpanded', false),
  2967. output('update', updatePressed)
  2968. ],
  2969. checked: [output('update', updateChecked)],
  2970. expanded: [output('update', updateExpanded)],
  2971. selected: [output('update', updateSelected)],
  2972. none: [output('update', noop)]
  2973. }))
  2974. ];
  2975. var Toggling = create$1({
  2976. fields: ToggleSchema,
  2977. name: 'toggling',
  2978. active: ActiveToggle,
  2979. apis: ToggleApis,
  2980. state: SetupBehaviourCellState(false)
  2981. });
  2982. var format = function (command, update) {
  2983. return Receiving.config({
  2984. channels: wrap$1(formatChanged, {
  2985. onReceive: function (button, data) {
  2986. if (data.command === command) {
  2987. update(button, data.state);
  2988. }
  2989. }
  2990. })
  2991. });
  2992. };
  2993. var orientation = function (onReceive) {
  2994. return Receiving.config({ channels: wrap$1(orientationChanged, { onReceive: onReceive }) });
  2995. };
  2996. var receive$1 = function (channel, onReceive) {
  2997. return {
  2998. key: channel,
  2999. value: { onReceive: onReceive }
  3000. };
  3001. };
  3002. var prefix = 'tinymce-mobile';
  3003. var resolve = function (p) {
  3004. return prefix + '-' + p;
  3005. };
  3006. var pointerEvents = function () {
  3007. var onClick = function (component, simulatedEvent) {
  3008. simulatedEvent.stop();
  3009. emitExecute(component);
  3010. };
  3011. return [
  3012. run(click(), onClick),
  3013. run(tap(), onClick),
  3014. cutter(touchstart()),
  3015. cutter(mousedown())
  3016. ];
  3017. };
  3018. var events$2 = function (optAction) {
  3019. var executeHandler = function (action) {
  3020. return runOnExecute(function (component, simulatedEvent) {
  3021. action(component);
  3022. simulatedEvent.stop();
  3023. });
  3024. };
  3025. return derive(flatten([
  3026. optAction.map(executeHandler).toArray(),
  3027. pointerEvents()
  3028. ]));
  3029. };
  3030. var focus$2 = function (component, focusConfig) {
  3031. if (!focusConfig.ignore) {
  3032. focus$1(component.element);
  3033. focusConfig.onFocus(component);
  3034. }
  3035. };
  3036. var blur$1 = function (component, focusConfig) {
  3037. if (!focusConfig.ignore) {
  3038. blur(component.element);
  3039. }
  3040. };
  3041. var isFocused = function (component) {
  3042. return hasFocus(component.element);
  3043. };
  3044. var FocusApis = /*#__PURE__*/Object.freeze({
  3045. __proto__: null,
  3046. focus: focus$2,
  3047. blur: blur$1,
  3048. isFocused: isFocused
  3049. });
  3050. var exhibit$1 = function (base, focusConfig) {
  3051. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3052. return nu$5(mod);
  3053. };
  3054. var events$3 = function (focusConfig) {
  3055. return derive([run(focus(), function (component, simulatedEvent) {
  3056. focus$2(component, focusConfig);
  3057. simulatedEvent.stop();
  3058. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3059. simulatedEvent.event.prevent();
  3060. })] : []));
  3061. };
  3062. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3063. __proto__: null,
  3064. exhibit: exhibit$1,
  3065. events: events$3
  3066. });
  3067. var FocusSchema = [
  3068. onHandler('onFocus'),
  3069. defaulted$1('stopMousedown', false),
  3070. defaulted$1('ignore', false)
  3071. ];
  3072. var Focusing = create$1({
  3073. fields: FocusSchema,
  3074. name: 'focusing',
  3075. active: ActiveFocus,
  3076. apis: FocusApis
  3077. });
  3078. var isSupported$1 = function (dom) {
  3079. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  3080. };
  3081. var internalSet = function (dom, property, value) {
  3082. if (!isString(value)) {
  3083. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3084. throw new Error('CSS value must be a string: ' + value);
  3085. }
  3086. if (isSupported$1(dom)) {
  3087. dom.style.setProperty(property, value);
  3088. }
  3089. };
  3090. var internalRemove = function (dom, property) {
  3091. if (isSupported$1(dom)) {
  3092. dom.style.removeProperty(property);
  3093. }
  3094. };
  3095. var set$3 = function (element, property, value) {
  3096. var dom = element.dom;
  3097. internalSet(dom, property, value);
  3098. };
  3099. var setAll$1 = function (element, css) {
  3100. var dom = element.dom;
  3101. each$1(css, function (v, k) {
  3102. internalSet(dom, k, v);
  3103. });
  3104. };
  3105. var get$4 = function (element, property) {
  3106. var dom = element.dom;
  3107. var styles = window.getComputedStyle(dom);
  3108. var r = styles.getPropertyValue(property);
  3109. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3110. };
  3111. var getUnsafeProperty = function (dom, property) {
  3112. return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  3113. };
  3114. var getRaw = function (element, property) {
  3115. var dom = element.dom;
  3116. var raw = getUnsafeProperty(dom, property);
  3117. return Optional.from(raw).filter(function (r) {
  3118. return r.length > 0;
  3119. });
  3120. };
  3121. var remove$5 = function (element, property) {
  3122. var dom = element.dom;
  3123. internalRemove(dom, property);
  3124. if (getOpt(element, 'style').map(trim).is('')) {
  3125. remove$1(element, 'style');
  3126. }
  3127. };
  3128. var reflow = function (e) {
  3129. return e.dom.offsetWidth;
  3130. };
  3131. function Dimension (name, getOffset) {
  3132. var set = function (element, h) {
  3133. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3134. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3135. }
  3136. var dom = element.dom;
  3137. if (isSupported$1(dom)) {
  3138. dom.style[name] = h + 'px';
  3139. }
  3140. };
  3141. var get = function (element) {
  3142. var r = getOffset(element);
  3143. if (r <= 0 || r === null) {
  3144. var css = get$4(element, name);
  3145. return parseFloat(css) || 0;
  3146. }
  3147. return r;
  3148. };
  3149. var getOuter = get;
  3150. var aggregate = function (element, properties) {
  3151. return foldl(properties, function (acc, property) {
  3152. var val = get$4(element, property);
  3153. var value = val === undefined ? 0 : parseInt(val, 10);
  3154. return isNaN(value) ? acc : acc + value;
  3155. }, 0);
  3156. };
  3157. var max = function (element, value, properties) {
  3158. var cumulativeInclusions = aggregate(element, properties);
  3159. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3160. return absoluteMax;
  3161. };
  3162. return {
  3163. set: set,
  3164. get: get,
  3165. getOuter: getOuter,
  3166. aggregate: aggregate,
  3167. max: max
  3168. };
  3169. }
  3170. var api = Dimension('height', function (element) {
  3171. var dom = element.dom;
  3172. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3173. });
  3174. var get$5 = function (element) {
  3175. return api.get(element);
  3176. };
  3177. var ancestors = function (scope, predicate, isRoot) {
  3178. return filter(parents(scope, isRoot), predicate);
  3179. };
  3180. var siblings$1 = function (scope, predicate) {
  3181. return filter(siblings(scope), predicate);
  3182. };
  3183. var all$2 = function (selector) {
  3184. return all(selector);
  3185. };
  3186. var ancestors$1 = function (scope, selector, isRoot) {
  3187. return ancestors(scope, function (e) {
  3188. return is(e, selector);
  3189. }, isRoot);
  3190. };
  3191. var siblings$2 = function (scope, selector) {
  3192. return siblings$1(scope, function (e) {
  3193. return is(e, selector);
  3194. });
  3195. };
  3196. var descendants = function (scope, selector) {
  3197. return all(selector, scope);
  3198. };
  3199. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3200. return is(scope, a) ? Optional.some(scope) : isFunction(isRoot) && isRoot(scope) ? Optional.none() : ancestor(scope, a, isRoot);
  3201. }
  3202. var ancestor$1 = function (scope, predicate, isRoot) {
  3203. var element = scope.dom;
  3204. var stop = isFunction(isRoot) ? isRoot : never;
  3205. while (element.parentNode) {
  3206. element = element.parentNode;
  3207. var el = SugarElement.fromDom(element);
  3208. if (predicate(el)) {
  3209. return Optional.some(el);
  3210. } else if (stop(el)) {
  3211. break;
  3212. }
  3213. }
  3214. return Optional.none();
  3215. };
  3216. var closest$1 = function (scope, predicate, isRoot) {
  3217. var is = function (s, test) {
  3218. return test(s);
  3219. };
  3220. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3221. };
  3222. var descendant = function (scope, predicate) {
  3223. var descend = function (node) {
  3224. for (var i = 0; i < node.childNodes.length; i++) {
  3225. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3226. if (predicate(child_1)) {
  3227. return Optional.some(child_1);
  3228. }
  3229. var res = descend(node.childNodes[i]);
  3230. if (res.isSome()) {
  3231. return res;
  3232. }
  3233. }
  3234. return Optional.none();
  3235. };
  3236. return descend(scope.dom);
  3237. };
  3238. var first = function (selector) {
  3239. return one(selector);
  3240. };
  3241. var ancestor$2 = function (scope, selector, isRoot) {
  3242. return ancestor$1(scope, function (e) {
  3243. return is(e, selector);
  3244. }, isRoot);
  3245. };
  3246. var descendant$1 = function (scope, selector) {
  3247. return one(selector, scope);
  3248. };
  3249. var closest$2 = function (scope, selector, isRoot) {
  3250. var is$1 = function (element, selector) {
  3251. return is(element, selector);
  3252. };
  3253. return ClosestOrAncestor(is$1, ancestor$2, scope, selector, isRoot);
  3254. };
  3255. var BACKSPACE = [8];
  3256. var TAB = [9];
  3257. var ENTER = [13];
  3258. var ESCAPE = [27];
  3259. var SPACE = [32];
  3260. var LEFT = [37];
  3261. var UP = [38];
  3262. var RIGHT = [39];
  3263. var DOWN = [40];
  3264. var cyclePrev = function (values, index, predicate) {
  3265. var before = reverse(values.slice(0, index));
  3266. var after = reverse(values.slice(index + 1));
  3267. return find(before.concat(after), predicate);
  3268. };
  3269. var tryPrev = function (values, index, predicate) {
  3270. var before = reverse(values.slice(0, index));
  3271. return find(before, predicate);
  3272. };
  3273. var cycleNext = function (values, index, predicate) {
  3274. var before = values.slice(0, index);
  3275. var after = values.slice(index + 1);
  3276. return find(after.concat(before), predicate);
  3277. };
  3278. var tryNext = function (values, index, predicate) {
  3279. var after = values.slice(index + 1);
  3280. return find(after, predicate);
  3281. };
  3282. var inSet = function (keys) {
  3283. return function (event) {
  3284. var raw = event.raw;
  3285. return contains(keys, raw.which);
  3286. };
  3287. };
  3288. var and = function (preds) {
  3289. return function (event) {
  3290. return forall(preds, function (pred) {
  3291. return pred(event);
  3292. });
  3293. };
  3294. };
  3295. var isShift = function (event) {
  3296. var raw = event.raw;
  3297. return raw.shiftKey === true;
  3298. };
  3299. var isControl = function (event) {
  3300. var raw = event.raw;
  3301. return raw.ctrlKey === true;
  3302. };
  3303. var isNotShift = not(isShift);
  3304. var rule = function (matches, action) {
  3305. return {
  3306. matches: matches,
  3307. classification: action
  3308. };
  3309. };
  3310. var choose$2 = function (transitions, event) {
  3311. var transition = find(transitions, function (t) {
  3312. return t.matches(event);
  3313. });
  3314. return transition.map(function (t) {
  3315. return t.classification;
  3316. });
  3317. };
  3318. var cycleBy = function (value, delta, min, max) {
  3319. var r = value + delta;
  3320. return r > max ? min : r < min ? max : r;
  3321. };
  3322. var clamp = function (value, min, max) {
  3323. return Math.min(Math.max(value, min), max);
  3324. };
  3325. var cat = function (arr) {
  3326. var r = [];
  3327. var push = function (x) {
  3328. r.push(x);
  3329. };
  3330. for (var i = 0; i < arr.length; i++) {
  3331. arr[i].each(push);
  3332. }
  3333. return r;
  3334. };
  3335. var sequence = function (arr) {
  3336. var r = [];
  3337. for (var i = 0; i < arr.length; i++) {
  3338. var x = arr[i];
  3339. if (x.isSome()) {
  3340. r.push(x.getOrDie());
  3341. } else {
  3342. return Optional.none();
  3343. }
  3344. }
  3345. return Optional.some(r);
  3346. };
  3347. var someIf = function (b, a) {
  3348. return b ? Optional.some(a) : Optional.none();
  3349. };
  3350. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3351. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  3352. each(highlighted, function (h) {
  3353. if (!exists(skip, function (skipComp) {
  3354. return skipComp.element === h;
  3355. })) {
  3356. remove$4(h, hConfig.highlightClass);
  3357. component.getSystem().getByDom(h).each(function (target) {
  3358. hConfig.onDehighlight(component, target);
  3359. emit(target, dehighlight());
  3360. });
  3361. }
  3362. });
  3363. };
  3364. var dehighlightAll = function (component, hConfig, hState) {
  3365. return dehighlightAllExcept(component, hConfig, hState, []);
  3366. };
  3367. var dehighlight$1 = function (component, hConfig, hState, target) {
  3368. if (isHighlighted(component, hConfig, hState, target)) {
  3369. remove$4(target.element, hConfig.highlightClass);
  3370. hConfig.onDehighlight(component, target);
  3371. emit(target, dehighlight());
  3372. }
  3373. };
  3374. var highlight$1 = function (component, hConfig, hState, target) {
  3375. dehighlightAllExcept(component, hConfig, hState, [target]);
  3376. if (!isHighlighted(component, hConfig, hState, target)) {
  3377. add$2(target.element, hConfig.highlightClass);
  3378. hConfig.onHighlight(component, target);
  3379. emit(target, highlight());
  3380. }
  3381. };
  3382. var highlightFirst = function (component, hConfig, hState) {
  3383. getFirst(component, hConfig).each(function (firstComp) {
  3384. highlight$1(component, hConfig, hState, firstComp);
  3385. });
  3386. };
  3387. var highlightLast = function (component, hConfig, hState) {
  3388. getLast(component, hConfig).each(function (lastComp) {
  3389. highlight$1(component, hConfig, hState, lastComp);
  3390. });
  3391. };
  3392. var highlightAt = function (component, hConfig, hState, index) {
  3393. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3394. throw new Error(err);
  3395. }, function (firstComp) {
  3396. highlight$1(component, hConfig, hState, firstComp);
  3397. });
  3398. };
  3399. var highlightBy = function (component, hConfig, hState, predicate) {
  3400. var candidates = getCandidates(component, hConfig);
  3401. var targetComp = find(candidates, predicate);
  3402. targetComp.each(function (c) {
  3403. highlight$1(component, hConfig, hState, c);
  3404. });
  3405. };
  3406. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3407. return has$2(queryTarget.element, hConfig.highlightClass);
  3408. };
  3409. var getHighlighted = function (component, hConfig, _hState) {
  3410. return descendant$1(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  3411. return component.getSystem().getByDom(e).toOptional();
  3412. });
  3413. };
  3414. var getByIndex = function (component, hConfig, hState, index) {
  3415. var items = descendants(component.element, '.' + hConfig.itemClass);
  3416. return Optional.from(items[index]).fold(function () {
  3417. return Result.error('No element found with index ' + index);
  3418. }, component.getSystem().getByDom);
  3419. };
  3420. var getFirst = function (component, hConfig, _hState) {
  3421. return descendant$1(component.element, '.' + hConfig.itemClass).bind(function (e) {
  3422. return component.getSystem().getByDom(e).toOptional();
  3423. });
  3424. };
  3425. var getLast = function (component, hConfig, _hState) {
  3426. var items = descendants(component.element, '.' + hConfig.itemClass);
  3427. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  3428. return last.bind(function (c) {
  3429. return component.getSystem().getByDom(c).toOptional();
  3430. });
  3431. };
  3432. var getDelta = function (component, hConfig, hState, delta) {
  3433. var items = descendants(component.element, '.' + hConfig.itemClass);
  3434. var current = findIndex(items, function (item) {
  3435. return has$2(item, hConfig.highlightClass);
  3436. });
  3437. return current.bind(function (selected) {
  3438. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3439. return component.getSystem().getByDom(items[dest]).toOptional();
  3440. });
  3441. };
  3442. var getPrevious = function (component, hConfig, hState) {
  3443. return getDelta(component, hConfig, hState, -1);
  3444. };
  3445. var getNext = function (component, hConfig, hState) {
  3446. return getDelta(component, hConfig, hState, +1);
  3447. };
  3448. var getCandidates = function (component, hConfig, _hState) {
  3449. var items = descendants(component.element, '.' + hConfig.itemClass);
  3450. return cat(map(items, function (i) {
  3451. return component.getSystem().getByDom(i).toOptional();
  3452. }));
  3453. };
  3454. var HighlightApis = /*#__PURE__*/Object.freeze({
  3455. __proto__: null,
  3456. dehighlightAll: dehighlightAll,
  3457. dehighlight: dehighlight$1,
  3458. highlight: highlight$1,
  3459. highlightFirst: highlightFirst,
  3460. highlightLast: highlightLast,
  3461. highlightAt: highlightAt,
  3462. highlightBy: highlightBy,
  3463. isHighlighted: isHighlighted,
  3464. getHighlighted: getHighlighted,
  3465. getFirst: getFirst,
  3466. getLast: getLast,
  3467. getPrevious: getPrevious,
  3468. getNext: getNext,
  3469. getCandidates: getCandidates
  3470. });
  3471. var HighlightSchema = [
  3472. strict$1('highlightClass'),
  3473. strict$1('itemClass'),
  3474. onHandler('onHighlight'),
  3475. onHandler('onDehighlight')
  3476. ];
  3477. var Highlighting = create$1({
  3478. fields: HighlightSchema,
  3479. name: 'highlighting',
  3480. apis: HighlightApis
  3481. });
  3482. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3483. var noChange = prevFocus.exists(function (p) {
  3484. return newFocus.exists(function (n) {
  3485. return eq(n, p);
  3486. });
  3487. });
  3488. if (!noChange) {
  3489. emitWith(component, focusShifted(), {
  3490. prevFocus: prevFocus,
  3491. newFocus: newFocus
  3492. });
  3493. }
  3494. };
  3495. var dom = function () {
  3496. var get = function (component) {
  3497. return search(component.element);
  3498. };
  3499. var set = function (component, focusee) {
  3500. var prevFocus = get(component);
  3501. component.getSystem().triggerFocus(focusee, component.element);
  3502. var newFocus = get(component);
  3503. reportFocusShifting(component, prevFocus, newFocus);
  3504. };
  3505. return {
  3506. get: get,
  3507. set: set
  3508. };
  3509. };
  3510. var highlights = function () {
  3511. var get = function (component) {
  3512. return Highlighting.getHighlighted(component).map(function (item) {
  3513. return item.element;
  3514. });
  3515. };
  3516. var set = function (component, element) {
  3517. var prevFocus = get(component);
  3518. component.getSystem().getByDom(element).fold(noop, function (item) {
  3519. Highlighting.highlight(component, item);
  3520. });
  3521. var newFocus = get(component);
  3522. reportFocusShifting(component, prevFocus, newFocus);
  3523. };
  3524. return {
  3525. get: get,
  3526. set: set
  3527. };
  3528. };
  3529. var FocusInsideModes;
  3530. (function (FocusInsideModes) {
  3531. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3532. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3533. FocusInsideModes['OnApiMode'] = 'onApi';
  3534. }(FocusInsideModes || (FocusInsideModes = {})));
  3535. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3536. var schema = function () {
  3537. return infoSchema.concat([
  3538. defaulted$1('focusManager', dom()),
  3539. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3540. return contains([
  3541. 'onFocus',
  3542. 'onEnterOrSpace',
  3543. 'onApi'
  3544. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3545. })),
  3546. output('handler', me),
  3547. output('state', stateInit),
  3548. output('sendFocusIn', optFocusIn)
  3549. ]);
  3550. };
  3551. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3552. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3553. return choose$2(rules, simulatedEvent.event).bind(function (rule) {
  3554. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3555. });
  3556. };
  3557. var toEvents = function (keyingConfig, keyingState) {
  3558. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3559. return run(focus(), function (component, simulatedEvent) {
  3560. focusIn(component, keyingConfig, keyingState);
  3561. simulatedEvent.stop();
  3562. });
  3563. });
  3564. var tryGoInsideComponent = function (component, simulatedEvent) {
  3565. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  3566. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3567. optFocusIn(keyingConfig).each(function (focusIn) {
  3568. focusIn(component, keyingConfig, keyingState);
  3569. simulatedEvent.stop();
  3570. });
  3571. }
  3572. };
  3573. var keyboardEvents = [
  3574. run(keydown(), function (component, simulatedEvent) {
  3575. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3576. tryGoInsideComponent(component, simulatedEvent);
  3577. }, function (_) {
  3578. simulatedEvent.stop();
  3579. });
  3580. }),
  3581. run(keyup(), function (component, simulatedEvent) {
  3582. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3583. simulatedEvent.stop();
  3584. });
  3585. })
  3586. ];
  3587. return derive(onFocusHandler.toArray().concat(keyboardEvents));
  3588. };
  3589. var me = {
  3590. schema: schema,
  3591. processKey: processKey,
  3592. toEvents: toEvents
  3593. };
  3594. return me;
  3595. };
  3596. var create$2 = function (cyclicField) {
  3597. var schema = [
  3598. option('onEscape'),
  3599. option('onEnter'),
  3600. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3601. defaulted$1('firstTabstop', 0),
  3602. defaulted$1('useTabstopAt', always),
  3603. option('visibilitySelector')
  3604. ].concat([cyclicField]);
  3605. var isVisible = function (tabbingConfig, element) {
  3606. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3607. return closest$2(element, sel);
  3608. }).getOr(element);
  3609. return get$5(target) > 0;
  3610. };
  3611. var findInitial = function (component, tabbingConfig) {
  3612. var tabstops = descendants(component.element, tabbingConfig.selector);
  3613. var visibles = filter(tabstops, function (elem) {
  3614. return isVisible(tabbingConfig, elem);
  3615. });
  3616. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  3617. };
  3618. var findCurrent = function (component, tabbingConfig) {
  3619. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3620. return closest$2(elem, tabbingConfig.selector);
  3621. });
  3622. };
  3623. var isTabstop = function (tabbingConfig, element) {
  3624. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3625. };
  3626. var focusIn = function (component, tabbingConfig, _tabbingState) {
  3627. findInitial(component, tabbingConfig).each(function (target) {
  3628. tabbingConfig.focusManager.set(component, target);
  3629. });
  3630. };
  3631. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3632. return cycle(tabstops, stopIndex, function (elem) {
  3633. return isTabstop(tabbingConfig, elem);
  3634. }).fold(function () {
  3635. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  3636. }, function (target) {
  3637. tabbingConfig.focusManager.set(component, target);
  3638. return Optional.some(true);
  3639. });
  3640. };
  3641. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  3642. var tabstops = descendants(component.element, tabbingConfig.selector);
  3643. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3644. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  3645. return optStopIndex.bind(function (stopIndex) {
  3646. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3647. });
  3648. });
  3649. };
  3650. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  3651. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3652. return go(component, simulatedEvent, tabbingConfig, navigate);
  3653. };
  3654. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  3655. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3656. return go(component, simulatedEvent, tabbingConfig, navigate);
  3657. };
  3658. var execute = function (component, simulatedEvent, tabbingConfig) {
  3659. return tabbingConfig.onEnter.bind(function (f) {
  3660. return f(component, simulatedEvent);
  3661. });
  3662. };
  3663. var exit = function (component, simulatedEvent, tabbingConfig) {
  3664. return tabbingConfig.onEscape.bind(function (f) {
  3665. return f(component, simulatedEvent);
  3666. });
  3667. };
  3668. var getKeydownRules = constant([
  3669. rule(and([
  3670. isShift,
  3671. inSet(TAB)
  3672. ]), goBackwards),
  3673. rule(inSet(TAB), goForwards),
  3674. rule(inSet(ESCAPE), exit),
  3675. rule(and([
  3676. isNotShift,
  3677. inSet(ENTER)
  3678. ]), execute)
  3679. ]);
  3680. var getKeyupRules = constant([]);
  3681. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3682. return Optional.some(focusIn);
  3683. });
  3684. };
  3685. var AcyclicType = create$2(state$1('cyclic', never));
  3686. var CyclicType = create$2(state$1('cyclic', always));
  3687. var inside = function (target) {
  3688. return name(target) === 'input' && get$1(target, 'type') !== 'radio' || name(target) === 'textarea';
  3689. };
  3690. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  3691. dispatch(component, focused, execute());
  3692. return Optional.some(true);
  3693. };
  3694. var defaultExecute = function (component, simulatedEvent, focused) {
  3695. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  3696. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  3697. };
  3698. var stopEventForFirefox = function (_component, _simulatedEvent) {
  3699. return Optional.some(true);
  3700. };
  3701. var schema$1 = [
  3702. defaulted$1('execute', defaultExecute),
  3703. defaulted$1('useSpace', false),
  3704. defaulted$1('useEnter', true),
  3705. defaulted$1('useControlEnter', false),
  3706. defaulted$1('useDown', false)
  3707. ];
  3708. var execute$1 = function (component, simulatedEvent, executeConfig) {
  3709. return executeConfig.execute(component, simulatedEvent, component.element);
  3710. };
  3711. var getKeydownRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  3712. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  3713. var enterExec = executeConfig.useEnter ? ENTER : [];
  3714. var downExec = executeConfig.useDown ? DOWN : [];
  3715. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3716. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  3717. isControl,
  3718. inSet(ENTER)
  3719. ]), execute$1)] : []);
  3720. };
  3721. var getKeyupRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  3722. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  3723. };
  3724. var ExecutionType = typical(schema$1, NoState.init, getKeydownRules, getKeyupRules, function () {
  3725. return Optional.none();
  3726. });
  3727. var flatgrid = function () {
  3728. var dimensions = Cell(Optional.none());
  3729. var setGridSize = function (numRows, numColumns) {
  3730. dimensions.set(Optional.some({
  3731. numRows: numRows,
  3732. numColumns: numColumns
  3733. }));
  3734. };
  3735. var getNumRows = function () {
  3736. return dimensions.get().map(function (d) {
  3737. return d.numRows;
  3738. });
  3739. };
  3740. var getNumColumns = function () {
  3741. return dimensions.get().map(function (d) {
  3742. return d.numColumns;
  3743. });
  3744. };
  3745. return nu$6({
  3746. readState: function () {
  3747. return dimensions.get().map(function (d) {
  3748. return {
  3749. numRows: String(d.numRows),
  3750. numColumns: String(d.numColumns)
  3751. };
  3752. }).getOr({
  3753. numRows: '?',
  3754. numColumns: '?'
  3755. });
  3756. },
  3757. setGridSize: setGridSize,
  3758. getNumRows: getNumRows,
  3759. getNumColumns: getNumColumns
  3760. });
  3761. };
  3762. var init = function (spec) {
  3763. return spec.state(spec);
  3764. };
  3765. var KeyingState = /*#__PURE__*/Object.freeze({
  3766. __proto__: null,
  3767. flatgrid: flatgrid,
  3768. init: init
  3769. });
  3770. var onDirection = function (isLtr, isRtl) {
  3771. return function (element) {
  3772. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3773. };
  3774. };
  3775. var getDirection = function (element) {
  3776. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3777. };
  3778. var useH = function (movement) {
  3779. return function (component, simulatedEvent, config, state) {
  3780. var move = movement(component.element);
  3781. return use(move, component, simulatedEvent, config, state);
  3782. };
  3783. };
  3784. var west = function (moveLeft, moveRight) {
  3785. var movement = onDirection(moveLeft, moveRight);
  3786. return useH(movement);
  3787. };
  3788. var east = function (moveLeft, moveRight) {
  3789. var movement = onDirection(moveRight, moveLeft);
  3790. return useH(movement);
  3791. };
  3792. var useV = function (move) {
  3793. return function (component, simulatedEvent, config, state) {
  3794. return use(move, component, simulatedEvent, config, state);
  3795. };
  3796. };
  3797. var use = function (move, component, simulatedEvent, config, state) {
  3798. var outcome = config.focusManager.get(component).bind(function (focused) {
  3799. return move(component.element, focused, config, state);
  3800. });
  3801. return outcome.map(function (newFocus) {
  3802. config.focusManager.set(component, newFocus);
  3803. return true;
  3804. });
  3805. };
  3806. var north = useV;
  3807. var south = useV;
  3808. var move = useV;
  3809. var isHidden = function (dom) {
  3810. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3811. };
  3812. var isVisible = function (element) {
  3813. return !isHidden(element.dom);
  3814. };
  3815. var locate = function (candidates, predicate) {
  3816. return findIndex(candidates, predicate).map(function (index) {
  3817. return {
  3818. index: index,
  3819. candidates: candidates
  3820. };
  3821. });
  3822. };
  3823. var locateVisible = function (container, current, selector) {
  3824. var predicate = function (x) {
  3825. return eq(x, current);
  3826. };
  3827. var candidates = descendants(container, selector);
  3828. var visible = filter(candidates, isVisible);
  3829. return locate(visible, predicate);
  3830. };
  3831. var findIndex$1 = function (elements, target) {
  3832. return findIndex(elements, function (elem) {
  3833. return eq(target, elem);
  3834. });
  3835. };
  3836. var withGrid = function (values, index, numCols, f) {
  3837. var oldRow = Math.floor(index / numCols);
  3838. var oldColumn = index % numCols;
  3839. return f(oldRow, oldColumn).bind(function (address) {
  3840. var newIndex = address.row * numCols + address.column;
  3841. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  3842. });
  3843. };
  3844. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  3845. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3846. var onLastRow = oldRow === numRows - 1;
  3847. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3848. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3849. return Optional.some({
  3850. row: oldRow,
  3851. column: newColumn
  3852. });
  3853. });
  3854. };
  3855. var cycleVertical = function (values, index, numRows, numCols, delta) {
  3856. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3857. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3858. var onLastRow = newRow === numRows - 1;
  3859. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3860. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  3861. return Optional.some({
  3862. row: newRow,
  3863. column: newCol
  3864. });
  3865. });
  3866. };
  3867. var cycleRight = function (values, index, numRows, numCols) {
  3868. return cycleHorizontal(values, index, numRows, numCols, +1);
  3869. };
  3870. var cycleLeft = function (values, index, numRows, numCols) {
  3871. return cycleHorizontal(values, index, numRows, numCols, -1);
  3872. };
  3873. var cycleUp = function (values, index, numRows, numCols) {
  3874. return cycleVertical(values, index, numRows, numCols, -1);
  3875. };
  3876. var cycleDown = function (values, index, numRows, numCols) {
  3877. return cycleVertical(values, index, numRows, numCols, +1);
  3878. };
  3879. var schema$2 = [
  3880. strict$1('selector'),
  3881. defaulted$1('execute', defaultExecute),
  3882. onKeyboardHandler('onEscape'),
  3883. defaulted$1('captureTab', false),
  3884. initSize()
  3885. ];
  3886. var focusIn = function (component, gridConfig, _gridState) {
  3887. descendant$1(component.element, gridConfig.selector).each(function (first) {
  3888. gridConfig.focusManager.set(component, first);
  3889. });
  3890. };
  3891. var findCurrent = function (component, gridConfig) {
  3892. return gridConfig.focusManager.get(component).bind(function (elem) {
  3893. return closest$2(elem, gridConfig.selector);
  3894. });
  3895. };
  3896. var execute$2 = function (component, simulatedEvent, gridConfig, _gridState) {
  3897. return findCurrent(component, gridConfig).bind(function (focused) {
  3898. return gridConfig.execute(component, simulatedEvent, focused);
  3899. });
  3900. };
  3901. var doMove = function (cycle) {
  3902. return function (element, focused, gridConfig, gridState) {
  3903. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3904. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3905. });
  3906. };
  3907. };
  3908. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  3909. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  3910. };
  3911. var doEscape = function (component, simulatedEvent, gridConfig) {
  3912. return gridConfig.onEscape(component, simulatedEvent);
  3913. };
  3914. var moveLeft = doMove(cycleLeft);
  3915. var moveRight = doMove(cycleRight);
  3916. var moveNorth = doMove(cycleUp);
  3917. var moveSouth = doMove(cycleDown);
  3918. var getKeydownRules$1 = constant([
  3919. rule(inSet(LEFT), west(moveLeft, moveRight)),
  3920. rule(inSet(RIGHT), east(moveLeft, moveRight)),
  3921. rule(inSet(UP), north(moveNorth)),
  3922. rule(inSet(DOWN), south(moveSouth)),
  3923. rule(and([
  3924. isShift,
  3925. inSet(TAB)
  3926. ]), handleTab),
  3927. rule(and([
  3928. isNotShift,
  3929. inSet(TAB)
  3930. ]), handleTab),
  3931. rule(inSet(ESCAPE), doEscape),
  3932. rule(inSet(SPACE.concat(ENTER)), execute$2)
  3933. ]);
  3934. var getKeyupRules$1 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  3935. var FlatgridType = typical(schema$2, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  3936. return Optional.some(focusIn);
  3937. });
  3938. var horizontal = function (container, selector, current, delta) {
  3939. var isDisabledButton = function (candidate) {
  3940. return name(candidate) === 'button' && get$1(candidate, 'disabled') === 'disabled';
  3941. };
  3942. var tryCycle = function (initial, index, candidates) {
  3943. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  3944. if (newIndex === initial) {
  3945. return Optional.none();
  3946. } else {
  3947. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  3948. }
  3949. };
  3950. return locateVisible(container, current, selector).bind(function (identified) {
  3951. var index = identified.index;
  3952. var candidates = identified.candidates;
  3953. return tryCycle(index, index, candidates);
  3954. });
  3955. };
  3956. var schema$3 = [
  3957. strict$1('selector'),
  3958. defaulted$1('getInitial', Optional.none),
  3959. defaulted$1('execute', defaultExecute),
  3960. onKeyboardHandler('onEscape'),
  3961. defaulted$1('executeOnMove', false),
  3962. defaulted$1('allowVertical', true)
  3963. ];
  3964. var findCurrent$1 = function (component, flowConfig) {
  3965. return flowConfig.focusManager.get(component).bind(function (elem) {
  3966. return closest$2(elem, flowConfig.selector);
  3967. });
  3968. };
  3969. var execute$3 = function (component, simulatedEvent, flowConfig) {
  3970. return findCurrent$1(component, flowConfig).bind(function (focused) {
  3971. return flowConfig.execute(component, simulatedEvent, focused);
  3972. });
  3973. };
  3974. var focusIn$1 = function (component, flowConfig, _state) {
  3975. flowConfig.getInitial(component).orThunk(function () {
  3976. return descendant$1(component.element, flowConfig.selector);
  3977. }).each(function (first) {
  3978. flowConfig.focusManager.set(component, first);
  3979. });
  3980. };
  3981. var moveLeft$1 = function (element, focused, info) {
  3982. return horizontal(element, info.selector, focused, -1);
  3983. };
  3984. var moveRight$1 = function (element, focused, info) {
  3985. return horizontal(element, info.selector, focused, +1);
  3986. };
  3987. var doMove$1 = function (movement) {
  3988. return function (component, simulatedEvent, flowConfig, flowState) {
  3989. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  3990. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Optional.some(true);
  3991. });
  3992. };
  3993. };
  3994. var doEscape$1 = function (component, simulatedEvent, flowConfig) {
  3995. return flowConfig.onEscape(component, simulatedEvent);
  3996. };
  3997. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  3998. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  3999. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  4000. return [
  4001. rule(inSet(westMovers), doMove$1(west(moveLeft$1, moveRight$1))),
  4002. rule(inSet(eastMovers), doMove$1(east(moveLeft$1, moveRight$1))),
  4003. rule(inSet(ENTER), execute$3),
  4004. rule(inSet(SPACE), execute$3),
  4005. rule(inSet(ESCAPE), doEscape$1)
  4006. ];
  4007. };
  4008. var getKeyupRules$2 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  4009. var FlowType = typical(schema$3, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  4010. return Optional.some(focusIn$1);
  4011. });
  4012. var toCell = function (matrix, rowIndex, columnIndex) {
  4013. return Optional.from(matrix[rowIndex]).bind(function (row) {
  4014. return Optional.from(row[columnIndex]).map(function (cell) {
  4015. return {
  4016. rowIndex: rowIndex,
  4017. columnIndex: columnIndex,
  4018. cell: cell
  4019. };
  4020. });
  4021. });
  4022. };
  4023. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  4024. var row = matrix[rowIndex];
  4025. var colsInRow = row.length;
  4026. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  4027. return toCell(matrix, rowIndex, newColIndex);
  4028. };
  4029. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  4030. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  4031. var colsInNextRow = matrix[nextRowIndex].length;
  4032. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4033. return toCell(matrix, nextRowIndex, nextColIndex);
  4034. };
  4035. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4036. var row = matrix[rowIndex];
  4037. var colsInRow = row.length;
  4038. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  4039. return toCell(matrix, rowIndex, newColIndex);
  4040. };
  4041. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  4042. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  4043. var colsInNextRow = matrix[nextRowIndex].length;
  4044. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4045. return toCell(matrix, nextRowIndex, nextColIndex);
  4046. };
  4047. var cycleRight$1 = function (matrix, startRow, startCol) {
  4048. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  4049. };
  4050. var cycleLeft$1 = function (matrix, startRow, startCol) {
  4051. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  4052. };
  4053. var cycleUp$1 = function (matrix, startRow, startCol) {
  4054. return cycleVertical$1(matrix, startCol, startRow, -1);
  4055. };
  4056. var cycleDown$1 = function (matrix, startRow, startCol) {
  4057. return cycleVertical$1(matrix, startCol, startRow, +1);
  4058. };
  4059. var moveLeft$2 = function (matrix, startRow, startCol) {
  4060. return moveHorizontal(matrix, startRow, startCol, -1);
  4061. };
  4062. var moveRight$2 = function (matrix, startRow, startCol) {
  4063. return moveHorizontal(matrix, startRow, startCol, +1);
  4064. };
  4065. var moveUp = function (matrix, startRow, startCol) {
  4066. return moveVertical(matrix, startCol, startRow, -1);
  4067. };
  4068. var moveDown = function (matrix, startRow, startCol) {
  4069. return moveVertical(matrix, startCol, startRow, +1);
  4070. };
  4071. var schema$4 = [
  4072. strictObjOf('selectors', [
  4073. strict$1('row'),
  4074. strict$1('cell')
  4075. ]),
  4076. defaulted$1('cycles', true),
  4077. defaulted$1('previousSelector', Optional.none),
  4078. defaulted$1('execute', defaultExecute)
  4079. ];
  4080. var focusIn$2 = function (component, matrixConfig, _state) {
  4081. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4082. var selectors = matrixConfig.selectors;
  4083. return descendant$1(component.element, selectors.cell);
  4084. });
  4085. focused.each(function (cell) {
  4086. matrixConfig.focusManager.set(component, cell);
  4087. });
  4088. };
  4089. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  4090. return search(component.element).bind(function (focused) {
  4091. return matrixConfig.execute(component, simulatedEvent, focused);
  4092. });
  4093. };
  4094. var toMatrix = function (rows, matrixConfig) {
  4095. return map(rows, function (row) {
  4096. return descendants(row, matrixConfig.selectors.cell);
  4097. });
  4098. };
  4099. var doMove$2 = function (ifCycle, ifMove) {
  4100. return function (element, focused, matrixConfig) {
  4101. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4102. return closest$2(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4103. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4104. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  4105. var allRows = descendants(element, matrixConfig.selectors.row);
  4106. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  4107. var matrix = toMatrix(allRows, matrixConfig);
  4108. return move(matrix, rowIndex, colIndex).map(function (next) {
  4109. return next.cell;
  4110. });
  4111. });
  4112. });
  4113. });
  4114. };
  4115. };
  4116. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  4117. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  4118. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  4119. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  4120. var getKeydownRules$3 = constant([
  4121. rule(inSet(LEFT), west(moveLeft$3, moveRight$3)),
  4122. rule(inSet(RIGHT), east(moveLeft$3, moveRight$3)),
  4123. rule(inSet(UP), north(moveNorth$1)),
  4124. rule(inSet(DOWN), south(moveSouth$1)),
  4125. rule(inSet(SPACE.concat(ENTER)), execute$4)
  4126. ]);
  4127. var getKeyupRules$3 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  4128. var MatrixType = typical(schema$4, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4129. return Optional.some(focusIn$2);
  4130. });
  4131. var schema$5 = [
  4132. strict$1('selector'),
  4133. defaulted$1('execute', defaultExecute),
  4134. defaulted$1('moveOnTab', false)
  4135. ];
  4136. var execute$5 = function (component, simulatedEvent, menuConfig) {
  4137. return menuConfig.focusManager.get(component).bind(function (focused) {
  4138. return menuConfig.execute(component, simulatedEvent, focused);
  4139. });
  4140. };
  4141. var focusIn$3 = function (component, menuConfig, _state) {
  4142. descendant$1(component.element, menuConfig.selector).each(function (first) {
  4143. menuConfig.focusManager.set(component, first);
  4144. });
  4145. };
  4146. var moveUp$1 = function (element, focused, info) {
  4147. return horizontal(element, info.selector, focused, -1);
  4148. };
  4149. var moveDown$1 = function (element, focused, info) {
  4150. return horizontal(element, info.selector, focused, +1);
  4151. };
  4152. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  4153. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4154. };
  4155. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  4156. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4157. };
  4158. var getKeydownRules$4 = constant([
  4159. rule(inSet(UP), move(moveUp$1)),
  4160. rule(inSet(DOWN), move(moveDown$1)),
  4161. rule(and([
  4162. isShift,
  4163. inSet(TAB)
  4164. ]), fireShiftTab),
  4165. rule(and([
  4166. isNotShift,
  4167. inSet(TAB)
  4168. ]), fireTab),
  4169. rule(inSet(ENTER), execute$5),
  4170. rule(inSet(SPACE), execute$5)
  4171. ]);
  4172. var getKeyupRules$4 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  4173. var MenuType = typical(schema$5, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  4174. return Optional.some(focusIn$3);
  4175. });
  4176. var schema$6 = [
  4177. onKeyboardHandler('onSpace'),
  4178. onKeyboardHandler('onEnter'),
  4179. onKeyboardHandler('onShiftEnter'),
  4180. onKeyboardHandler('onLeft'),
  4181. onKeyboardHandler('onRight'),
  4182. onKeyboardHandler('onTab'),
  4183. onKeyboardHandler('onShiftTab'),
  4184. onKeyboardHandler('onUp'),
  4185. onKeyboardHandler('onDown'),
  4186. onKeyboardHandler('onEscape'),
  4187. defaulted$1('stopSpaceKeyup', false),
  4188. option('focusIn')
  4189. ];
  4190. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  4191. return [
  4192. rule(inSet(SPACE), specialInfo.onSpace),
  4193. rule(and([
  4194. isNotShift,
  4195. inSet(ENTER)
  4196. ]), specialInfo.onEnter),
  4197. rule(and([
  4198. isShift,
  4199. inSet(ENTER)
  4200. ]), specialInfo.onShiftEnter),
  4201. rule(and([
  4202. isShift,
  4203. inSet(TAB)
  4204. ]), specialInfo.onShiftTab),
  4205. rule(and([
  4206. isNotShift,
  4207. inSet(TAB)
  4208. ]), specialInfo.onTab),
  4209. rule(inSet(UP), specialInfo.onUp),
  4210. rule(inSet(DOWN), specialInfo.onDown),
  4211. rule(inSet(LEFT), specialInfo.onLeft),
  4212. rule(inSet(RIGHT), specialInfo.onRight),
  4213. rule(inSet(SPACE), specialInfo.onSpace),
  4214. rule(inSet(ESCAPE), specialInfo.onEscape)
  4215. ];
  4216. };
  4217. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  4218. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  4219. };
  4220. var SpecialType = typical(schema$6, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  4221. return specialInfo.focusIn;
  4222. });
  4223. var acyclic = AcyclicType.schema();
  4224. var cyclic = CyclicType.schema();
  4225. var flow = FlowType.schema();
  4226. var flatgrid$1 = FlatgridType.schema();
  4227. var matrix = MatrixType.schema();
  4228. var execution = ExecutionType.schema();
  4229. var menu = MenuType.schema();
  4230. var special = SpecialType.schema();
  4231. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4232. __proto__: null,
  4233. acyclic: acyclic,
  4234. cyclic: cyclic,
  4235. flow: flow,
  4236. flatgrid: flatgrid$1,
  4237. matrix: matrix,
  4238. execution: execution,
  4239. menu: menu,
  4240. special: special
  4241. });
  4242. var isFlatgridState = function (keyState) {
  4243. return hasNonNullableKey(keyState, 'setGridSize');
  4244. };
  4245. var Keying = createModes$1({
  4246. branchKey: 'mode',
  4247. branches: KeyboardBranches,
  4248. name: 'keying',
  4249. active: {
  4250. events: function (keyingConfig, keyingState) {
  4251. var handler = keyingConfig.handler;
  4252. return handler.toEvents(keyingConfig, keyingState);
  4253. }
  4254. },
  4255. apis: {
  4256. focusIn: function (component, keyConfig, keyState) {
  4257. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4258. component.getSystem().triggerFocus(component.element, component.element);
  4259. }, function (sendFocusIn) {
  4260. sendFocusIn(component, keyConfig, keyState);
  4261. });
  4262. },
  4263. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4264. if (!isFlatgridState(keyState)) {
  4265. console.error('Layout does not support setGridSize');
  4266. } else {
  4267. keyState.setGridSize(numRows, numColumns);
  4268. }
  4269. }
  4270. },
  4271. state: KeyingState
  4272. });
  4273. var field$1 = function (name, forbidden) {
  4274. return defaultedObjOf(name, {}, map(forbidden, function (f) {
  4275. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4276. }).concat([state$1('dump', identity)]));
  4277. };
  4278. var get$6 = function (data) {
  4279. return data.dump;
  4280. };
  4281. var augment = function (data, original) {
  4282. return __assign(__assign({}, data.dump), derive$1(original));
  4283. };
  4284. var SketchBehaviours = {
  4285. field: field$1,
  4286. augment: augment,
  4287. get: get$6
  4288. };
  4289. var _placeholder = 'placeholder';
  4290. var adt$2 = Adt.generate([
  4291. {
  4292. single: [
  4293. 'required',
  4294. 'valueThunk'
  4295. ]
  4296. },
  4297. {
  4298. multiple: [
  4299. 'required',
  4300. 'valueThunks'
  4301. ]
  4302. }
  4303. ]);
  4304. var isSubstituted = function (spec) {
  4305. return has(spec, 'uiType');
  4306. };
  4307. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4308. if (owner.exists(function (o) {
  4309. return o !== compSpec.owner;
  4310. })) {
  4311. return adt$2.single(true, constant(compSpec));
  4312. }
  4313. return get(placeholders, compSpec.name).fold(function () {
  4314. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4315. }, function (newSpec) {
  4316. return newSpec.replace();
  4317. });
  4318. };
  4319. var scan = function (owner, detail, compSpec, placeholders) {
  4320. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  4321. return subPlaceholder(owner, detail, compSpec, placeholders);
  4322. } else {
  4323. return adt$2.single(false, constant(compSpec));
  4324. }
  4325. };
  4326. var substitute = function (owner, detail, compSpec, placeholders) {
  4327. var base = scan(owner, detail, compSpec, placeholders);
  4328. return base.fold(function (req, valueThunk) {
  4329. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  4330. var childSpecs = get(value, 'components').getOr([]);
  4331. var substituted = bind(childSpecs, function (c) {
  4332. return substitute(owner, detail, c, placeholders);
  4333. });
  4334. return [__assign(__assign({}, value), { components: substituted })];
  4335. }, function (req, valuesThunk) {
  4336. if (isSubstituted(compSpec)) {
  4337. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4338. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4339. return preprocessor(values);
  4340. } else {
  4341. return valuesThunk(detail);
  4342. }
  4343. });
  4344. };
  4345. var substituteAll = function (owner, detail, components, placeholders) {
  4346. return bind(components, function (c) {
  4347. return substitute(owner, detail, c, placeholders);
  4348. });
  4349. };
  4350. var oneReplace = function (label, replacements) {
  4351. var called = false;
  4352. var used = function () {
  4353. return called;
  4354. };
  4355. var replace = function () {
  4356. if (called) {
  4357. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4358. }
  4359. called = true;
  4360. return replacements;
  4361. };
  4362. var required = function () {
  4363. return replacements.fold(function (req, _) {
  4364. return req;
  4365. }, function (req, _) {
  4366. return req;
  4367. });
  4368. };
  4369. return {
  4370. name: constant(label),
  4371. required: required,
  4372. used: used,
  4373. replace: replace
  4374. };
  4375. };
  4376. var substitutePlaces = function (owner, detail, components, placeholders) {
  4377. var ps = map$1(placeholders, function (ph, name) {
  4378. return oneReplace(name, ph);
  4379. });
  4380. var outcome = substituteAll(owner, detail, components, ps);
  4381. each$1(ps, function (p) {
  4382. if (p.used() === false && p.required()) {
  4383. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4384. }
  4385. });
  4386. return outcome;
  4387. };
  4388. var single = adt$2.single;
  4389. var multiple = adt$2.multiple;
  4390. var placeholder = constant(_placeholder);
  4391. var unique = 0;
  4392. var generate$1 = function (prefix) {
  4393. var date = new Date();
  4394. var time = date.getTime();
  4395. var random = Math.floor(Math.random() * 1000000000);
  4396. unique++;
  4397. return prefix + '_' + random + unique + String(time);
  4398. };
  4399. var adt$3 = Adt.generate([
  4400. { required: ['data'] },
  4401. { external: ['data'] },
  4402. { optional: ['data'] },
  4403. { group: ['data'] }
  4404. ]);
  4405. var fFactory = defaulted$1('factory', { sketch: identity });
  4406. var fSchema = defaulted$1('schema', []);
  4407. var fName = strict$1('name');
  4408. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  4409. return '<alloy.' + generate$1(typeSpec.name) + '>';
  4410. }), anyValue$1());
  4411. var fGroupSchema = state$1('schema', function () {
  4412. return [option('preprocess')];
  4413. });
  4414. var fDefaults = defaulted$1('defaults', constant({}));
  4415. var fOverrides = defaulted$1('overrides', constant({}));
  4416. var requiredSpec = objOf([
  4417. fFactory,
  4418. fSchema,
  4419. fName,
  4420. fPname,
  4421. fDefaults,
  4422. fOverrides
  4423. ]);
  4424. var externalSpec = objOf([
  4425. fFactory,
  4426. fSchema,
  4427. fName,
  4428. fDefaults,
  4429. fOverrides
  4430. ]);
  4431. var optionalSpec = objOf([
  4432. fFactory,
  4433. fSchema,
  4434. fName,
  4435. fPname,
  4436. fDefaults,
  4437. fOverrides
  4438. ]);
  4439. var groupSpec = objOf([
  4440. fFactory,
  4441. fGroupSchema,
  4442. fName,
  4443. strict$1('unit'),
  4444. fPname,
  4445. fDefaults,
  4446. fOverrides
  4447. ]);
  4448. var asNamedPart = function (part) {
  4449. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  4450. };
  4451. var name$1 = function (part) {
  4452. var get = function (data) {
  4453. return data.name;
  4454. };
  4455. return part.fold(get, get, get, get);
  4456. };
  4457. var convert = function (adtConstructor, partSchema) {
  4458. return function (spec) {
  4459. var data = asRawOrDie('Converting part type', partSchema, spec);
  4460. return adtConstructor(data);
  4461. };
  4462. };
  4463. var required = convert(adt$3.required, requiredSpec);
  4464. var external = convert(adt$3.external, externalSpec);
  4465. var optional = convert(adt$3.optional, optionalSpec);
  4466. var group = convert(adt$3.group, groupSpec);
  4467. var original = constant('entirety');
  4468. var combine = function (detail, data, partSpec, partValidated) {
  4469. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4470. };
  4471. var subs = function (owner, detail, parts) {
  4472. var internals = {};
  4473. var externals = {};
  4474. each(parts, function (part) {
  4475. part.fold(function (data) {
  4476. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  4477. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4478. });
  4479. }, function (data) {
  4480. var partSpec = detail.parts[data.name];
  4481. externals[data.name] = constant(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  4482. }, function (data) {
  4483. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  4484. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4485. });
  4486. }, function (data) {
  4487. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4488. var units = detail[data.name];
  4489. return map(units, function (u) {
  4490. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4491. });
  4492. });
  4493. });
  4494. });
  4495. return {
  4496. internals: constant(internals),
  4497. externals: constant(externals)
  4498. };
  4499. };
  4500. var generate$2 = function (owner, parts) {
  4501. var r = {};
  4502. each(parts, function (part) {
  4503. asNamedPart(part).each(function (np) {
  4504. var g = doGenerateOne(owner, np.pname);
  4505. r[np.name] = function (config) {
  4506. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4507. return __assign(__assign({}, g), {
  4508. config: config,
  4509. validated: validated
  4510. });
  4511. };
  4512. });
  4513. });
  4514. return r;
  4515. };
  4516. var doGenerateOne = function (owner, pname) {
  4517. return {
  4518. uiType: placeholder(),
  4519. owner: owner,
  4520. name: pname
  4521. };
  4522. };
  4523. var generateOne = function (owner, pname, config) {
  4524. return {
  4525. uiType: placeholder(),
  4526. owner: owner,
  4527. name: pname,
  4528. config: config,
  4529. validated: {}
  4530. };
  4531. };
  4532. var schemas = function (parts) {
  4533. return bind(parts, function (part) {
  4534. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  4535. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  4536. }).toArray();
  4537. });
  4538. };
  4539. var names = function (parts) {
  4540. return map(parts, name$1);
  4541. };
  4542. var substitutes = function (owner, detail, parts) {
  4543. return subs(owner, detail, parts);
  4544. };
  4545. var components = function (owner, detail, internals) {
  4546. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  4547. };
  4548. var getPart = function (component, detail, partKey) {
  4549. var uid = detail.partUids[partKey];
  4550. return component.getSystem().getByUid(uid).toOptional();
  4551. };
  4552. var getPartOrDie = function (component, detail, partKey) {
  4553. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4554. };
  4555. var getAllParts = function (component, detail) {
  4556. var system = component.getSystem();
  4557. return map$1(detail.partUids, function (pUid, _k) {
  4558. return constant(system.getByUid(pUid));
  4559. });
  4560. };
  4561. var defaultUids = function (baseUid, partTypes) {
  4562. var partNames = names(partTypes);
  4563. return wrapAll$1(map(partNames, function (pn) {
  4564. return {
  4565. key: pn,
  4566. value: baseUid + '-' + pn
  4567. };
  4568. }));
  4569. };
  4570. var defaultUidsSchema = function (partTypes) {
  4571. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  4572. return defaultUids(spec.uid, partTypes);
  4573. }), anyValue$1());
  4574. };
  4575. var premadeTag = generate$1('alloy-premade');
  4576. var premade = function (comp) {
  4577. return wrap$1(premadeTag, comp);
  4578. };
  4579. var getPremade = function (spec) {
  4580. return get(spec, premadeTag);
  4581. };
  4582. var makeApi = function (f) {
  4583. return markAsSketchApi(function (component) {
  4584. var rest = [];
  4585. for (var _i = 1; _i < arguments.length; _i++) {
  4586. rest[_i - 1] = arguments[_i];
  4587. }
  4588. return f.apply(void 0, __spreadArrays([
  4589. component.getApis(),
  4590. component
  4591. ], rest));
  4592. }, f);
  4593. };
  4594. var prefix$1 = constant('alloy-id-');
  4595. var idAttr = constant('data-alloy-id');
  4596. var prefix$2 = prefix$1();
  4597. var idAttr$1 = idAttr();
  4598. var write = function (label, elem) {
  4599. var id = generate$1(prefix$2 + label);
  4600. writeOnly(elem, id);
  4601. return id;
  4602. };
  4603. var writeOnly = function (elem, uid) {
  4604. Object.defineProperty(elem.dom, idAttr$1, {
  4605. value: uid,
  4606. writable: true
  4607. });
  4608. };
  4609. var read$2 = function (elem) {
  4610. var id = isElement(elem) ? elem.dom[idAttr$1] : null;
  4611. return Optional.from(id);
  4612. };
  4613. var generate$3 = function (prefix) {
  4614. return generate$1(prefix);
  4615. };
  4616. var base = function (partSchemas, partUidsSchemas) {
  4617. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  4618. return ps.concat([
  4619. strict$1('uid'),
  4620. defaulted$1('dom', {}),
  4621. defaulted$1('components', []),
  4622. snapshot('originalSpec'),
  4623. defaulted$1('debug.sketcher', {})
  4624. ]).concat(partUidsSchemas);
  4625. };
  4626. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4627. var baseS = base(partSchemas, partUidsSchemas);
  4628. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4629. };
  4630. var single$1 = function (owner, schema, factory, spec) {
  4631. var specWithUid = supplyUid(spec);
  4632. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  4633. return factory(detail, specWithUid);
  4634. };
  4635. var composite = function (owner, schema, partTypes, factory, spec) {
  4636. var specWithUid = supplyUid(spec);
  4637. var partSchemas = schemas(partTypes);
  4638. var partUidsSchema = defaultUidsSchema(partTypes);
  4639. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4640. var subs = substitutes(owner, detail, partTypes);
  4641. var components$1 = components(owner, detail, subs.internals());
  4642. return factory(detail, components$1, specWithUid, subs.externals());
  4643. };
  4644. var hasUid = function (spec) {
  4645. return has(spec, 'uid');
  4646. };
  4647. var supplyUid = function (spec) {
  4648. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$3('uid') });
  4649. };
  4650. function isSketchSpec(spec) {
  4651. return spec.uid !== undefined;
  4652. }
  4653. var singleSchema = objOfOnly([
  4654. strict$1('name'),
  4655. strict$1('factory'),
  4656. strict$1('configFields'),
  4657. defaulted$1('apis', {}),
  4658. defaulted$1('extraApis', {})
  4659. ]);
  4660. var compositeSchema = objOfOnly([
  4661. strict$1('name'),
  4662. strict$1('factory'),
  4663. strict$1('configFields'),
  4664. strict$1('partFields'),
  4665. defaulted$1('apis', {}),
  4666. defaulted$1('extraApis', {})
  4667. ]);
  4668. var single$2 = function (rawConfig) {
  4669. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4670. var sketch = function (spec) {
  4671. return single$1(config.name, config.configFields, config.factory, spec);
  4672. };
  4673. var apis = map$1(config.apis, makeApi);
  4674. var extraApis = map$1(config.extraApis, function (f, k) {
  4675. return markAsExtraApi(f, k);
  4676. });
  4677. return __assign(__assign({
  4678. name: config.name,
  4679. configFields: config.configFields,
  4680. sketch: sketch
  4681. }, apis), extraApis);
  4682. };
  4683. var composite$1 = function (rawConfig) {
  4684. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4685. var sketch = function (spec) {
  4686. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  4687. };
  4688. var parts = generate$2(config.name, config.partFields);
  4689. var apis = map$1(config.apis, makeApi);
  4690. var extraApis = map$1(config.extraApis, function (f, k) {
  4691. return markAsExtraApi(f, k);
  4692. });
  4693. return __assign(__assign({
  4694. name: config.name,
  4695. partFields: config.partFields,
  4696. configFields: config.configFields,
  4697. sketch: sketch,
  4698. parts: parts
  4699. }, apis), extraApis);
  4700. };
  4701. var factory = function (detail) {
  4702. var events = events$2(detail.action);
  4703. var tag = detail.dom.tag;
  4704. var lookupAttr = function (attr) {
  4705. return get(detail.dom, 'attributes').bind(function (attrs) {
  4706. return get(attrs, attr);
  4707. });
  4708. };
  4709. var getModAttributes = function () {
  4710. if (tag === 'button') {
  4711. var type = lookupAttr('type').getOr('button');
  4712. var roleAttrs = lookupAttr('role').map(function (role) {
  4713. return { role: role };
  4714. }).getOr({});
  4715. return __assign({ type: type }, roleAttrs);
  4716. } else {
  4717. var role = lookupAttr('role').getOr('button');
  4718. return { role: role };
  4719. }
  4720. };
  4721. return {
  4722. uid: detail.uid,
  4723. dom: detail.dom,
  4724. components: detail.components,
  4725. events: events,
  4726. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4727. Focusing.config({}),
  4728. Keying.config({
  4729. mode: 'execution',
  4730. useSpace: true,
  4731. useEnter: true
  4732. })
  4733. ]),
  4734. domModification: { attributes: getModAttributes() },
  4735. eventOrder: detail.eventOrder
  4736. };
  4737. };
  4738. var Button = single$2({
  4739. name: 'Button',
  4740. factory: factory,
  4741. configFields: [
  4742. defaulted$1('uid', undefined),
  4743. strict$1('dom'),
  4744. defaulted$1('components', []),
  4745. SketchBehaviours.field('buttonBehaviours', [
  4746. Focusing,
  4747. Keying
  4748. ]),
  4749. option('action'),
  4750. option('role'),
  4751. defaulted$1('eventOrder', {})
  4752. ]
  4753. });
  4754. var exhibit$2 = function () {
  4755. return nu$5({
  4756. styles: {
  4757. '-webkit-user-select': 'none',
  4758. 'user-select': 'none',
  4759. '-ms-user-select': 'none',
  4760. '-moz-user-select': '-moz-none'
  4761. },
  4762. attributes: { unselectable: 'on' }
  4763. });
  4764. };
  4765. var events$4 = function () {
  4766. return derive([abort(selectstart(), always)]);
  4767. };
  4768. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4769. __proto__: null,
  4770. events: events$4,
  4771. exhibit: exhibit$2
  4772. });
  4773. var Unselecting = create$1({
  4774. fields: [],
  4775. name: 'unselecting',
  4776. active: ActiveUnselecting
  4777. });
  4778. var getAttrs = function (elem) {
  4779. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  4780. return foldl(attributes, function (b, attr) {
  4781. var _a;
  4782. if (attr.name === 'class') {
  4783. return b;
  4784. } else {
  4785. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4786. }
  4787. }, {});
  4788. };
  4789. var getClasses = function (elem) {
  4790. return Array.prototype.slice.call(elem.dom.classList, 0);
  4791. };
  4792. var fromHtml$2 = function (html) {
  4793. var elem = SugarElement.fromHtml(html);
  4794. var children$1 = children(elem);
  4795. var attrs = getAttrs(elem);
  4796. var classes = getClasses(elem);
  4797. var contents = children$1.length === 0 ? {} : { innerHtml: get$3(elem) };
  4798. return __assign({
  4799. tag: name(elem),
  4800. classes: classes,
  4801. attributes: attrs
  4802. }, contents);
  4803. };
  4804. var dom$1 = function (rawHtml) {
  4805. var html = supplant(rawHtml, { prefix: prefix });
  4806. return fromHtml$2(html);
  4807. };
  4808. var spec = function (rawHtml) {
  4809. return { dom: dom$1(rawHtml) };
  4810. };
  4811. var forToolbarCommand = function (editor, command) {
  4812. return forToolbar(command, function () {
  4813. editor.execCommand(command);
  4814. }, {}, editor);
  4815. };
  4816. var getToggleBehaviours = function (command) {
  4817. return derive$1([
  4818. Toggling.config({
  4819. toggleClass: resolve('toolbar-button-selected'),
  4820. toggleOnExecute: false,
  4821. aria: { mode: 'pressed' }
  4822. }),
  4823. format(command, function (button, status) {
  4824. var toggle = status ? Toggling.on : Toggling.off;
  4825. toggle(button);
  4826. })
  4827. ]);
  4828. };
  4829. var forToolbarStateCommand = function (editor, command) {
  4830. var extraBehaviours = getToggleBehaviours(command);
  4831. return forToolbar(command, function () {
  4832. editor.execCommand(command);
  4833. }, extraBehaviours, editor);
  4834. };
  4835. var forToolbarStateAction = function (editor, clazz, command, action) {
  4836. var extraBehaviours = getToggleBehaviours(command);
  4837. return forToolbar(clazz, action, extraBehaviours, editor);
  4838. };
  4839. var getToolbarIconButton = function (clazz, editor) {
  4840. var icons = editor.ui.registry.getAll().icons;
  4841. var optOxideIcon = Optional.from(icons[clazz]);
  4842. return optOxideIcon.fold(function () {
  4843. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4844. }, function (icon) {
  4845. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4846. });
  4847. };
  4848. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4849. return Button.sketch({
  4850. dom: getToolbarIconButton(clazz, editor),
  4851. action: action,
  4852. buttonBehaviours: deepMerge(derive$1([Unselecting.config({})]), extraBehaviours)
  4853. });
  4854. };
  4855. var labelPart = optional({
  4856. schema: [strict$1('dom')],
  4857. name: 'label'
  4858. });
  4859. var edgePart = function (name) {
  4860. return optional({
  4861. name: '' + name + '-edge',
  4862. overrides: function (detail) {
  4863. var action = detail.model.manager.edgeActions[name];
  4864. return action.fold(function () {
  4865. return {};
  4866. }, function (a) {
  4867. return {
  4868. events: derive([
  4869. runActionExtra(touchstart(), function (comp, se, d) {
  4870. return a(comp, d);
  4871. }, [detail]),
  4872. runActionExtra(mousedown(), function (comp, se, d) {
  4873. return a(comp, d);
  4874. }, [detail]),
  4875. runActionExtra(mousemove(), function (comp, se, det) {
  4876. if (det.mouseIsDown.get()) {
  4877. a(comp, det);
  4878. }
  4879. }, [detail])
  4880. ])
  4881. };
  4882. });
  4883. }
  4884. });
  4885. };
  4886. var tlEdgePart = edgePart('top-left');
  4887. var tedgePart = edgePart('top');
  4888. var trEdgePart = edgePart('top-right');
  4889. var redgePart = edgePart('right');
  4890. var brEdgePart = edgePart('bottom-right');
  4891. var bedgePart = edgePart('bottom');
  4892. var blEdgePart = edgePart('bottom-left');
  4893. var ledgePart = edgePart('left');
  4894. var thumbPart = required({
  4895. name: 'thumb',
  4896. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  4897. overrides: function (detail) {
  4898. return {
  4899. events: derive([
  4900. redirectToPart(touchstart(), detail, 'spectrum'),
  4901. redirectToPart(touchmove(), detail, 'spectrum'),
  4902. redirectToPart(touchend(), detail, 'spectrum'),
  4903. redirectToPart(mousedown(), detail, 'spectrum'),
  4904. redirectToPart(mousemove(), detail, 'spectrum'),
  4905. redirectToPart(mouseup(), detail, 'spectrum')
  4906. ])
  4907. };
  4908. }
  4909. });
  4910. var spectrumPart = required({
  4911. schema: [state$1('mouseIsDown', function () {
  4912. return Cell(false);
  4913. })],
  4914. name: 'spectrum',
  4915. overrides: function (detail) {
  4916. var modelDetail = detail.model;
  4917. var model = modelDetail.manager;
  4918. var setValueFrom = function (component, simulatedEvent) {
  4919. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  4920. return model.setValueFrom(component, detail, value);
  4921. });
  4922. };
  4923. return {
  4924. behaviours: derive$1([
  4925. Keying.config({
  4926. mode: 'special',
  4927. onLeft: function (spectrum) {
  4928. return model.onLeft(spectrum, detail);
  4929. },
  4930. onRight: function (spectrum) {
  4931. return model.onRight(spectrum, detail);
  4932. },
  4933. onUp: function (spectrum) {
  4934. return model.onUp(spectrum, detail);
  4935. },
  4936. onDown: function (spectrum) {
  4937. return model.onDown(spectrum, detail);
  4938. }
  4939. }),
  4940. Focusing.config({})
  4941. ]),
  4942. events: derive([
  4943. run(touchstart(), setValueFrom),
  4944. run(touchmove(), setValueFrom),
  4945. run(mousedown(), setValueFrom),
  4946. run(mousemove(), function (spectrum, se) {
  4947. if (detail.mouseIsDown.get()) {
  4948. setValueFrom(spectrum, se);
  4949. }
  4950. })
  4951. ])
  4952. };
  4953. }
  4954. });
  4955. var SliderParts = [
  4956. labelPart,
  4957. ledgePart,
  4958. redgePart,
  4959. tedgePart,
  4960. bedgePart,
  4961. tlEdgePart,
  4962. trEdgePart,
  4963. blEdgePart,
  4964. brEdgePart,
  4965. thumbPart,
  4966. spectrumPart
  4967. ];
  4968. var onLoad$1 = function (component, repConfig, repState) {
  4969. repConfig.store.manager.onLoad(component, repConfig, repState);
  4970. };
  4971. var onUnload = function (component, repConfig, repState) {
  4972. repConfig.store.manager.onUnload(component, repConfig, repState);
  4973. };
  4974. var setValue = function (component, repConfig, repState, data) {
  4975. repConfig.store.manager.setValue(component, repConfig, repState, data);
  4976. };
  4977. var getValue = function (component, repConfig, repState) {
  4978. return repConfig.store.manager.getValue(component, repConfig, repState);
  4979. };
  4980. var getState = function (component, repConfig, repState) {
  4981. return repState;
  4982. };
  4983. var RepresentApis = /*#__PURE__*/Object.freeze({
  4984. __proto__: null,
  4985. onLoad: onLoad$1,
  4986. onUnload: onUnload,
  4987. setValue: setValue,
  4988. getValue: getValue,
  4989. getState: getState
  4990. });
  4991. var events$5 = function (repConfig, repState) {
  4992. var es = repConfig.resetOnDom ? [
  4993. runOnAttached(function (comp, _se) {
  4994. onLoad$1(comp, repConfig, repState);
  4995. }),
  4996. runOnDetached(function (comp, _se) {
  4997. onUnload(comp, repConfig, repState);
  4998. })
  4999. ] : [loadEvent(repConfig, repState, onLoad$1)];
  5000. return derive(es);
  5001. };
  5002. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5003. __proto__: null,
  5004. events: events$5
  5005. });
  5006. var memory = function () {
  5007. var data = Cell(null);
  5008. var readState = function () {
  5009. return {
  5010. mode: 'memory',
  5011. value: data.get()
  5012. };
  5013. };
  5014. var isNotSet = function () {
  5015. return data.get() === null;
  5016. };
  5017. var clear = function () {
  5018. data.set(null);
  5019. };
  5020. return nu$6({
  5021. set: data.set,
  5022. get: data.get,
  5023. isNotSet: isNotSet,
  5024. clear: clear,
  5025. readState: readState
  5026. });
  5027. };
  5028. var manual = function () {
  5029. var readState = function () {
  5030. };
  5031. return nu$6({ readState: readState });
  5032. };
  5033. var dataset = function () {
  5034. var dataByValue = Cell({});
  5035. var dataByText = Cell({});
  5036. var readState = function () {
  5037. return {
  5038. mode: 'dataset',
  5039. dataByValue: dataByValue.get(),
  5040. dataByText: dataByText.get()
  5041. };
  5042. };
  5043. var clear = function () {
  5044. dataByValue.set({});
  5045. dataByText.set({});
  5046. };
  5047. var lookup = function (itemString) {
  5048. return get(dataByValue.get(), itemString).orThunk(function () {
  5049. return get(dataByText.get(), itemString);
  5050. });
  5051. };
  5052. var update = function (items) {
  5053. var currentDataByValue = dataByValue.get();
  5054. var currentDataByText = dataByText.get();
  5055. var newDataByValue = {};
  5056. var newDataByText = {};
  5057. each(items, function (item) {
  5058. newDataByValue[item.value] = item;
  5059. get(item, 'meta').each(function (meta) {
  5060. get(meta, 'text').each(function (text) {
  5061. newDataByText[text] = item;
  5062. });
  5063. });
  5064. });
  5065. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5066. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5067. };
  5068. return nu$6({
  5069. readState: readState,
  5070. lookup: lookup,
  5071. update: update,
  5072. clear: clear
  5073. });
  5074. };
  5075. var init$1 = function (spec) {
  5076. return spec.store.manager.state(spec);
  5077. };
  5078. var RepresentState = /*#__PURE__*/Object.freeze({
  5079. __proto__: null,
  5080. memory: memory,
  5081. dataset: dataset,
  5082. manual: manual,
  5083. init: init$1
  5084. });
  5085. var setValue$1 = function (component, repConfig, repState, data) {
  5086. var store = repConfig.store;
  5087. repState.update([data]);
  5088. store.setValue(component, data);
  5089. repConfig.onSetValue(component, data);
  5090. };
  5091. var getValue$1 = function (component, repConfig, repState) {
  5092. var store = repConfig.store;
  5093. var key = store.getDataKey(component);
  5094. return repState.lookup(key).fold(function () {
  5095. return store.getFallbackEntry(key);
  5096. }, function (data) {
  5097. return data;
  5098. });
  5099. };
  5100. var onLoad$2 = function (component, repConfig, repState) {
  5101. var store = repConfig.store;
  5102. store.initialValue.each(function (data) {
  5103. setValue$1(component, repConfig, repState, data);
  5104. });
  5105. };
  5106. var onUnload$1 = function (component, repConfig, repState) {
  5107. repState.clear();
  5108. };
  5109. var DatasetStore = [
  5110. option('initialValue'),
  5111. strict$1('getFallbackEntry'),
  5112. strict$1('getDataKey'),
  5113. strict$1('setValue'),
  5114. output('manager', {
  5115. setValue: setValue$1,
  5116. getValue: getValue$1,
  5117. onLoad: onLoad$2,
  5118. onUnload: onUnload$1,
  5119. state: dataset
  5120. })
  5121. ];
  5122. var getValue$2 = function (component, repConfig, _repState) {
  5123. return repConfig.store.getValue(component);
  5124. };
  5125. var setValue$2 = function (component, repConfig, _repState, data) {
  5126. repConfig.store.setValue(component, data);
  5127. repConfig.onSetValue(component, data);
  5128. };
  5129. var onLoad$3 = function (component, repConfig, _repState) {
  5130. repConfig.store.initialValue.each(function (data) {
  5131. repConfig.store.setValue(component, data);
  5132. });
  5133. };
  5134. var ManualStore = [
  5135. strict$1('getValue'),
  5136. defaulted$1('setValue', noop),
  5137. option('initialValue'),
  5138. output('manager', {
  5139. setValue: setValue$2,
  5140. getValue: getValue$2,
  5141. onLoad: onLoad$3,
  5142. onUnload: noop,
  5143. state: NoState.init
  5144. })
  5145. ];
  5146. var setValue$3 = function (component, repConfig, repState, data) {
  5147. repState.set(data);
  5148. repConfig.onSetValue(component, data);
  5149. };
  5150. var getValue$3 = function (component, repConfig, repState) {
  5151. return repState.get();
  5152. };
  5153. var onLoad$4 = function (component, repConfig, repState) {
  5154. repConfig.store.initialValue.each(function (initVal) {
  5155. if (repState.isNotSet()) {
  5156. repState.set(initVal);
  5157. }
  5158. });
  5159. };
  5160. var onUnload$2 = function (component, repConfig, repState) {
  5161. repState.clear();
  5162. };
  5163. var MemoryStore = [
  5164. option('initialValue'),
  5165. output('manager', {
  5166. setValue: setValue$3,
  5167. getValue: getValue$3,
  5168. onLoad: onLoad$4,
  5169. onUnload: onUnload$2,
  5170. state: memory
  5171. })
  5172. ];
  5173. var RepresentSchema = [
  5174. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5175. memory: MemoryStore,
  5176. manual: ManualStore,
  5177. dataset: DatasetStore
  5178. })),
  5179. onHandler('onSetValue'),
  5180. defaulted$1('resetOnDom', false)
  5181. ];
  5182. var Representing = create$1({
  5183. fields: RepresentSchema,
  5184. name: 'representing',
  5185. active: ActiveRepresenting,
  5186. apis: RepresentApis,
  5187. extra: {
  5188. setValueFrom: function (component, source) {
  5189. var value = Representing.getValue(source);
  5190. Representing.setValue(component, value);
  5191. }
  5192. },
  5193. state: RepresentState
  5194. });
  5195. var api$1 = Dimension('width', function (element) {
  5196. return element.dom.offsetWidth;
  5197. });
  5198. var set$4 = function (element, h) {
  5199. return api$1.set(element, h);
  5200. };
  5201. var get$7 = function (element) {
  5202. return api$1.get(element);
  5203. };
  5204. var r = function (left, top) {
  5205. var translate = function (x, y) {
  5206. return r(left + x, top + y);
  5207. };
  5208. return {
  5209. left: left,
  5210. top: top,
  5211. translate: translate
  5212. };
  5213. };
  5214. var SugarPosition = r;
  5215. var _sliderChangeEvent = 'slider.change.value';
  5216. var sliderChangeEvent = constant(_sliderChangeEvent);
  5217. var isTouchEvent = function (evt) {
  5218. return evt.type.indexOf('touch') !== -1;
  5219. };
  5220. var getEventSource = function (simulatedEvent) {
  5221. var evt = simulatedEvent.event.raw;
  5222. if (isTouchEvent(evt)) {
  5223. var touchEvent = evt;
  5224. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  5225. return SugarPosition(t.clientX, t.clientY);
  5226. }) : Optional.none();
  5227. } else {
  5228. var mouseEvent = evt;
  5229. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  5230. return SugarPosition(me.clientX, me.clientY);
  5231. }) : Optional.none();
  5232. }
  5233. };
  5234. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  5235. var minX = function (detail) {
  5236. return detail.model.minX;
  5237. };
  5238. var minY = function (detail) {
  5239. return detail.model.minY;
  5240. };
  5241. var min1X = function (detail) {
  5242. return detail.model.minX - 1;
  5243. };
  5244. var min1Y = function (detail) {
  5245. return detail.model.minY - 1;
  5246. };
  5247. var maxX = function (detail) {
  5248. return detail.model.maxX;
  5249. };
  5250. var maxY = function (detail) {
  5251. return detail.model.maxY;
  5252. };
  5253. var max1X = function (detail) {
  5254. return detail.model.maxX + 1;
  5255. };
  5256. var max1Y = function (detail) {
  5257. return detail.model.maxY + 1;
  5258. };
  5259. var range = function (detail, max, min) {
  5260. return max(detail) - min(detail);
  5261. };
  5262. var xRange = function (detail) {
  5263. return range(detail, maxX, minX);
  5264. };
  5265. var yRange = function (detail) {
  5266. return range(detail, maxY, minY);
  5267. };
  5268. var halfX = function (detail) {
  5269. return xRange(detail) / 2;
  5270. };
  5271. var halfY = function (detail) {
  5272. return yRange(detail) / 2;
  5273. };
  5274. var step = function (detail) {
  5275. return detail.stepSize;
  5276. };
  5277. var snap = function (detail) {
  5278. return detail.snapToGrid;
  5279. };
  5280. var snapStart = function (detail) {
  5281. return detail.snapStart;
  5282. };
  5283. var rounded = function (detail) {
  5284. return detail.rounded;
  5285. };
  5286. var hasEdge = function (detail, edgeName) {
  5287. return detail[edgeName + '-edge'] !== undefined;
  5288. };
  5289. var hasLEdge = function (detail) {
  5290. return hasEdge(detail, l);
  5291. };
  5292. var hasREdge = function (detail) {
  5293. return hasEdge(detail, r$1);
  5294. };
  5295. var hasTEdge = function (detail) {
  5296. return hasEdge(detail, t);
  5297. };
  5298. var hasBEdge = function (detail) {
  5299. return hasEdge(detail, b);
  5300. };
  5301. var currentValue = function (detail) {
  5302. return detail.model.value.get();
  5303. };
  5304. var xValue = function (x) {
  5305. return { x: x };
  5306. };
  5307. var yValue = function (y) {
  5308. return { y: y };
  5309. };
  5310. var xyValue = function (x, y) {
  5311. return {
  5312. x: x,
  5313. y: y
  5314. };
  5315. };
  5316. var fireSliderChange = function (component, value) {
  5317. emitWith(component, sliderChangeEvent(), { value: value });
  5318. };
  5319. var setToTLEdgeXY = function (edge, detail) {
  5320. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  5321. };
  5322. var setToTEdge = function (edge, detail) {
  5323. fireSliderChange(edge, yValue(min1Y(detail)));
  5324. };
  5325. var setToTEdgeXY = function (edge, detail) {
  5326. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  5327. };
  5328. var setToTREdgeXY = function (edge, detail) {
  5329. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  5330. };
  5331. var setToREdge = function (edge, detail) {
  5332. fireSliderChange(edge, xValue(max1X(detail)));
  5333. };
  5334. var setToREdgeXY = function (edge, detail) {
  5335. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  5336. };
  5337. var setToBREdgeXY = function (edge, detail) {
  5338. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  5339. };
  5340. var setToBEdge = function (edge, detail) {
  5341. fireSliderChange(edge, yValue(max1Y(detail)));
  5342. };
  5343. var setToBEdgeXY = function (edge, detail) {
  5344. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  5345. };
  5346. var setToBLEdgeXY = function (edge, detail) {
  5347. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  5348. };
  5349. var setToLEdge = function (edge, detail) {
  5350. fireSliderChange(edge, xValue(min1X(detail)));
  5351. };
  5352. var setToLEdgeXY = function (edge, detail) {
  5353. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  5354. };
  5355. var reduceBy = function (value, min, max, step) {
  5356. if (value < min) {
  5357. return value;
  5358. } else if (value > max) {
  5359. return max;
  5360. } else if (value === min) {
  5361. return min - 1;
  5362. } else {
  5363. return Math.max(min, value - step);
  5364. }
  5365. };
  5366. var increaseBy = function (value, min, max, step) {
  5367. if (value > max) {
  5368. return value;
  5369. } else if (value < min) {
  5370. return min;
  5371. } else if (value === max) {
  5372. return max + 1;
  5373. } else {
  5374. return Math.min(max, value + step);
  5375. }
  5376. };
  5377. var capValue = function (value, min, max) {
  5378. return Math.max(min, Math.min(max, value));
  5379. };
  5380. var snapValueOf = function (value, min, max, step, snapStart) {
  5381. return snapStart.fold(function () {
  5382. var initValue = value - min;
  5383. var extraValue = Math.round(initValue / step) * step;
  5384. return capValue(min + extraValue, min - 1, max + 1);
  5385. }, function (start) {
  5386. var remainder = (value - start) % step;
  5387. var adjustment = Math.round(remainder / step);
  5388. var rawSteps = Math.floor((value - start) / step);
  5389. var maxSteps = Math.floor((max - start) / step);
  5390. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5391. var r = start + numSteps * step;
  5392. return Math.max(start, r);
  5393. });
  5394. };
  5395. var findOffsetOf = function (value, min, max) {
  5396. return Math.min(max, Math.max(value, min)) - min;
  5397. };
  5398. var findValueOf = function (args) {
  5399. 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;
  5400. var capMin = hasMinEdge ? min - 1 : min;
  5401. var capMax = hasMaxEdge ? max + 1 : max;
  5402. if (value < minBound) {
  5403. return capMin;
  5404. } else if (value > maxBound) {
  5405. return capMax;
  5406. } else {
  5407. var offset = findOffsetOf(value, minBound, maxBound);
  5408. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5409. if (snap && newValue >= min && newValue <= max) {
  5410. return snapValueOf(newValue, min, max, step, snapStart);
  5411. } else if (rounded) {
  5412. return Math.round(newValue);
  5413. } else {
  5414. return newValue;
  5415. }
  5416. }
  5417. };
  5418. var findOffsetOfValue = function (args) {
  5419. 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;
  5420. if (value < min) {
  5421. return hasMinEdge ? 0 : centerMinEdge;
  5422. } else if (value > max) {
  5423. return hasMaxEdge ? maxBound : centerMaxEdge;
  5424. } else {
  5425. return (value - min) / range * maxOffset;
  5426. }
  5427. };
  5428. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5429. var getBounds = function (component) {
  5430. return component.element.dom.getBoundingClientRect();
  5431. };
  5432. var getBoundsProperty = function (bounds, property) {
  5433. return bounds[property];
  5434. };
  5435. var getMinXBounds = function (component) {
  5436. var bounds = getBounds(component);
  5437. return getBoundsProperty(bounds, left);
  5438. };
  5439. var getMaxXBounds = function (component) {
  5440. var bounds = getBounds(component);
  5441. return getBoundsProperty(bounds, right);
  5442. };
  5443. var getMinYBounds = function (component) {
  5444. var bounds = getBounds(component);
  5445. return getBoundsProperty(bounds, top);
  5446. };
  5447. var getMaxYBounds = function (component) {
  5448. var bounds = getBounds(component);
  5449. return getBoundsProperty(bounds, bottom);
  5450. };
  5451. var getXScreenRange = function (component) {
  5452. var bounds = getBounds(component);
  5453. return getBoundsProperty(bounds, width);
  5454. };
  5455. var getYScreenRange = function (component) {
  5456. var bounds = getBounds(component);
  5457. return getBoundsProperty(bounds, height);
  5458. };
  5459. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5460. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5461. };
  5462. var getXCenterOffSetOf = function (component, spectrum) {
  5463. var componentBounds = getBounds(component);
  5464. var spectrumBounds = getBounds(spectrum);
  5465. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5466. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5467. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5468. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5469. };
  5470. var getYCenterOffSetOf = function (component, spectrum) {
  5471. var componentBounds = getBounds(component);
  5472. var spectrumBounds = getBounds(spectrum);
  5473. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5474. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5475. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5476. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5477. };
  5478. var fireSliderChange$1 = function (spectrum, value) {
  5479. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5480. };
  5481. var sliderValue = function (x) {
  5482. return { x: x };
  5483. };
  5484. var findValueOfOffset = function (spectrum, detail, left) {
  5485. var args = {
  5486. min: minX(detail),
  5487. max: maxX(detail),
  5488. range: xRange(detail),
  5489. value: left,
  5490. step: step(detail),
  5491. snap: snap(detail),
  5492. snapStart: snapStart(detail),
  5493. rounded: rounded(detail),
  5494. hasMinEdge: hasLEdge(detail),
  5495. hasMaxEdge: hasREdge(detail),
  5496. minBound: getMinXBounds(spectrum),
  5497. maxBound: getMaxXBounds(spectrum),
  5498. screenRange: getXScreenRange(spectrum)
  5499. };
  5500. return findValueOf(args);
  5501. };
  5502. var setValueFrom = function (spectrum, detail, value) {
  5503. var xValue = findValueOfOffset(spectrum, detail, value);
  5504. var sliderVal = sliderValue(xValue);
  5505. fireSliderChange$1(spectrum, sliderVal);
  5506. return xValue;
  5507. };
  5508. var setToMin = function (spectrum, detail) {
  5509. var min = minX(detail);
  5510. fireSliderChange$1(spectrum, sliderValue(min));
  5511. };
  5512. var setToMax = function (spectrum, detail) {
  5513. var max = maxX(detail);
  5514. fireSliderChange$1(spectrum, sliderValue(max));
  5515. };
  5516. var moveBy = function (direction, spectrum, detail) {
  5517. var f = direction > 0 ? increaseBy : reduceBy;
  5518. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5519. fireSliderChange$1(spectrum, sliderValue(xValue));
  5520. return Optional.some(xValue);
  5521. };
  5522. var handleMovement = function (direction) {
  5523. return function (spectrum, detail) {
  5524. return moveBy(direction, spectrum, detail).map(function () {
  5525. return true;
  5526. });
  5527. };
  5528. };
  5529. var getValueFromEvent = function (simulatedEvent) {
  5530. var pos = getEventSource(simulatedEvent);
  5531. return pos.map(function (p) {
  5532. return p.left;
  5533. });
  5534. };
  5535. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5536. var minOffset = 0;
  5537. var maxOffset = getXScreenRange(spectrum);
  5538. var centerMinEdge = minEdge.bind(function (edge) {
  5539. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5540. }).getOr(minOffset);
  5541. var centerMaxEdge = maxEdge.bind(function (edge) {
  5542. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5543. }).getOr(maxOffset);
  5544. var args = {
  5545. min: minX(detail),
  5546. max: maxX(detail),
  5547. range: xRange(detail),
  5548. value: value,
  5549. hasMinEdge: hasLEdge(detail),
  5550. hasMaxEdge: hasREdge(detail),
  5551. minBound: getMinXBounds(spectrum),
  5552. minOffset: minOffset,
  5553. maxBound: getMaxXBounds(spectrum),
  5554. maxOffset: maxOffset,
  5555. centerMinEdge: centerMinEdge,
  5556. centerMaxEdge: centerMaxEdge
  5557. };
  5558. return findOffsetOfValue(args);
  5559. };
  5560. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5561. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5562. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5563. };
  5564. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5565. var value = currentValue(detail);
  5566. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5567. var thumbRadius = get$7(thumb.element) / 2;
  5568. set$3(thumb.element, 'left', pos - thumbRadius + 'px');
  5569. };
  5570. var onLeft = handleMovement(-1);
  5571. var onRight = handleMovement(1);
  5572. var onUp = Optional.none;
  5573. var onDown = Optional.none;
  5574. var edgeActions = {
  5575. 'top-left': Optional.none(),
  5576. 'top': Optional.none(),
  5577. 'top-right': Optional.none(),
  5578. 'right': Optional.some(setToREdge),
  5579. 'bottom-right': Optional.none(),
  5580. 'bottom': Optional.none(),
  5581. 'bottom-left': Optional.none(),
  5582. 'left': Optional.some(setToLEdge)
  5583. };
  5584. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5585. __proto__: null,
  5586. setValueFrom: setValueFrom,
  5587. setToMin: setToMin,
  5588. setToMax: setToMax,
  5589. findValueOfOffset: findValueOfOffset,
  5590. getValueFromEvent: getValueFromEvent,
  5591. findPositionOfValue: findPositionOfValue,
  5592. setPositionFromValue: setPositionFromValue,
  5593. onLeft: onLeft,
  5594. onRight: onRight,
  5595. onUp: onUp,
  5596. onDown: onDown,
  5597. edgeActions: edgeActions
  5598. });
  5599. var fireSliderChange$2 = function (spectrum, value) {
  5600. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5601. };
  5602. var sliderValue$1 = function (y) {
  5603. return { y: y };
  5604. };
  5605. var findValueOfOffset$1 = function (spectrum, detail, top) {
  5606. var args = {
  5607. min: minY(detail),
  5608. max: maxY(detail),
  5609. range: yRange(detail),
  5610. value: top,
  5611. step: step(detail),
  5612. snap: snap(detail),
  5613. snapStart: snapStart(detail),
  5614. rounded: rounded(detail),
  5615. hasMinEdge: hasTEdge(detail),
  5616. hasMaxEdge: hasBEdge(detail),
  5617. minBound: getMinYBounds(spectrum),
  5618. maxBound: getMaxYBounds(spectrum),
  5619. screenRange: getYScreenRange(spectrum)
  5620. };
  5621. return findValueOf(args);
  5622. };
  5623. var setValueFrom$1 = function (spectrum, detail, value) {
  5624. var yValue = findValueOfOffset$1(spectrum, detail, value);
  5625. var sliderVal = sliderValue$1(yValue);
  5626. fireSliderChange$2(spectrum, sliderVal);
  5627. return yValue;
  5628. };
  5629. var setToMin$1 = function (spectrum, detail) {
  5630. var min = minY(detail);
  5631. fireSliderChange$2(spectrum, sliderValue$1(min));
  5632. };
  5633. var setToMax$1 = function (spectrum, detail) {
  5634. var max = maxY(detail);
  5635. fireSliderChange$2(spectrum, sliderValue$1(max));
  5636. };
  5637. var moveBy$1 = function (direction, spectrum, detail) {
  5638. var f = direction > 0 ? increaseBy : reduceBy;
  5639. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5640. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  5641. return Optional.some(yValue);
  5642. };
  5643. var handleMovement$1 = function (direction) {
  5644. return function (spectrum, detail) {
  5645. return moveBy$1(direction, spectrum, detail).map(function () {
  5646. return true;
  5647. });
  5648. };
  5649. };
  5650. var getValueFromEvent$1 = function (simulatedEvent) {
  5651. var pos = getEventSource(simulatedEvent);
  5652. return pos.map(function (p) {
  5653. return p.top;
  5654. });
  5655. };
  5656. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  5657. var minOffset = 0;
  5658. var maxOffset = getYScreenRange(spectrum);
  5659. var centerMinEdge = minEdge.bind(function (edge) {
  5660. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5661. }).getOr(minOffset);
  5662. var centerMaxEdge = maxEdge.bind(function (edge) {
  5663. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5664. }).getOr(maxOffset);
  5665. var args = {
  5666. min: minY(detail),
  5667. max: maxY(detail),
  5668. range: yRange(detail),
  5669. value: value,
  5670. hasMinEdge: hasTEdge(detail),
  5671. hasMaxEdge: hasBEdge(detail),
  5672. minBound: getMinYBounds(spectrum),
  5673. minOffset: minOffset,
  5674. maxBound: getMaxYBounds(spectrum),
  5675. maxOffset: maxOffset,
  5676. centerMinEdge: centerMinEdge,
  5677. centerMaxEdge: centerMaxEdge
  5678. };
  5679. return findOffsetOfValue(args);
  5680. };
  5681. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5682. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  5683. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5684. };
  5685. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5686. var value = currentValue(detail);
  5687. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5688. var thumbRadius = get$5(thumb.element) / 2;
  5689. set$3(thumb.element, 'top', pos - thumbRadius + 'px');
  5690. };
  5691. var onLeft$1 = Optional.none;
  5692. var onRight$1 = Optional.none;
  5693. var onUp$1 = handleMovement$1(-1);
  5694. var onDown$1 = handleMovement$1(1);
  5695. var edgeActions$1 = {
  5696. 'top-left': Optional.none(),
  5697. 'top': Optional.some(setToTEdge),
  5698. 'top-right': Optional.none(),
  5699. 'right': Optional.none(),
  5700. 'bottom-right': Optional.none(),
  5701. 'bottom': Optional.some(setToBEdge),
  5702. 'bottom-left': Optional.none(),
  5703. 'left': Optional.none()
  5704. };
  5705. var VerticalModel = /*#__PURE__*/Object.freeze({
  5706. __proto__: null,
  5707. setValueFrom: setValueFrom$1,
  5708. setToMin: setToMin$1,
  5709. setToMax: setToMax$1,
  5710. findValueOfOffset: findValueOfOffset$1,
  5711. getValueFromEvent: getValueFromEvent$1,
  5712. findPositionOfValue: findPositionOfValue$1,
  5713. setPositionFromValue: setPositionFromValue$1,
  5714. onLeft: onLeft$1,
  5715. onRight: onRight$1,
  5716. onUp: onUp$1,
  5717. onDown: onDown$1,
  5718. edgeActions: edgeActions$1
  5719. });
  5720. var fireSliderChange$3 = function (spectrum, value) {
  5721. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5722. };
  5723. var sliderValue$2 = function (x, y) {
  5724. return {
  5725. x: x,
  5726. y: y
  5727. };
  5728. };
  5729. var setValueFrom$2 = function (spectrum, detail, value) {
  5730. var xValue = findValueOfOffset(spectrum, detail, value.left);
  5731. var yValue = findValueOfOffset$1(spectrum, detail, value.top);
  5732. var val = sliderValue$2(xValue, yValue);
  5733. fireSliderChange$3(spectrum, val);
  5734. return val;
  5735. };
  5736. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  5737. var f = direction > 0 ? increaseBy : reduceBy;
  5738. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5739. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5740. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  5741. return Optional.some(xValue);
  5742. };
  5743. var handleMovement$2 = function (direction, isVerticalMovement) {
  5744. return function (spectrum, detail) {
  5745. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  5746. return true;
  5747. });
  5748. };
  5749. };
  5750. var setToMin$2 = function (spectrum, detail) {
  5751. var mX = minX(detail);
  5752. var mY = minY(detail);
  5753. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5754. };
  5755. var setToMax$2 = function (spectrum, detail) {
  5756. var mX = maxX(detail);
  5757. var mY = maxY(detail);
  5758. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5759. };
  5760. var getValueFromEvent$2 = function (simulatedEvent) {
  5761. return getEventSource(simulatedEvent);
  5762. };
  5763. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5764. var value = currentValue(detail);
  5765. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5766. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5767. var thumbXRadius = get$7(thumb.element) / 2;
  5768. var thumbYRadius = get$5(thumb.element) / 2;
  5769. set$3(thumb.element, 'left', xPos - thumbXRadius + 'px');
  5770. set$3(thumb.element, 'top', yPos - thumbYRadius + 'px');
  5771. };
  5772. var onLeft$2 = handleMovement$2(-1, false);
  5773. var onRight$2 = handleMovement$2(1, false);
  5774. var onUp$2 = handleMovement$2(-1, true);
  5775. var onDown$2 = handleMovement$2(1, true);
  5776. var edgeActions$2 = {
  5777. 'top-left': Optional.some(setToTLEdgeXY),
  5778. 'top': Optional.some(setToTEdgeXY),
  5779. 'top-right': Optional.some(setToTREdgeXY),
  5780. 'right': Optional.some(setToREdgeXY),
  5781. 'bottom-right': Optional.some(setToBREdgeXY),
  5782. 'bottom': Optional.some(setToBEdgeXY),
  5783. 'bottom-left': Optional.some(setToBLEdgeXY),
  5784. 'left': Optional.some(setToLEdgeXY)
  5785. };
  5786. var TwoDModel = /*#__PURE__*/Object.freeze({
  5787. __proto__: null,
  5788. setValueFrom: setValueFrom$2,
  5789. setToMin: setToMin$2,
  5790. setToMax: setToMax$2,
  5791. getValueFromEvent: getValueFromEvent$2,
  5792. setPositionFromValue: setPositionFromValue$2,
  5793. onLeft: onLeft$2,
  5794. onRight: onRight$2,
  5795. onUp: onUp$2,
  5796. onDown: onDown$2,
  5797. edgeActions: edgeActions$2
  5798. });
  5799. var SliderSchema = [
  5800. defaulted$1('stepSize', 1),
  5801. defaulted$1('onChange', noop),
  5802. defaulted$1('onChoose', noop),
  5803. defaulted$1('onInit', noop),
  5804. defaulted$1('onDragStart', noop),
  5805. defaulted$1('onDragEnd', noop),
  5806. defaulted$1('snapToGrid', false),
  5807. defaulted$1('rounded', true),
  5808. option('snapStart'),
  5809. strictOf('model', choose$1('mode', {
  5810. x: [
  5811. defaulted$1('minX', 0),
  5812. defaulted$1('maxX', 100),
  5813. state$1('value', function (spec) {
  5814. return Cell(spec.mode.minX);
  5815. }),
  5816. strict$1('getInitialValue'),
  5817. output('manager', HorizontalModel)
  5818. ],
  5819. y: [
  5820. defaulted$1('minY', 0),
  5821. defaulted$1('maxY', 100),
  5822. state$1('value', function (spec) {
  5823. return Cell(spec.mode.minY);
  5824. }),
  5825. strict$1('getInitialValue'),
  5826. output('manager', VerticalModel)
  5827. ],
  5828. xy: [
  5829. defaulted$1('minX', 0),
  5830. defaulted$1('maxX', 100),
  5831. defaulted$1('minY', 0),
  5832. defaulted$1('maxY', 100),
  5833. state$1('value', function (spec) {
  5834. return Cell({
  5835. x: spec.mode.minX,
  5836. y: spec.mode.minY
  5837. });
  5838. }),
  5839. strict$1('getInitialValue'),
  5840. output('manager', TwoDModel)
  5841. ]
  5842. })),
  5843. field$1('sliderBehaviours', [
  5844. Keying,
  5845. Representing
  5846. ]),
  5847. state$1('mouseIsDown', function () {
  5848. return Cell(false);
  5849. })
  5850. ];
  5851. var mouseReleased = constant('mouse.released');
  5852. var sketch = function (detail, components, _spec, _externals) {
  5853. var _a;
  5854. var getThumb = function (component) {
  5855. return getPartOrDie(component, detail, 'thumb');
  5856. };
  5857. var getSpectrum = function (component) {
  5858. return getPartOrDie(component, detail, 'spectrum');
  5859. };
  5860. var getLeftEdge = function (component) {
  5861. return getPart(component, detail, 'left-edge');
  5862. };
  5863. var getRightEdge = function (component) {
  5864. return getPart(component, detail, 'right-edge');
  5865. };
  5866. var getTopEdge = function (component) {
  5867. return getPart(component, detail, 'top-edge');
  5868. };
  5869. var getBottomEdge = function (component) {
  5870. return getPart(component, detail, 'bottom-edge');
  5871. };
  5872. var modelDetail = detail.model;
  5873. var model = modelDetail.manager;
  5874. var refresh = function (slider, thumb) {
  5875. model.setPositionFromValue(slider, thumb, detail, {
  5876. getLeftEdge: getLeftEdge,
  5877. getRightEdge: getRightEdge,
  5878. getTopEdge: getTopEdge,
  5879. getBottomEdge: getBottomEdge,
  5880. getSpectrum: getSpectrum
  5881. });
  5882. };
  5883. var changeValue = function (slider, newValue) {
  5884. modelDetail.value.set(newValue);
  5885. var thumb = getThumb(slider);
  5886. refresh(slider, thumb);
  5887. detail.onChange(slider, thumb, newValue);
  5888. return Optional.some(true);
  5889. };
  5890. var resetToMin = function (slider) {
  5891. model.setToMin(slider, detail);
  5892. };
  5893. var resetToMax = function (slider) {
  5894. model.setToMax(slider, detail);
  5895. };
  5896. var choose = function (slider) {
  5897. var fireOnChoose = function () {
  5898. getPart(slider, detail, 'thumb').each(function (thumb) {
  5899. var value = modelDetail.value.get();
  5900. detail.onChoose(slider, thumb, value);
  5901. });
  5902. };
  5903. var wasDown = detail.mouseIsDown.get();
  5904. detail.mouseIsDown.set(false);
  5905. if (wasDown) {
  5906. fireOnChoose();
  5907. }
  5908. };
  5909. var onDragStart = function (slider, simulatedEvent) {
  5910. simulatedEvent.stop();
  5911. detail.mouseIsDown.set(true);
  5912. detail.onDragStart(slider, getThumb(slider));
  5913. };
  5914. var onDragEnd = function (slider, simulatedEvent) {
  5915. simulatedEvent.stop();
  5916. detail.onDragEnd(slider, getThumb(slider));
  5917. choose(slider);
  5918. };
  5919. return {
  5920. uid: detail.uid,
  5921. dom: detail.dom,
  5922. components: components,
  5923. behaviours: augment(detail.sliderBehaviours, [
  5924. Keying.config({
  5925. mode: 'special',
  5926. focusIn: function (slider) {
  5927. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  5928. }
  5929. }),
  5930. Representing.config({
  5931. store: {
  5932. mode: 'manual',
  5933. getValue: function (_) {
  5934. return modelDetail.value.get();
  5935. }
  5936. }
  5937. }),
  5938. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  5939. ]),
  5940. events: derive([
  5941. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  5942. changeValue(slider, simulatedEvent.event.value);
  5943. }),
  5944. runOnAttached(function (slider, _simulatedEvent) {
  5945. var getInitial = modelDetail.getInitialValue();
  5946. modelDetail.value.set(getInitial);
  5947. var thumb = getThumb(slider);
  5948. refresh(slider, thumb);
  5949. var spectrum = getSpectrum(slider);
  5950. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  5951. }),
  5952. run(touchstart(), onDragStart),
  5953. run(touchend(), onDragEnd),
  5954. run(mousedown(), onDragStart),
  5955. run(mouseup(), onDragEnd)
  5956. ]),
  5957. apis: {
  5958. resetToMin: resetToMin,
  5959. resetToMax: resetToMax,
  5960. changeValue: changeValue,
  5961. refresh: refresh
  5962. },
  5963. domModification: { styles: { position: 'relative' } }
  5964. };
  5965. };
  5966. var Slider = composite$1({
  5967. name: 'Slider',
  5968. configFields: SliderSchema,
  5969. partFields: SliderParts,
  5970. factory: sketch,
  5971. apis: {
  5972. resetToMin: function (apis, slider) {
  5973. apis.resetToMin(slider);
  5974. },
  5975. resetToMax: function (apis, slider) {
  5976. apis.resetToMax(slider);
  5977. },
  5978. refresh: function (apis, slider) {
  5979. apis.refresh(slider);
  5980. }
  5981. }
  5982. });
  5983. var button = function (realm, clazz, makeItems, editor) {
  5984. return forToolbar(clazz, function () {
  5985. var items = makeItems();
  5986. realm.setContextToolbar([{
  5987. label: clazz + ' group',
  5988. items: items
  5989. }]);
  5990. }, {}, editor);
  5991. };
  5992. var BLACK = -1;
  5993. var makeSlider = function (spec$1) {
  5994. var getColor = function (hue) {
  5995. if (hue < 0) {
  5996. return 'black';
  5997. } else if (hue > 360) {
  5998. return 'white';
  5999. } else {
  6000. return 'hsl(' + hue + ', 100%, 50%)';
  6001. }
  6002. };
  6003. var onInit = function (slider, thumb, spectrum, value) {
  6004. var color = getColor(value.x());
  6005. set$3(thumb.element, 'background-color', color);
  6006. };
  6007. var onChange = function (slider, thumb, value) {
  6008. var color = getColor(value.x());
  6009. set$3(thumb.element, 'background-color', color);
  6010. spec$1.onChange(slider, thumb, color);
  6011. };
  6012. return Slider.sketch({
  6013. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  6014. components: [
  6015. Slider.parts['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  6016. Slider.parts.spectrum({
  6017. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  6018. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  6019. behaviours: derive$1([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6020. }),
  6021. Slider.parts['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  6022. Slider.parts.thumb({
  6023. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6024. behaviours: derive$1([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6025. })
  6026. ],
  6027. onChange: onChange,
  6028. onDragStart: function (slider, thumb) {
  6029. Toggling.on(thumb);
  6030. },
  6031. onDragEnd: function (slider, thumb) {
  6032. Toggling.off(thumb);
  6033. },
  6034. onInit: onInit,
  6035. stepSize: 10,
  6036. model: {
  6037. mode: 'x',
  6038. minX: 0,
  6039. maxX: 360,
  6040. getInitialValue: function () {
  6041. return { x: spec$1.getInitialValue() };
  6042. }
  6043. },
  6044. sliderBehaviours: derive$1([orientation(Slider.refresh)])
  6045. });
  6046. };
  6047. var makeItems = function (spec) {
  6048. return [makeSlider(spec)];
  6049. };
  6050. var sketch$1 = function (realm, editor) {
  6051. var spec = {
  6052. onChange: function (slider, thumb, color) {
  6053. editor.undoManager.transact(function () {
  6054. editor.formatter.apply('forecolor', { value: color });
  6055. editor.nodeChanged();
  6056. });
  6057. },
  6058. getInitialValue: function () {
  6059. return BLACK;
  6060. }
  6061. };
  6062. return button(realm, 'color-levels', function () {
  6063. return makeItems(spec);
  6064. }, editor);
  6065. };
  6066. var candidatesArray = [
  6067. '9px',
  6068. '10px',
  6069. '11px',
  6070. '12px',
  6071. '14px',
  6072. '16px',
  6073. '18px',
  6074. '20px',
  6075. '24px',
  6076. '32px',
  6077. '36px'
  6078. ];
  6079. var defaultSize = 'medium';
  6080. var defaultIndex = 2;
  6081. var indexToSize = function (index) {
  6082. return Optional.from(candidatesArray[index]);
  6083. };
  6084. var sizeToIndex = function (size) {
  6085. return findIndex(candidatesArray, function (v) {
  6086. return v === size;
  6087. });
  6088. };
  6089. var getRawOrComputed = function (isRoot, rawStart) {
  6090. var optStart = isElement(rawStart) ? Optional.some(rawStart) : parent(rawStart).filter(isElement);
  6091. return optStart.map(function (start) {
  6092. var inline = closest$1(start, function (elem) {
  6093. return getRaw(elem, 'font-size').isSome();
  6094. }, isRoot).bind(function (elem) {
  6095. return getRaw(elem, 'font-size');
  6096. });
  6097. return inline.getOrThunk(function () {
  6098. return get$4(start, 'font-size');
  6099. });
  6100. }).getOr('');
  6101. };
  6102. var getSize = function (editor) {
  6103. var node = editor.selection.getStart();
  6104. var elem = SugarElement.fromDom(node);
  6105. var root = SugarElement.fromDom(editor.getBody());
  6106. var isRoot = function (e) {
  6107. return eq(root, e);
  6108. };
  6109. var elemSize = getRawOrComputed(isRoot, elem);
  6110. return find(candidatesArray, function (size) {
  6111. return elemSize === size;
  6112. }).getOr(defaultSize);
  6113. };
  6114. var applySize = function (editor, value) {
  6115. var currentValue = getSize(editor);
  6116. if (currentValue !== value) {
  6117. editor.execCommand('fontSize', false, value);
  6118. }
  6119. };
  6120. var get$8 = function (editor) {
  6121. var size = getSize(editor);
  6122. return sizeToIndex(size).getOr(defaultIndex);
  6123. };
  6124. var apply$1 = function (editor, index) {
  6125. indexToSize(index).each(function (size) {
  6126. applySize(editor, size);
  6127. });
  6128. };
  6129. var candidates = constant(candidatesArray);
  6130. var schema$7 = objOfOnly([
  6131. strict$1('getInitialValue'),
  6132. strict$1('onChange'),
  6133. strict$1('category'),
  6134. strict$1('sizes')
  6135. ]);
  6136. var sketch$2 = function (rawSpec) {
  6137. var spec$1 = asRawOrDie('SizeSlider', schema$7, rawSpec);
  6138. var isValidValue = function (valueIndex) {
  6139. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6140. };
  6141. var onChange = function (slider, thumb, valueIndex) {
  6142. var index = valueIndex.x();
  6143. if (isValidValue(index)) {
  6144. spec$1.onChange(index);
  6145. }
  6146. };
  6147. return Slider.sketch({
  6148. dom: {
  6149. tag: 'div',
  6150. classes: [
  6151. resolve('slider-' + spec$1.category + '-size-container'),
  6152. resolve('slider'),
  6153. resolve('slider-size-container')
  6154. ]
  6155. },
  6156. onChange: onChange,
  6157. onDragStart: function (slider, thumb) {
  6158. Toggling.on(thumb);
  6159. },
  6160. onDragEnd: function (slider, thumb) {
  6161. Toggling.off(thumb);
  6162. },
  6163. model: {
  6164. mode: 'x',
  6165. minX: 0,
  6166. maxX: spec$1.sizes.length - 1,
  6167. getInitialValue: function () {
  6168. return { x: spec$1.getInitialValue() };
  6169. }
  6170. },
  6171. stepSize: 1,
  6172. snapToGrid: true,
  6173. sliderBehaviours: derive$1([orientation(Slider.refresh)]),
  6174. components: [
  6175. Slider.parts.spectrum({
  6176. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6177. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  6178. }),
  6179. Slider.parts.thumb({
  6180. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6181. behaviours: derive$1([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6182. })
  6183. ]
  6184. });
  6185. };
  6186. var sizes = candidates();
  6187. var makeSlider$1 = function (spec) {
  6188. return sketch$2({
  6189. onChange: spec.onChange,
  6190. sizes: sizes,
  6191. category: 'font',
  6192. getInitialValue: spec.getInitialValue
  6193. });
  6194. };
  6195. var makeItems$1 = function (spec$1) {
  6196. return [
  6197. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6198. makeSlider$1(spec$1),
  6199. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6200. ];
  6201. };
  6202. var sketch$3 = function (realm, editor) {
  6203. var spec = {
  6204. onChange: function (value) {
  6205. apply$1(editor, value);
  6206. },
  6207. getInitialValue: function () {
  6208. return get$8(editor);
  6209. }
  6210. };
  6211. return button(realm, 'font-size', function () {
  6212. return makeItems$1(spec);
  6213. }, editor);
  6214. };
  6215. var record = function (spec) {
  6216. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$3('memento');
  6217. var get = function (anyInSystem) {
  6218. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6219. };
  6220. var getOpt = function (anyInSystem) {
  6221. return anyInSystem.getSystem().getByUid(uid).toOptional();
  6222. };
  6223. var asSpec = function () {
  6224. return __assign(__assign({}, spec), { uid: uid });
  6225. };
  6226. return {
  6227. get: get,
  6228. getOpt: getOpt,
  6229. asSpec: asSpec
  6230. };
  6231. };
  6232. var promise = function () {
  6233. var Promise = function (fn) {
  6234. if (typeof this !== 'object') {
  6235. throw new TypeError('Promises must be constructed via new');
  6236. }
  6237. if (typeof fn !== 'function') {
  6238. throw new TypeError('not a function');
  6239. }
  6240. this._state = null;
  6241. this._value = null;
  6242. this._deferreds = [];
  6243. doResolve(fn, bind(resolve, this), bind(reject, this));
  6244. };
  6245. var anyWindow = window;
  6246. var asap = Promise.immediateFn || typeof anyWindow.setImmediate === 'function' && anyWindow.setImmediate || function (fn) {
  6247. setTimeout(fn, 1);
  6248. };
  6249. function bind(fn, thisArg) {
  6250. return function () {
  6251. return fn.apply(thisArg, arguments);
  6252. };
  6253. }
  6254. var isArray = Array.isArray || function (value) {
  6255. return Object.prototype.toString.call(value) === '[object Array]';
  6256. };
  6257. function handle(deferred) {
  6258. var me = this;
  6259. if (this._state === null) {
  6260. this._deferreds.push(deferred);
  6261. return;
  6262. }
  6263. asap(function () {
  6264. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  6265. if (cb === null) {
  6266. (me._state ? deferred.resolve : deferred.reject)(me._value);
  6267. return;
  6268. }
  6269. var ret;
  6270. try {
  6271. ret = cb(me._value);
  6272. } catch (e) {
  6273. deferred.reject(e);
  6274. return;
  6275. }
  6276. deferred.resolve(ret);
  6277. });
  6278. }
  6279. function resolve(newValue) {
  6280. try {
  6281. if (newValue === this) {
  6282. throw new TypeError('A promise cannot be resolved with itself.');
  6283. }
  6284. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6285. var then = newValue.then;
  6286. if (typeof then === 'function') {
  6287. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  6288. return;
  6289. }
  6290. }
  6291. this._state = true;
  6292. this._value = newValue;
  6293. finale.call(this);
  6294. } catch (e) {
  6295. reject.call(this, e);
  6296. }
  6297. }
  6298. function reject(newValue) {
  6299. this._state = false;
  6300. this._value = newValue;
  6301. finale.call(this);
  6302. }
  6303. function finale() {
  6304. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  6305. var deferred = _a[_i];
  6306. handle.call(this, deferred);
  6307. }
  6308. this._deferreds = [];
  6309. }
  6310. function Handler(onFulfilled, onRejected, resolve, reject) {
  6311. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6312. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6313. this.resolve = resolve;
  6314. this.reject = reject;
  6315. }
  6316. function doResolve(fn, onFulfilled, onRejected) {
  6317. var done = false;
  6318. try {
  6319. fn(function (value) {
  6320. if (done) {
  6321. return;
  6322. }
  6323. done = true;
  6324. onFulfilled(value);
  6325. }, function (reason) {
  6326. if (done) {
  6327. return;
  6328. }
  6329. done = true;
  6330. onRejected(reason);
  6331. });
  6332. } catch (ex) {
  6333. if (done) {
  6334. return;
  6335. }
  6336. done = true;
  6337. onRejected(ex);
  6338. }
  6339. }
  6340. Promise.prototype.catch = function (onRejected) {
  6341. return this.then(null, onRejected);
  6342. };
  6343. Promise.prototype.then = function (onFulfilled, onRejected) {
  6344. var me = this;
  6345. return new Promise(function (resolve, reject) {
  6346. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  6347. });
  6348. };
  6349. Promise.all = function () {
  6350. var values = [];
  6351. for (var _i = 0; _i < arguments.length; _i++) {
  6352. values[_i] = arguments[_i];
  6353. }
  6354. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  6355. return new Promise(function (resolve, reject) {
  6356. if (args.length === 0) {
  6357. return resolve([]);
  6358. }
  6359. var remaining = args.length;
  6360. function res(i, val) {
  6361. try {
  6362. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6363. var then = val.then;
  6364. if (typeof then === 'function') {
  6365. then.call(val, function (val) {
  6366. res(i, val);
  6367. }, reject);
  6368. return;
  6369. }
  6370. }
  6371. args[i] = val;
  6372. if (--remaining === 0) {
  6373. resolve(args);
  6374. }
  6375. } catch (ex) {
  6376. reject(ex);
  6377. }
  6378. }
  6379. for (var i = 0; i < args.length; i++) {
  6380. res(i, args[i]);
  6381. }
  6382. });
  6383. };
  6384. Promise.resolve = function (value) {
  6385. if (value && typeof value === 'object' && value.constructor === Promise) {
  6386. return value;
  6387. }
  6388. return new Promise(function (resolve) {
  6389. resolve(value);
  6390. });
  6391. };
  6392. Promise.reject = function (reason) {
  6393. return new Promise(function (resolve, reject) {
  6394. reject(reason);
  6395. });
  6396. };
  6397. Promise.race = function (values) {
  6398. return new Promise(function (resolve, reject) {
  6399. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  6400. var value = values_1[_i];
  6401. value.then(resolve, reject);
  6402. }
  6403. });
  6404. };
  6405. return Promise;
  6406. };
  6407. var Promise = window.Promise ? window.Promise : promise();
  6408. function blobToDataUri(blob) {
  6409. return new Promise(function (resolve) {
  6410. var reader = new FileReader();
  6411. reader.onloadend = function () {
  6412. resolve(reader.result);
  6413. };
  6414. reader.readAsDataURL(blob);
  6415. });
  6416. }
  6417. function blobToBase64(blob) {
  6418. return blobToDataUri(blob).then(function (dataUri) {
  6419. return dataUri.split(',')[1];
  6420. });
  6421. }
  6422. var blobToBase64$1 = function (blob) {
  6423. return blobToBase64(blob);
  6424. };
  6425. var addImage = function (editor, blob) {
  6426. blobToBase64$1(blob).then(function (base64) {
  6427. editor.undoManager.transact(function () {
  6428. var cache = editor.editorUpload.blobCache;
  6429. var info = cache.create(generate$1('mceu'), blob, base64);
  6430. cache.add(info);
  6431. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6432. editor.insertContent(img);
  6433. });
  6434. });
  6435. };
  6436. var extractBlob = function (simulatedEvent) {
  6437. var event = simulatedEvent.event.raw;
  6438. var files = event.target.files || event.dataTransfer.files;
  6439. return Optional.from(files[0]);
  6440. };
  6441. var sketch$4 = function (editor) {
  6442. var pickerDom = {
  6443. tag: 'input',
  6444. attributes: {
  6445. accept: 'image/*',
  6446. type: 'file',
  6447. title: ''
  6448. },
  6449. styles: {
  6450. visibility: 'hidden',
  6451. position: 'absolute'
  6452. }
  6453. };
  6454. var memPicker = record({
  6455. dom: pickerDom,
  6456. events: derive([
  6457. cutter(click()),
  6458. run(change(), function (picker, simulatedEvent) {
  6459. extractBlob(simulatedEvent).each(function (blob) {
  6460. addImage(editor, blob);
  6461. });
  6462. })
  6463. ])
  6464. });
  6465. return Button.sketch({
  6466. dom: getToolbarIconButton('image', editor),
  6467. components: [memPicker.asSpec()],
  6468. action: function (button) {
  6469. var picker = memPicker.get(button);
  6470. picker.element.dom.click();
  6471. }
  6472. });
  6473. };
  6474. var get$9 = function (element) {
  6475. return element.dom.textContent;
  6476. };
  6477. var set$5 = function (element, value) {
  6478. element.dom.textContent = value;
  6479. };
  6480. var isNotEmpty = function (val) {
  6481. return val.length > 0;
  6482. };
  6483. var defaultToEmpty = function (str) {
  6484. return str === undefined || str === null ? '' : str;
  6485. };
  6486. var noLink = function (editor) {
  6487. var text = editor.selection.getContent({ format: 'text' });
  6488. return {
  6489. url: '',
  6490. text: text,
  6491. title: '',
  6492. target: '',
  6493. link: Optional.none()
  6494. };
  6495. };
  6496. var fromLink = function (link) {
  6497. var text = get$9(link);
  6498. var url = get$1(link, 'href');
  6499. var title = get$1(link, 'title');
  6500. var target = get$1(link, 'target');
  6501. return {
  6502. url: defaultToEmpty(url),
  6503. text: text !== url ? defaultToEmpty(text) : '',
  6504. title: defaultToEmpty(title),
  6505. target: defaultToEmpty(target),
  6506. link: Optional.some(link)
  6507. };
  6508. };
  6509. var getInfo = function (editor) {
  6510. return query(editor).fold(function () {
  6511. return noLink(editor);
  6512. }, function (link) {
  6513. return fromLink(link);
  6514. });
  6515. };
  6516. var wasSimple = function (link) {
  6517. var prevHref = get$1(link, 'href');
  6518. var prevText = get$9(link);
  6519. return prevHref === prevText;
  6520. };
  6521. var getTextToApply = function (link, url, info) {
  6522. return info.text.toOptional().filter(isNotEmpty).fold(function () {
  6523. return wasSimple(link) ? Optional.some(url) : Optional.none();
  6524. }, Optional.some);
  6525. };
  6526. var unlinkIfRequired = function (editor, info) {
  6527. var activeLink = info.link.bind(identity);
  6528. activeLink.each(function (_link) {
  6529. editor.execCommand('unlink');
  6530. });
  6531. };
  6532. var getAttrs$1 = function (url, info) {
  6533. var attrs = {};
  6534. attrs.href = url;
  6535. info.title.toOptional().filter(isNotEmpty).each(function (title) {
  6536. attrs.title = title;
  6537. });
  6538. info.target.toOptional().filter(isNotEmpty).each(function (target) {
  6539. attrs.target = target;
  6540. });
  6541. return attrs;
  6542. };
  6543. var applyInfo = function (editor, info) {
  6544. info.url.toOptional().filter(isNotEmpty).fold(function () {
  6545. unlinkIfRequired(editor, info);
  6546. }, function (url) {
  6547. var attrs = getAttrs$1(url, info);
  6548. var activeLink = info.link.bind(identity);
  6549. activeLink.fold(function () {
  6550. var text = info.text.toOptional().filter(isNotEmpty).getOr(url);
  6551. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6552. }, function (link) {
  6553. var text = getTextToApply(link, url, info);
  6554. setAll(link, attrs);
  6555. text.each(function (newText) {
  6556. set$5(link, newText);
  6557. });
  6558. });
  6559. });
  6560. };
  6561. var query = function (editor) {
  6562. var start = SugarElement.fromDom(editor.selection.getStart());
  6563. return closest$2(start, 'a');
  6564. };
  6565. var platform$1 = detect$3();
  6566. var preserve = function (f, editor) {
  6567. var rng = editor.selection.getRng();
  6568. f();
  6569. editor.selection.setRng(rng);
  6570. };
  6571. var forAndroid = function (editor, f) {
  6572. var wrapper = platform$1.os.isAndroid() ? preserve : apply;
  6573. wrapper(f, editor);
  6574. };
  6575. var events$6 = function (name, eventHandlers) {
  6576. var events = derive(eventHandlers);
  6577. return create$1({
  6578. fields: [strict$1('enabled')],
  6579. name: name,
  6580. active: { events: constant(events) }
  6581. });
  6582. };
  6583. var config = function (name, eventHandlers) {
  6584. var me = events$6(name, eventHandlers);
  6585. return {
  6586. key: name,
  6587. value: {
  6588. config: {},
  6589. me: me,
  6590. configAsRaw: constant({}),
  6591. initialConfig: {},
  6592. state: NoState
  6593. }
  6594. };
  6595. };
  6596. var getCurrent = function (component, composeConfig, _composeState) {
  6597. return composeConfig.find(component);
  6598. };
  6599. var ComposeApis = /*#__PURE__*/Object.freeze({
  6600. __proto__: null,
  6601. getCurrent: getCurrent
  6602. });
  6603. var ComposeSchema = [strict$1('find')];
  6604. var Composing = create$1({
  6605. fields: ComposeSchema,
  6606. name: 'composing',
  6607. apis: ComposeApis
  6608. });
  6609. var factory$1 = function (detail) {
  6610. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6611. return {
  6612. uid: detail.uid,
  6613. dom: __assign({
  6614. tag: 'div',
  6615. attributes: __assign({ role: 'presentation' }, attributes)
  6616. }, domWithoutAttributes),
  6617. components: detail.components,
  6618. behaviours: get$6(detail.containerBehaviours),
  6619. events: detail.events,
  6620. domModification: detail.domModification,
  6621. eventOrder: detail.eventOrder
  6622. };
  6623. };
  6624. var Container = single$2({
  6625. name: 'Container',
  6626. factory: factory$1,
  6627. configFields: [
  6628. defaulted$1('components', []),
  6629. field$1('containerBehaviours', []),
  6630. defaulted$1('events', {}),
  6631. defaulted$1('domModification', {}),
  6632. defaulted$1('eventOrder', {})
  6633. ]
  6634. });
  6635. var factory$2 = function (detail) {
  6636. return {
  6637. uid: detail.uid,
  6638. dom: detail.dom,
  6639. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6640. Representing.config({
  6641. store: {
  6642. mode: 'memory',
  6643. initialValue: detail.getInitialValue()
  6644. }
  6645. }),
  6646. Composing.config({ find: Optional.some })
  6647. ]),
  6648. events: derive([runOnAttached(function (component, _simulatedEvent) {
  6649. Representing.setValue(component, detail.getInitialValue());
  6650. })])
  6651. };
  6652. };
  6653. var DataField = single$2({
  6654. name: 'DataField',
  6655. factory: factory$2,
  6656. configFields: [
  6657. strict$1('uid'),
  6658. strict$1('dom'),
  6659. strict$1('getInitialValue'),
  6660. SketchBehaviours.field('dataBehaviours', [
  6661. Representing,
  6662. Composing
  6663. ])
  6664. ]
  6665. });
  6666. var get$a = function (element) {
  6667. return element.dom.value;
  6668. };
  6669. var set$6 = function (element, value) {
  6670. if (value === undefined) {
  6671. throw new Error('Value.set was undefined');
  6672. }
  6673. element.dom.value = value;
  6674. };
  6675. var schema$8 = constant([
  6676. option('data'),
  6677. defaulted$1('inputAttributes', {}),
  6678. defaulted$1('inputStyles', {}),
  6679. defaulted$1('tag', 'input'),
  6680. defaulted$1('inputClasses', []),
  6681. onHandler('onSetValue'),
  6682. defaulted$1('styles', {}),
  6683. defaulted$1('eventOrder', {}),
  6684. field$1('inputBehaviours', [
  6685. Representing,
  6686. Focusing
  6687. ]),
  6688. defaulted$1('selectOnFocus', true)
  6689. ]);
  6690. var focusBehaviours = function (detail) {
  6691. return derive$1([Focusing.config({
  6692. onFocus: !detail.selectOnFocus ? noop : function (component) {
  6693. var input = component.element;
  6694. var value = get$a(input);
  6695. input.dom.setSelectionRange(0, value.length);
  6696. }
  6697. })]);
  6698. };
  6699. var behaviours = function (detail) {
  6700. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6701. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  6702. return { initialValue: data };
  6703. }).getOr({})), {
  6704. getValue: function (input) {
  6705. return get$a(input.element);
  6706. },
  6707. setValue: function (input, data) {
  6708. var current = get$a(input.element);
  6709. if (current !== data) {
  6710. set$6(input.element, data);
  6711. }
  6712. }
  6713. }),
  6714. onSetValue: detail.onSetValue
  6715. })]));
  6716. };
  6717. var dom$2 = function (detail) {
  6718. return {
  6719. tag: detail.tag,
  6720. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6721. styles: detail.inputStyles,
  6722. classes: detail.inputClasses
  6723. };
  6724. };
  6725. var factory$3 = function (detail, _spec) {
  6726. return {
  6727. uid: detail.uid,
  6728. dom: dom$2(detail),
  6729. components: [],
  6730. behaviours: behaviours(detail),
  6731. eventOrder: detail.eventOrder
  6732. };
  6733. };
  6734. var Input = single$2({
  6735. name: 'Input',
  6736. configFields: schema$8(),
  6737. factory: factory$3
  6738. });
  6739. var exhibit$3 = function (base, tabConfig) {
  6740. return nu$5({
  6741. attributes: wrapAll$1([{
  6742. key: tabConfig.tabAttr,
  6743. value: 'true'
  6744. }])
  6745. });
  6746. };
  6747. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6748. __proto__: null,
  6749. exhibit: exhibit$3
  6750. });
  6751. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  6752. var Tabstopping = create$1({
  6753. fields: TabstopSchema,
  6754. name: 'tabstopping',
  6755. active: ActiveTabstopping
  6756. });
  6757. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6758. var clearInputBehaviour = 'input-clearing';
  6759. var field$2 = function (name, placeholder) {
  6760. var inputSpec = record(Input.sketch({
  6761. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6762. onSetValue: function (input$1, _data) {
  6763. emit(input$1, input());
  6764. },
  6765. inputBehaviours: derive$1([
  6766. Composing.config({ find: Optional.some }),
  6767. Tabstopping.config({}),
  6768. Keying.config({ mode: 'execution' })
  6769. ]),
  6770. selectOnFocus: false
  6771. }));
  6772. var buttonSpec = record(Button.sketch({
  6773. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6774. action: function (button) {
  6775. var input = inputSpec.get(button);
  6776. Representing.setValue(input, '');
  6777. }
  6778. }));
  6779. return {
  6780. name: name,
  6781. spec: Container.sketch({
  6782. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6783. components: [
  6784. inputSpec.asSpec(),
  6785. buttonSpec.asSpec()
  6786. ],
  6787. containerBehaviours: derive$1([
  6788. Toggling.config({ toggleClass: resolve('input-container-empty') }),
  6789. Composing.config({
  6790. find: function (comp) {
  6791. return Optional.some(inputSpec.get(comp));
  6792. }
  6793. }),
  6794. config(clearInputBehaviour, [run(input(), function (iContainer) {
  6795. var input = inputSpec.get(iContainer);
  6796. var val = Representing.getValue(input);
  6797. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6798. f(iContainer);
  6799. })])
  6800. ])
  6801. })
  6802. };
  6803. };
  6804. var hidden = function (name) {
  6805. return {
  6806. name: name,
  6807. spec: DataField.sketch({
  6808. dom: {
  6809. tag: 'span',
  6810. styles: { display: 'none' }
  6811. },
  6812. getInitialValue: function () {
  6813. return Optional.none();
  6814. }
  6815. })
  6816. };
  6817. };
  6818. var nativeDisabled = [
  6819. 'input',
  6820. 'button',
  6821. 'textarea',
  6822. 'select'
  6823. ];
  6824. var onLoad$5 = function (component, disableConfig, disableState) {
  6825. var f = disableConfig.disabled() ? disable : enable;
  6826. f(component, disableConfig);
  6827. };
  6828. var hasNative = function (component, config) {
  6829. return config.useNative === true && contains(nativeDisabled, name(component.element));
  6830. };
  6831. var nativeIsDisabled = function (component) {
  6832. return has$1(component.element, 'disabled');
  6833. };
  6834. var nativeDisable = function (component) {
  6835. set(component.element, 'disabled', 'disabled');
  6836. };
  6837. var nativeEnable = function (component) {
  6838. remove$1(component.element, 'disabled');
  6839. };
  6840. var ariaIsDisabled = function (component) {
  6841. return get$1(component.element, 'aria-disabled') === 'true';
  6842. };
  6843. var ariaDisable = function (component) {
  6844. set(component.element, 'aria-disabled', 'true');
  6845. };
  6846. var ariaEnable = function (component) {
  6847. set(component.element, 'aria-disabled', 'false');
  6848. };
  6849. var disable = function (component, disableConfig, _disableState) {
  6850. disableConfig.disableClass.each(function (disableClass) {
  6851. add$2(component.element, disableClass);
  6852. });
  6853. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6854. f(component);
  6855. disableConfig.onDisabled(component);
  6856. };
  6857. var enable = function (component, disableConfig, _disableState) {
  6858. disableConfig.disableClass.each(function (disableClass) {
  6859. remove$4(component.element, disableClass);
  6860. });
  6861. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6862. f(component);
  6863. disableConfig.onEnabled(component);
  6864. };
  6865. var isDisabled = function (component, disableConfig) {
  6866. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6867. };
  6868. var set$7 = function (component, disableConfig, disableState, disabled) {
  6869. var f = disabled ? disable : enable;
  6870. f(component, disableConfig);
  6871. };
  6872. var DisableApis = /*#__PURE__*/Object.freeze({
  6873. __proto__: null,
  6874. enable: enable,
  6875. disable: disable,
  6876. isDisabled: isDisabled,
  6877. onLoad: onLoad$5,
  6878. set: set$7
  6879. });
  6880. var exhibit$4 = function (base, disableConfig) {
  6881. return nu$5({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6882. };
  6883. var events$7 = function (disableConfig, disableState) {
  6884. return derive([
  6885. abort(execute(), function (component, _simulatedEvent) {
  6886. return isDisabled(component, disableConfig);
  6887. }),
  6888. loadEvent(disableConfig, disableState, onLoad$5)
  6889. ]);
  6890. };
  6891. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6892. __proto__: null,
  6893. exhibit: exhibit$4,
  6894. events: events$7
  6895. });
  6896. var DisableSchema = [
  6897. defaultedFunction('disabled', never),
  6898. defaulted$1('useNative', true),
  6899. option('disableClass'),
  6900. onHandler('onDisabled'),
  6901. onHandler('onEnabled')
  6902. ];
  6903. var Disabling = create$1({
  6904. fields: DisableSchema,
  6905. name: 'disabling',
  6906. active: ActiveDisable,
  6907. apis: DisableApis
  6908. });
  6909. var owner$1 = 'form';
  6910. var schema$9 = [field$1('formBehaviours', [Representing])];
  6911. var getPartName = function (name) {
  6912. return '<alloy.field.' + name + '>';
  6913. };
  6914. var sketch$5 = function (fSpec) {
  6915. var parts = function () {
  6916. var record = [];
  6917. var field = function (name, config) {
  6918. record.push(name);
  6919. return generateOne(owner$1, getPartName(name), config);
  6920. };
  6921. return {
  6922. field: field,
  6923. record: function () {
  6924. return record;
  6925. }
  6926. };
  6927. }();
  6928. var spec = fSpec(parts);
  6929. var partNames = parts.record();
  6930. var fieldParts = map(partNames, function (n) {
  6931. return required({
  6932. name: n,
  6933. pname: getPartName(n)
  6934. });
  6935. });
  6936. return composite(owner$1, schema$9, fieldParts, make, spec);
  6937. };
  6938. var toResult$1 = function (o, e) {
  6939. return o.fold(function () {
  6940. return Result.error(e);
  6941. }, Result.value);
  6942. };
  6943. var make = function (detail, components) {
  6944. return {
  6945. uid: detail.uid,
  6946. dom: detail.dom,
  6947. components: components,
  6948. behaviours: augment(detail.formBehaviours, [Representing.config({
  6949. store: {
  6950. mode: 'manual',
  6951. getValue: function (form) {
  6952. var resPs = getAllParts(form, detail);
  6953. return map$1(resPs, function (resPThunk, pName) {
  6954. return resPThunk().bind(function (v) {
  6955. var opt = Composing.getCurrent(v);
  6956. return toResult$1(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  6957. }).map(Representing.getValue);
  6958. });
  6959. },
  6960. setValue: function (form, values) {
  6961. each$1(values, function (newValue, key) {
  6962. getPart(form, detail, key).each(function (wrapper) {
  6963. Composing.getCurrent(wrapper).each(function (field) {
  6964. Representing.setValue(field, newValue);
  6965. });
  6966. });
  6967. });
  6968. }
  6969. }
  6970. })]),
  6971. apis: {
  6972. getField: function (form, key) {
  6973. return getPart(form, detail, key).bind(Composing.getCurrent);
  6974. }
  6975. }
  6976. };
  6977. };
  6978. var Form = {
  6979. getField: makeApi(function (apis, component, key) {
  6980. return apis.getField(component, key);
  6981. }),
  6982. sketch: sketch$5
  6983. };
  6984. var api$2 = function () {
  6985. var subject = Cell(Optional.none());
  6986. var revoke = function () {
  6987. return subject.get().each(function (s) {
  6988. return s.destroy();
  6989. });
  6990. };
  6991. var clear = function () {
  6992. revoke();
  6993. subject.set(Optional.none());
  6994. };
  6995. var set = function (s) {
  6996. revoke();
  6997. subject.set(Optional.some(s));
  6998. };
  6999. var run = function (f) {
  7000. return subject.get().each(f);
  7001. };
  7002. var isSet = function () {
  7003. return subject.get().isSome();
  7004. };
  7005. return {
  7006. clear: clear,
  7007. isSet: isSet,
  7008. set: set,
  7009. run: run
  7010. };
  7011. };
  7012. var value$2 = function () {
  7013. var subject = Cell(Optional.none());
  7014. var clear = function () {
  7015. return subject.set(Optional.none());
  7016. };
  7017. var set = function (s) {
  7018. return subject.set(Optional.some(s));
  7019. };
  7020. var isSet = function () {
  7021. return subject.get().isSome();
  7022. };
  7023. var on = function (f) {
  7024. return subject.get().each(f);
  7025. };
  7026. return {
  7027. clear: clear,
  7028. set: set,
  7029. isSet: isSet,
  7030. on: on
  7031. };
  7032. };
  7033. var SWIPING_LEFT = 1;
  7034. var SWIPING_RIGHT = -1;
  7035. var SWIPING_NONE = 0;
  7036. var init$2 = function (xValue) {
  7037. return {
  7038. xValue: xValue,
  7039. points: []
  7040. };
  7041. };
  7042. var move$1 = function (model, xValue) {
  7043. if (xValue === model.xValue) {
  7044. return model;
  7045. }
  7046. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7047. var newPoint = {
  7048. direction: currentDirection,
  7049. xValue: xValue
  7050. };
  7051. var priorPoints = function () {
  7052. if (model.points.length === 0) {
  7053. return [];
  7054. } else {
  7055. var prev = model.points[model.points.length - 1];
  7056. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7057. }
  7058. }();
  7059. return {
  7060. xValue: xValue,
  7061. points: priorPoints.concat([newPoint])
  7062. };
  7063. };
  7064. var complete = function (model) {
  7065. if (model.points.length === 0) {
  7066. return SWIPING_NONE;
  7067. } else {
  7068. var firstDirection = model.points[0].direction;
  7069. var lastDirection = model.points[model.points.length - 1].direction;
  7070. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7071. }
  7072. };
  7073. var sketch$6 = function (rawSpec) {
  7074. var navigateEvent = 'navigateEvent';
  7075. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7076. var formAdhocEvents = 'form-events';
  7077. var schema = objOf([
  7078. strict$1('fields'),
  7079. defaulted$1('maxFieldIndex', rawSpec.fields.length - 1),
  7080. strict$1('onExecute'),
  7081. strict$1('getInitialValue'),
  7082. state$1('state', function () {
  7083. return {
  7084. dialogSwipeState: value$2(),
  7085. currentScreen: Cell(0)
  7086. };
  7087. })
  7088. ]);
  7089. var spec$1 = asRawOrDie('SerialisedDialog', schema, rawSpec);
  7090. var navigationButton = function (direction, directionName, enabled) {
  7091. return Button.sketch({
  7092. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7093. action: function (button) {
  7094. emitWith(button, navigateEvent, { direction: direction });
  7095. },
  7096. buttonBehaviours: derive$1([Disabling.config({
  7097. disableClass: resolve('toolbar-navigation-disabled'),
  7098. disabled: function () {
  7099. return !enabled;
  7100. }
  7101. })])
  7102. });
  7103. };
  7104. var reposition = function (dialog, message) {
  7105. descendant$1(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7106. set$3(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  7107. });
  7108. };
  7109. var navigate = function (dialog, direction) {
  7110. var screens = descendants(dialog.element, '.' + resolve('serialised-dialog-screen'));
  7111. descendant$1(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7112. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  7113. getRaw(parent, 'left').each(function (left) {
  7114. var currentLeft = parseInt(left, 10);
  7115. var w = get$7(screens[0]);
  7116. set$3(parent, 'left', currentLeft - direction * w + 'px');
  7117. });
  7118. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  7119. }
  7120. });
  7121. };
  7122. var focusInput = function (dialog) {
  7123. var inputs = descendants(dialog.element, 'input');
  7124. var optInput = Optional.from(inputs[spec$1.state.currentScreen.get()]);
  7125. optInput.each(function (input) {
  7126. dialog.getSystem().getByDom(input).each(function (inputComp) {
  7127. dispatchFocus(dialog, inputComp.element);
  7128. });
  7129. });
  7130. var dotitems = memDots.get(dialog);
  7131. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  7132. };
  7133. var resetState = function () {
  7134. spec$1.state.currentScreen.set(0);
  7135. spec$1.state.dialogSwipeState.clear();
  7136. };
  7137. var memForm = record(Form.sketch(function (parts) {
  7138. return {
  7139. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  7140. components: [Container.sketch({
  7141. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  7142. components: map(spec$1.fields, function (field, i) {
  7143. return i <= spec$1.maxFieldIndex ? Container.sketch({
  7144. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  7145. components: [
  7146. navigationButton(-1, 'previous', i > 0),
  7147. parts.field(field.name, field.spec),
  7148. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  7149. ]
  7150. }) : parts.field(field.name, field.spec);
  7151. })
  7152. })],
  7153. formBehaviours: derive$1([
  7154. orientation(function (dialog, message) {
  7155. reposition(dialog, message);
  7156. }),
  7157. Keying.config({
  7158. mode: 'special',
  7159. focusIn: function (dialog, _specialInfo) {
  7160. focusInput(dialog);
  7161. },
  7162. onTab: function (dialog, _specialInfo) {
  7163. navigate(dialog, +1);
  7164. return Optional.some(true);
  7165. },
  7166. onShiftTab: function (dialog, _specialInfo) {
  7167. navigate(dialog, -1);
  7168. return Optional.some(true);
  7169. }
  7170. }),
  7171. config(formAdhocEvents, [
  7172. runOnAttached(function (dialog, _simulatedEvent) {
  7173. resetState();
  7174. var dotitems = memDots.get(dialog);
  7175. Highlighting.highlightFirst(dotitems);
  7176. spec$1.getInitialValue(dialog).each(function (v) {
  7177. Representing.setValue(dialog, v);
  7178. });
  7179. }),
  7180. runOnExecute(spec$1.onExecute),
  7181. run(transitionend(), function (dialog, simulatedEvent) {
  7182. var event = simulatedEvent.event;
  7183. if (event.raw.propertyName === 'left') {
  7184. focusInput(dialog);
  7185. }
  7186. }),
  7187. run(navigateEvent, function (dialog, simulatedEvent) {
  7188. var event = simulatedEvent.event;
  7189. var direction = event.direction;
  7190. navigate(dialog, direction);
  7191. })
  7192. ])
  7193. ])
  7194. };
  7195. }));
  7196. var memDots = record({
  7197. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7198. behaviours: derive$1([Highlighting.config({
  7199. highlightClass: resolve('dot-active'),
  7200. itemClass: resolve('dot-item')
  7201. })]),
  7202. components: bind(spec$1.fields, function (_f, i) {
  7203. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7204. })
  7205. });
  7206. return {
  7207. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7208. components: [
  7209. memForm.asSpec(),
  7210. memDots.asSpec()
  7211. ],
  7212. behaviours: derive$1([
  7213. Keying.config({
  7214. mode: 'special',
  7215. focusIn: function (wrapper) {
  7216. var form = memForm.get(wrapper);
  7217. Keying.focusIn(form);
  7218. }
  7219. }),
  7220. config(wrapperAdhocEvents, [
  7221. run(touchstart(), function (_wrapper, simulatedEvent) {
  7222. var event = simulatedEvent.event;
  7223. spec$1.state.dialogSwipeState.set(init$2(event.raw.touches[0].clientX));
  7224. }),
  7225. run(touchmove(), function (_wrapper, simulatedEvent) {
  7226. var event = simulatedEvent.event;
  7227. spec$1.state.dialogSwipeState.on(function (state) {
  7228. simulatedEvent.event.prevent();
  7229. spec$1.state.dialogSwipeState.set(move$1(state, event.raw.touches[0].clientX));
  7230. });
  7231. }),
  7232. run(touchend(), function (wrapper, _simulatedEvent) {
  7233. spec$1.state.dialogSwipeState.on(function (state) {
  7234. var dialog = memForm.get(wrapper);
  7235. var direction = -1 * complete(state);
  7236. navigate(dialog, direction);
  7237. });
  7238. })
  7239. ])
  7240. ])
  7241. };
  7242. };
  7243. var getGroups = cached(function (realm, editor) {
  7244. return [{
  7245. label: 'the link group',
  7246. items: [sketch$6({
  7247. fields: [
  7248. field$2('url', 'Type or paste URL'),
  7249. field$2('text', 'Link text'),
  7250. field$2('title', 'Link title'),
  7251. field$2('target', 'Link target'),
  7252. hidden('link')
  7253. ],
  7254. maxFieldIndex: [
  7255. 'url',
  7256. 'text',
  7257. 'title',
  7258. 'target'
  7259. ].length - 1,
  7260. getInitialValue: function () {
  7261. return Optional.some(getInfo(editor));
  7262. },
  7263. onExecute: function (dialog, _simulatedEvent) {
  7264. var info = Representing.getValue(dialog);
  7265. applyInfo(editor, info);
  7266. realm.restoreToolbar();
  7267. editor.focus();
  7268. }
  7269. })]
  7270. }];
  7271. });
  7272. var sketch$7 = function (realm, editor) {
  7273. return forToolbarStateAction(editor, 'link', 'link', function () {
  7274. var groups = getGroups(realm, editor);
  7275. realm.setContextToolbar(groups);
  7276. forAndroid(editor, function () {
  7277. realm.focusToolbar();
  7278. });
  7279. query(editor).each(function (link) {
  7280. editor.selection.select(link.dom);
  7281. });
  7282. });
  7283. };
  7284. var isRecursive = function (component, originator, target) {
  7285. return eq(originator, component.element) && !eq(originator, target);
  7286. };
  7287. var events$8 = derive([can(focus(), function (component, simulatedEvent) {
  7288. var event = simulatedEvent.event;
  7289. var originator = event.originator;
  7290. var target = event.target;
  7291. if (isRecursive(component, originator, target)) {
  7292. console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  7293. return false;
  7294. } else {
  7295. return true;
  7296. }
  7297. })]);
  7298. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7299. __proto__: null,
  7300. events: events$8
  7301. });
  7302. var make$1 = identity;
  7303. var NoContextApi = function (getComp) {
  7304. var fail = function (event) {
  7305. return function () {
  7306. throw new Error('The component must be in a context to send: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : ''));
  7307. };
  7308. };
  7309. return {
  7310. debugInfo: constant('fake'),
  7311. triggerEvent: fail('triggerEvent'),
  7312. triggerFocus: fail('triggerFocus'),
  7313. triggerEscape: fail('triggerEscape'),
  7314. build: fail('build'),
  7315. addToWorld: fail('addToWorld'),
  7316. removeFromWorld: fail('removeFromWorld'),
  7317. addToGui: fail('addToGui'),
  7318. removeFromGui: fail('removeFromGui'),
  7319. getByUid: fail('getByUid'),
  7320. getByDom: fail('getByDom'),
  7321. broadcast: fail('broadcast'),
  7322. broadcastOn: fail('broadcastOn'),
  7323. broadcastEvent: fail('broadcastEvent'),
  7324. isConnected: never
  7325. };
  7326. };
  7327. var singleton = NoContextApi();
  7328. var generateFrom = function (spec, all) {
  7329. var schema = map(all, function (a) {
  7330. return optionObjOf(a.name(), [
  7331. strict$1('config'),
  7332. defaulted$1('state', NoState)
  7333. ]);
  7334. });
  7335. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7336. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7337. }, function (v) {
  7338. return v;
  7339. });
  7340. return {
  7341. list: all,
  7342. data: map$1(validated, function (optBlobThunk) {
  7343. var output = optBlobThunk.map(function (blob) {
  7344. return {
  7345. config: blob.config,
  7346. state: blob.state.init(blob.config)
  7347. };
  7348. });
  7349. return function () {
  7350. return output;
  7351. };
  7352. })
  7353. };
  7354. };
  7355. var getBehaviours = function (bData) {
  7356. return bData.list;
  7357. };
  7358. var getData = function (bData) {
  7359. return bData.data;
  7360. };
  7361. var byInnerKey = function (data, tuple) {
  7362. var r = {};
  7363. each$1(data, function (detail, key) {
  7364. each$1(detail, function (value, indexKey) {
  7365. var chain = get(r, indexKey).getOr([]);
  7366. r[indexKey] = chain.concat([tuple(key, value)]);
  7367. });
  7368. });
  7369. return r;
  7370. };
  7371. var combine$1 = function (info, baseMod, behaviours, base) {
  7372. var modsByBehaviour = __assign({}, baseMod);
  7373. each(behaviours, function (behaviour) {
  7374. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7375. });
  7376. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  7377. return {
  7378. name: name,
  7379. modification: modification
  7380. };
  7381. });
  7382. var combineObjects = function (objects) {
  7383. return foldr(objects, function (b, a) {
  7384. return __assign(__assign({}, a.modification), b);
  7385. }, {});
  7386. };
  7387. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7388. return a.modification.concat(b);
  7389. }, []);
  7390. var combinedAttributes = combineObjects(byAspect.attributes);
  7391. var combinedStyles = combineObjects(byAspect.styles);
  7392. return nu$5({
  7393. classes: combinedClasses,
  7394. attributes: combinedAttributes,
  7395. styles: combinedStyles
  7396. });
  7397. };
  7398. var sortKeys = function (label, keyName, array, order) {
  7399. try {
  7400. var sorted = sort(array, function (a, b) {
  7401. var aKey = a[keyName];
  7402. var bKey = b[keyName];
  7403. var aIndex = order.indexOf(aKey);
  7404. var bIndex = order.indexOf(bKey);
  7405. if (aIndex === -1) {
  7406. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7407. }
  7408. if (bIndex === -1) {
  7409. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7410. }
  7411. if (aIndex < bIndex) {
  7412. return -1;
  7413. } else if (bIndex < aIndex) {
  7414. return 1;
  7415. } else {
  7416. return 0;
  7417. }
  7418. });
  7419. return Result.value(sorted);
  7420. } catch (err) {
  7421. return Result.error([err]);
  7422. }
  7423. };
  7424. var uncurried = function (handler, purpose) {
  7425. return {
  7426. handler: handler,
  7427. purpose: purpose
  7428. };
  7429. };
  7430. var curried = function (handler, purpose) {
  7431. return {
  7432. cHandler: handler,
  7433. purpose: purpose
  7434. };
  7435. };
  7436. var curryArgs = function (descHandler, extraArgs) {
  7437. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  7438. };
  7439. var getCurried = function (descHandler) {
  7440. return descHandler.cHandler;
  7441. };
  7442. var behaviourTuple = function (name, handler) {
  7443. return {
  7444. name: name,
  7445. handler: handler
  7446. };
  7447. };
  7448. var nameToHandlers = function (behaviours, info) {
  7449. var r = {};
  7450. each(behaviours, function (behaviour) {
  7451. r[behaviour.name()] = behaviour.handlers(info);
  7452. });
  7453. return r;
  7454. };
  7455. var groupByEvents = function (info, behaviours, base) {
  7456. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7457. return byInnerKey(behaviourEvents, behaviourTuple);
  7458. };
  7459. var combine$2 = function (info, eventOrder, behaviours, base) {
  7460. var byEventName = groupByEvents(info, behaviours, base);
  7461. return combineGroups(byEventName, eventOrder);
  7462. };
  7463. var assemble = function (rawHandler) {
  7464. var handler = read$1(rawHandler);
  7465. return function (component, simulatedEvent) {
  7466. var rest = [];
  7467. for (var _i = 2; _i < arguments.length; _i++) {
  7468. rest[_i - 2] = arguments[_i];
  7469. }
  7470. var args = [
  7471. component,
  7472. simulatedEvent
  7473. ].concat(rest);
  7474. if (handler.abort.apply(undefined, args)) {
  7475. simulatedEvent.stop();
  7476. } else if (handler.can.apply(undefined, args)) {
  7477. handler.run.apply(undefined, args);
  7478. }
  7479. };
  7480. };
  7481. var missingOrderError = function (eventName, tuples) {
  7482. 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(tuples, function (c) {
  7483. return c.name;
  7484. }), null, 2)]);
  7485. };
  7486. var fuse$1 = function (tuples, eventOrder, eventName) {
  7487. var order = eventOrder[eventName];
  7488. if (!order) {
  7489. return missingOrderError(eventName, tuples);
  7490. } else {
  7491. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7492. var handlers = map(sortedTuples, function (tuple) {
  7493. return tuple.handler;
  7494. });
  7495. return fuse(handlers);
  7496. });
  7497. }
  7498. };
  7499. var combineGroups = function (byEventName, eventOrder) {
  7500. var r = mapToArray(byEventName, function (tuples, eventName) {
  7501. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse$1(tuples, eventOrder, eventName);
  7502. return combined.map(function (handler) {
  7503. var assembled = assemble(handler);
  7504. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  7505. return exists(tuples, function (t) {
  7506. return t.name === o;
  7507. });
  7508. }).join(' > ') : tuples[0].name;
  7509. return wrap$1(eventName, uncurried(assembled, purpose));
  7510. });
  7511. });
  7512. return consolidate(r, {});
  7513. };
  7514. var baseBehaviour = 'alloy.base.behaviour';
  7515. var toInfo = function (spec) {
  7516. var _a;
  7517. return asRaw('custom.definition', objOf([
  7518. field('dom', 'dom', strict(), objOf([
  7519. strict$1('tag'),
  7520. defaulted$1('styles', {}),
  7521. defaulted$1('classes', []),
  7522. defaulted$1('attributes', {}),
  7523. option('value'),
  7524. option('innerHtml')
  7525. ])),
  7526. strict$1('components'),
  7527. strict$1('uid'),
  7528. defaulted$1('events', {}),
  7529. defaulted$1('apis', {}),
  7530. field('eventOrder', 'eventOrder', mergeWith((_a = {}, _a[execute()] = [
  7531. 'disabling',
  7532. baseBehaviour,
  7533. 'toggling',
  7534. 'typeaheadevents'
  7535. ], _a[focus()] = [
  7536. baseBehaviour,
  7537. 'focusing',
  7538. 'keying'
  7539. ], _a[systemInit()] = [
  7540. baseBehaviour,
  7541. 'disabling',
  7542. 'toggling',
  7543. 'representing'
  7544. ], _a[input()] = [
  7545. baseBehaviour,
  7546. 'representing',
  7547. 'streaming',
  7548. 'invalidating'
  7549. ], _a[detachedFromDom()] = [
  7550. baseBehaviour,
  7551. 'representing',
  7552. 'item-events',
  7553. 'tooltipping'
  7554. ], _a[mousedown()] = [
  7555. 'focusing',
  7556. baseBehaviour,
  7557. 'item-type-events'
  7558. ], _a[touchstart()] = [
  7559. 'focusing',
  7560. baseBehaviour,
  7561. 'item-type-events'
  7562. ], _a[mouseover()] = [
  7563. 'item-type-events',
  7564. 'tooltipping'
  7565. ], _a[receive()] = [
  7566. 'receiving',
  7567. 'reflecting',
  7568. 'tooltipping'
  7569. ], _a)), anyValue$1()),
  7570. option('domModification')
  7571. ]), spec);
  7572. };
  7573. var toDefinition = function (detail) {
  7574. return __assign(__assign({}, detail.dom), {
  7575. uid: detail.uid,
  7576. domChildren: map(detail.components, function (comp) {
  7577. return comp.element;
  7578. })
  7579. });
  7580. };
  7581. var toModification = function (detail) {
  7582. return detail.domModification.fold(function () {
  7583. return nu$5({});
  7584. }, nu$5);
  7585. };
  7586. var toEvents = function (info) {
  7587. return info.events;
  7588. };
  7589. var add$3 = function (element, classes) {
  7590. each(classes, function (x) {
  7591. add$2(element, x);
  7592. });
  7593. };
  7594. var remove$6 = function (element, classes) {
  7595. each(classes, function (x) {
  7596. remove$4(element, x);
  7597. });
  7598. };
  7599. var renderToDom = function (definition) {
  7600. var subject = SugarElement.fromTag(definition.tag);
  7601. setAll(subject, definition.attributes);
  7602. add$3(subject, definition.classes);
  7603. setAll$1(subject, definition.styles);
  7604. definition.innerHtml.each(function (html) {
  7605. return set$1(subject, html);
  7606. });
  7607. var children = definition.domChildren;
  7608. append$1(subject, children);
  7609. definition.value.each(function (value) {
  7610. set$6(subject, value);
  7611. });
  7612. if (!definition.uid) {
  7613. debugger;
  7614. }
  7615. writeOnly(subject, definition.uid);
  7616. return subject;
  7617. };
  7618. var getBehaviours$1 = function (spec) {
  7619. var behaviours = get(spec, 'behaviours').getOr({});
  7620. var keys$1 = filter(keys(behaviours), function (k) {
  7621. return behaviours[k] !== undefined;
  7622. });
  7623. return map(keys$1, function (k) {
  7624. return behaviours[k].me;
  7625. });
  7626. };
  7627. var generateFrom$1 = function (spec, all) {
  7628. return generateFrom(spec, all);
  7629. };
  7630. var generate$4 = function (spec) {
  7631. var all = getBehaviours$1(spec);
  7632. return generateFrom$1(spec, all);
  7633. };
  7634. var getDomDefinition = function (info, bList, bData) {
  7635. var definition = toDefinition(info);
  7636. var infoModification = toModification(info);
  7637. var baseModification = { 'alloy.base.modification': infoModification };
  7638. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7639. return merge$1(definition, modification);
  7640. };
  7641. var getEvents = function (info, bList, bData) {
  7642. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7643. return combine$2(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7644. };
  7645. var build = function (spec) {
  7646. var getMe = function () {
  7647. return me;
  7648. };
  7649. var systemApi = Cell(singleton);
  7650. var info = getOrDie(toInfo(spec));
  7651. var bBlob = generate$4(spec);
  7652. var bList = getBehaviours(bBlob);
  7653. var bData = getData(bBlob);
  7654. var modDefinition = getDomDefinition(info, bList, bData);
  7655. var item = renderToDom(modDefinition);
  7656. var events = getEvents(info, bList, bData);
  7657. var subcomponents = Cell(info.components);
  7658. var connect = function (newApi) {
  7659. systemApi.set(newApi);
  7660. };
  7661. var disconnect = function () {
  7662. systemApi.set(NoContextApi(getMe));
  7663. };
  7664. var syncComponents = function () {
  7665. var children$1 = children(item);
  7666. var subs = bind(children$1, function (child) {
  7667. return systemApi.get().getByDom(child).fold(function () {
  7668. return [];
  7669. }, function (c) {
  7670. return [c];
  7671. });
  7672. });
  7673. subcomponents.set(subs);
  7674. };
  7675. var config = function (behaviour) {
  7676. var b = bData;
  7677. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7678. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7679. };
  7680. return f();
  7681. };
  7682. var hasConfigured = function (behaviour) {
  7683. return isFunction(bData[behaviour.name()]);
  7684. };
  7685. var getApis = function () {
  7686. return info.apis;
  7687. };
  7688. var readState = function (behaviourName) {
  7689. return bData[behaviourName]().map(function (b) {
  7690. return b.state.readState();
  7691. }).getOr('not enabled');
  7692. };
  7693. var me = {
  7694. getSystem: systemApi.get,
  7695. config: config,
  7696. hasConfigured: hasConfigured,
  7697. spec: spec,
  7698. readState: readState,
  7699. getApis: getApis,
  7700. connect: connect,
  7701. disconnect: disconnect,
  7702. element: item,
  7703. syncComponents: syncComponents,
  7704. components: subcomponents.get,
  7705. events: events
  7706. };
  7707. return me;
  7708. };
  7709. var buildSubcomponents = function (spec) {
  7710. var components = get(spec, 'components').getOr([]);
  7711. return map(components, build$1);
  7712. };
  7713. var buildFromSpec = function (userSpec) {
  7714. var _a = make$1(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7715. var components = buildSubcomponents(spec);
  7716. var completeSpec = __assign(__assign({}, spec), {
  7717. events: __assign(__assign({}, DefaultEvents), specEvents),
  7718. components: components
  7719. });
  7720. return Result.value(build(completeSpec));
  7721. };
  7722. var text = function (textContent) {
  7723. var element = SugarElement.fromText(textContent);
  7724. return external$1({ element: element });
  7725. };
  7726. var external$1 = function (spec) {
  7727. var extSpec = asRawOrDie('external.component', objOfOnly([
  7728. strict$1('element'),
  7729. option('uid')
  7730. ]), spec);
  7731. var systemApi = Cell(NoContextApi());
  7732. var connect = function (newApi) {
  7733. systemApi.set(newApi);
  7734. };
  7735. var disconnect = function () {
  7736. systemApi.set(NoContextApi(function () {
  7737. return me;
  7738. }));
  7739. };
  7740. extSpec.uid.each(function (uid) {
  7741. writeOnly(extSpec.element, uid);
  7742. });
  7743. var me = {
  7744. getSystem: systemApi.get,
  7745. config: Optional.none,
  7746. hasConfigured: never,
  7747. connect: connect,
  7748. disconnect: disconnect,
  7749. getApis: function () {
  7750. return {};
  7751. },
  7752. element: extSpec.element,
  7753. spec: spec,
  7754. readState: constant('No state'),
  7755. syncComponents: noop,
  7756. components: constant([]),
  7757. events: {}
  7758. };
  7759. return premade(me);
  7760. };
  7761. var uids = generate$3;
  7762. var build$1 = function (spec) {
  7763. return getPremade(spec).fold(function () {
  7764. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  7765. return buildFromSpec(userSpecWithUid).getOrDie();
  7766. }, function (prebuilt) {
  7767. return prebuilt;
  7768. });
  7769. };
  7770. var premade$1 = premade;
  7771. var hoverEvent = 'alloy.item-hover';
  7772. var focusEvent = 'alloy.item-focus';
  7773. var onHover = function (item) {
  7774. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7775. if (!Focusing.isFocused(item)) {
  7776. Focusing.focus(item);
  7777. }
  7778. emitWith(item, hoverEvent, { item: item });
  7779. }
  7780. };
  7781. var onFocus = function (item) {
  7782. emitWith(item, focusEvent, { item: item });
  7783. };
  7784. var hover = constant(hoverEvent);
  7785. var focus$3 = constant(focusEvent);
  7786. var builder = function (detail) {
  7787. return {
  7788. dom: detail.dom,
  7789. 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 } : {}) }),
  7790. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7791. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7792. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7793. }),
  7794. Focusing.config({
  7795. ignore: detail.ignoreFocus,
  7796. stopMousedown: detail.ignoreFocus,
  7797. onFocus: function (component) {
  7798. onFocus(component);
  7799. }
  7800. }),
  7801. Keying.config({ mode: 'execution' }),
  7802. Representing.config({
  7803. store: {
  7804. mode: 'memory',
  7805. initialValue: detail.data
  7806. }
  7807. }),
  7808. config('item-type-events', __spreadArrays(pointerEvents(), [
  7809. run(mouseover(), onHover),
  7810. run(focusItem(), Focusing.focus)
  7811. ]))
  7812. ]),
  7813. components: detail.components,
  7814. eventOrder: detail.eventOrder
  7815. };
  7816. };
  7817. var schema$a = [
  7818. strict$1('data'),
  7819. strict$1('components'),
  7820. strict$1('dom'),
  7821. defaulted$1('hasSubmenu', false),
  7822. option('toggling'),
  7823. SketchBehaviours.field('itemBehaviours', [
  7824. Toggling,
  7825. Focusing,
  7826. Keying,
  7827. Representing
  7828. ]),
  7829. defaulted$1('ignoreFocus', false),
  7830. defaulted$1('domModification', {}),
  7831. output('builder', builder),
  7832. defaulted$1('eventOrder', {})
  7833. ];
  7834. var builder$1 = function (detail) {
  7835. return {
  7836. dom: detail.dom,
  7837. components: detail.components,
  7838. events: derive([stopper(focusItem())])
  7839. };
  7840. };
  7841. var schema$b = [
  7842. strict$1('dom'),
  7843. strict$1('components'),
  7844. output('builder', builder$1)
  7845. ];
  7846. var owner$2 = function () {
  7847. return 'item-widget';
  7848. };
  7849. var parts = constant([required({
  7850. name: 'widget',
  7851. overrides: function (detail) {
  7852. return {
  7853. behaviours: derive$1([Representing.config({
  7854. store: {
  7855. mode: 'manual',
  7856. getValue: function (_component) {
  7857. return detail.data;
  7858. },
  7859. setValue: function () {
  7860. }
  7861. }
  7862. })])
  7863. };
  7864. }
  7865. })]);
  7866. var builder$2 = function (detail) {
  7867. var subs = substitutes(owner$2(), detail, parts());
  7868. var components$1 = components(owner$2(), detail, subs.internals());
  7869. var focusWidget = function (component) {
  7870. return getPart(component, detail, 'widget').map(function (widget) {
  7871. Keying.focusIn(widget);
  7872. return widget;
  7873. });
  7874. };
  7875. var onHorizontalArrow = function (component, simulatedEvent) {
  7876. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  7877. if (detail.autofocus) {
  7878. simulatedEvent.setSource(component.element);
  7879. return Optional.none();
  7880. } else {
  7881. return Optional.none();
  7882. }
  7883. }();
  7884. };
  7885. return {
  7886. dom: detail.dom,
  7887. components: components$1,
  7888. domModification: detail.domModification,
  7889. events: derive([
  7890. runOnExecute(function (component, simulatedEvent) {
  7891. focusWidget(component).each(function (_widget) {
  7892. simulatedEvent.stop();
  7893. });
  7894. }),
  7895. run(mouseover(), onHover),
  7896. run(focusItem(), function (component, _simulatedEvent) {
  7897. if (detail.autofocus) {
  7898. focusWidget(component);
  7899. } else {
  7900. Focusing.focus(component);
  7901. }
  7902. })
  7903. ]),
  7904. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7905. Representing.config({
  7906. store: {
  7907. mode: 'memory',
  7908. initialValue: detail.data
  7909. }
  7910. }),
  7911. Focusing.config({
  7912. ignore: detail.ignoreFocus,
  7913. onFocus: function (component) {
  7914. onFocus(component);
  7915. }
  7916. }),
  7917. Keying.config({
  7918. mode: 'special',
  7919. focusIn: detail.autofocus ? function (component) {
  7920. focusWidget(component);
  7921. } : revoke(),
  7922. onLeft: onHorizontalArrow,
  7923. onRight: onHorizontalArrow,
  7924. onEscape: function (component, simulatedEvent) {
  7925. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7926. Focusing.focus(component);
  7927. return Optional.some(true);
  7928. } else if (detail.autofocus) {
  7929. simulatedEvent.setSource(component.element);
  7930. return Optional.none();
  7931. } else {
  7932. return Optional.none();
  7933. }
  7934. }
  7935. })
  7936. ])
  7937. };
  7938. };
  7939. var schema$c = [
  7940. strict$1('uid'),
  7941. strict$1('data'),
  7942. strict$1('components'),
  7943. strict$1('dom'),
  7944. defaulted$1('autofocus', false),
  7945. defaulted$1('ignoreFocus', false),
  7946. SketchBehaviours.field('widgetBehaviours', [
  7947. Representing,
  7948. Focusing,
  7949. Keying
  7950. ]),
  7951. defaulted$1('domModification', {}),
  7952. defaultUidsSchema(parts()),
  7953. output('builder', builder$2)
  7954. ];
  7955. var itemSchema$1 = choose$1('type', {
  7956. widget: schema$c,
  7957. item: schema$a,
  7958. separator: schema$b
  7959. });
  7960. var configureGrid = function (detail, movementInfo) {
  7961. return {
  7962. mode: 'flatgrid',
  7963. selector: '.' + detail.markers.item,
  7964. initSize: {
  7965. numColumns: movementInfo.initSize.numColumns,
  7966. numRows: movementInfo.initSize.numRows
  7967. },
  7968. focusManager: detail.focusManager
  7969. };
  7970. };
  7971. var configureMatrix = function (detail, movementInfo) {
  7972. return {
  7973. mode: 'matrix',
  7974. selectors: {
  7975. row: movementInfo.rowSelector,
  7976. cell: '.' + detail.markers.item
  7977. },
  7978. focusManager: detail.focusManager
  7979. };
  7980. };
  7981. var configureMenu = function (detail, movementInfo) {
  7982. return {
  7983. mode: 'menu',
  7984. selector: '.' + detail.markers.item,
  7985. moveOnTab: movementInfo.moveOnTab,
  7986. focusManager: detail.focusManager
  7987. };
  7988. };
  7989. var parts$1 = constant([group({
  7990. factory: {
  7991. sketch: function (spec) {
  7992. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  7993. return itemInfo.builder(itemInfo);
  7994. }
  7995. },
  7996. name: 'items',
  7997. unit: 'item',
  7998. defaults: function (detail, u) {
  7999. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$3('item') });
  8000. },
  8001. overrides: function (detail, u) {
  8002. return {
  8003. type: u.type,
  8004. ignoreFocus: detail.fakeFocus,
  8005. domModification: { classes: [detail.markers.item] }
  8006. };
  8007. }
  8008. })]);
  8009. var schema$d = constant([
  8010. strict$1('value'),
  8011. strict$1('items'),
  8012. strict$1('dom'),
  8013. strict$1('components'),
  8014. defaulted$1('eventOrder', {}),
  8015. field$1('menuBehaviours', [
  8016. Highlighting,
  8017. Representing,
  8018. Composing,
  8019. Keying
  8020. ]),
  8021. defaultedOf('movement', {
  8022. mode: 'menu',
  8023. moveOnTab: true
  8024. }, choose$1('mode', {
  8025. grid: [
  8026. initSize(),
  8027. output('config', configureGrid)
  8028. ],
  8029. matrix: [
  8030. output('config', configureMatrix),
  8031. strict$1('rowSelector')
  8032. ],
  8033. menu: [
  8034. defaulted$1('moveOnTab', true),
  8035. output('config', configureMenu)
  8036. ]
  8037. })),
  8038. itemMarkers(),
  8039. defaulted$1('fakeFocus', false),
  8040. defaulted$1('focusManager', dom()),
  8041. onHandler('onHighlight')
  8042. ]);
  8043. var focus$4 = constant('alloy.menu-focus');
  8044. var make$2 = function (detail, components, _spec, _externals) {
  8045. return {
  8046. uid: detail.uid,
  8047. dom: detail.dom,
  8048. markers: detail.markers,
  8049. behaviours: augment(detail.menuBehaviours, [
  8050. Highlighting.config({
  8051. highlightClass: detail.markers.selectedItem,
  8052. itemClass: detail.markers.item,
  8053. onHighlight: detail.onHighlight
  8054. }),
  8055. Representing.config({
  8056. store: {
  8057. mode: 'memory',
  8058. initialValue: detail.value
  8059. }
  8060. }),
  8061. Composing.config({ find: Optional.some }),
  8062. Keying.config(detail.movement.config(detail, detail.movement))
  8063. ]),
  8064. events: derive([
  8065. run(focus$3(), function (menu, simulatedEvent) {
  8066. var event = simulatedEvent.event;
  8067. menu.getSystem().getByDom(event.target).each(function (item) {
  8068. Highlighting.highlight(menu, item);
  8069. simulatedEvent.stop();
  8070. emitWith(menu, focus$4(), {
  8071. menu: menu,
  8072. item: item
  8073. });
  8074. });
  8075. }),
  8076. run(hover(), function (menu, simulatedEvent) {
  8077. var item = simulatedEvent.event.item;
  8078. Highlighting.highlight(menu, item);
  8079. })
  8080. ]),
  8081. components: components,
  8082. eventOrder: detail.eventOrder,
  8083. domModification: { attributes: { role: 'menu' } }
  8084. };
  8085. };
  8086. var Menu = composite$1({
  8087. name: 'Menu',
  8088. configFields: schema$d(),
  8089. partFields: parts$1(),
  8090. factory: make$2
  8091. });
  8092. var preserve$1 = function (f, container) {
  8093. var dos = getRootNode(container);
  8094. var refocus = active(dos).bind(function (focused) {
  8095. var hasFocus = function (elem) {
  8096. return eq(focused, elem);
  8097. };
  8098. return hasFocus(container) ? Optional.some(container) : descendant(container, hasFocus);
  8099. });
  8100. var result = f(container);
  8101. refocus.each(function (oldFocus) {
  8102. active(dos).filter(function (newFocus) {
  8103. return eq(newFocus, oldFocus);
  8104. }).fold(function () {
  8105. focus$1(oldFocus);
  8106. }, noop);
  8107. });
  8108. return result;
  8109. };
  8110. var set$8 = function (component, replaceConfig, replaceState, data) {
  8111. preserve$1(function () {
  8112. var newChildren = map(data, component.getSystem().build);
  8113. replaceChildren(component, newChildren);
  8114. }, component.element);
  8115. };
  8116. var insert = function (component, replaceConfig, insertion, childSpec) {
  8117. var child = component.getSystem().build(childSpec);
  8118. attachWith(component, child, insertion);
  8119. };
  8120. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  8121. insert(component, replaceConfig, append, appendee);
  8122. };
  8123. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  8124. insert(component, replaceConfig, prepend, prependee);
  8125. };
  8126. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  8127. var children = contents(component);
  8128. var foundChild = find(children, function (child) {
  8129. return eq(removee.element, child.element);
  8130. });
  8131. foundChild.each(detach);
  8132. };
  8133. var contents = function (component, _replaceConfig) {
  8134. return component.components();
  8135. };
  8136. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8137. var children = contents(component);
  8138. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  8139. remove$7(component, replaceConfig, replaceState, replacee);
  8140. replacer.each(function (r) {
  8141. insert(component, replaceConfig, function (p, c) {
  8142. appendAt(p, c, replaceeIndex);
  8143. }, r);
  8144. });
  8145. return replacee;
  8146. });
  8147. };
  8148. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8149. var children = contents(component);
  8150. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  8151. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8152. });
  8153. };
  8154. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8155. __proto__: null,
  8156. append: append$2,
  8157. prepend: prepend$1,
  8158. remove: remove$7,
  8159. replaceAt: replaceAt,
  8160. replaceBy: replaceBy,
  8161. set: set$8,
  8162. contents: contents
  8163. });
  8164. var Replacing = create$1({
  8165. fields: [],
  8166. name: 'replacing',
  8167. apis: ReplaceApis
  8168. });
  8169. var transpose = function (obj) {
  8170. return tupleMap(obj, function (v, k) {
  8171. return {
  8172. k: v,
  8173. v: k
  8174. };
  8175. });
  8176. };
  8177. var trace = function (items, byItem, byMenu, finish) {
  8178. return get(byMenu, finish).bind(function (triggerItem) {
  8179. return get(items, triggerItem).bind(function (triggerMenu) {
  8180. var rest = trace(items, byItem, byMenu, triggerMenu);
  8181. return Optional.some([triggerMenu].concat(rest));
  8182. });
  8183. }).getOr([]);
  8184. };
  8185. var generate$5 = function (menus, expansions) {
  8186. var items = {};
  8187. each$1(menus, function (menuItems, menu) {
  8188. each(menuItems, function (item) {
  8189. items[item] = menu;
  8190. });
  8191. });
  8192. var byItem = expansions;
  8193. var byMenu = transpose(expansions);
  8194. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  8195. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8196. });
  8197. return map$1(items, function (menu) {
  8198. return get(menuPaths, menu).getOr([menu]);
  8199. });
  8200. };
  8201. var init$3 = function () {
  8202. var expansions = Cell({});
  8203. var menus = Cell({});
  8204. var paths = Cell({});
  8205. var primary = Cell(Optional.none());
  8206. var directory = Cell({});
  8207. var clear = function () {
  8208. expansions.set({});
  8209. menus.set({});
  8210. paths.set({});
  8211. primary.set(Optional.none());
  8212. };
  8213. var isClear = function () {
  8214. return primary.get().isNone();
  8215. };
  8216. var setMenuBuilt = function (menuName, built) {
  8217. var _a;
  8218. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8219. type: 'prepared',
  8220. menu: built
  8221. }, _a)));
  8222. };
  8223. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8224. primary.set(Optional.some(sPrimary));
  8225. expansions.set(sExpansions);
  8226. menus.set(sMenus);
  8227. directory.set(dir);
  8228. var sPaths = generate$5(dir, sExpansions);
  8229. paths.set(sPaths);
  8230. };
  8231. var getTriggeringItem = function (menuValue) {
  8232. return find$2(expansions.get(), function (v, _k) {
  8233. return v === menuValue;
  8234. });
  8235. };
  8236. var getTriggerData = function (menuValue, getItemByValue, path) {
  8237. return getPreparedMenu(menuValue).bind(function (menu) {
  8238. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8239. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8240. return {
  8241. triggeredMenu: menu,
  8242. triggeringItem: triggeredItem,
  8243. triggeringPath: path
  8244. };
  8245. });
  8246. });
  8247. });
  8248. };
  8249. var getTriggeringPath = function (itemValue, getItemByValue) {
  8250. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  8251. return getPreparedMenu(menuValue).isSome();
  8252. });
  8253. return get(paths.get(), itemValue).bind(function (path) {
  8254. var revPath = reverse(extraPath.concat(path));
  8255. var triggers = bind(revPath, function (menuValue, menuIndex) {
  8256. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8257. return primary.get().is(menuValue) ? [] : [Optional.none()];
  8258. }, function (data) {
  8259. return [Optional.some(data)];
  8260. });
  8261. });
  8262. return sequence(triggers);
  8263. });
  8264. };
  8265. var expand = function (itemValue) {
  8266. return get(expansions.get(), itemValue).map(function (menu) {
  8267. var current = get(paths.get(), itemValue).getOr([]);
  8268. return [menu].concat(current);
  8269. });
  8270. };
  8271. var collapse = function (itemValue) {
  8272. return get(paths.get(), itemValue).bind(function (path) {
  8273. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8274. });
  8275. };
  8276. var refresh = function (itemValue) {
  8277. return get(paths.get(), itemValue);
  8278. };
  8279. var getPreparedMenu = function (menuValue) {
  8280. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8281. };
  8282. var lookupMenu = function (menuValue) {
  8283. return get(menus.get(), menuValue);
  8284. };
  8285. var lookupItem = function (itemValue) {
  8286. return get(expansions.get(), itemValue);
  8287. };
  8288. var otherMenus = function (path) {
  8289. var menuValues = directory.get();
  8290. return difference(keys(menuValues), path);
  8291. };
  8292. var getPrimary = function () {
  8293. return primary.get().bind(getPreparedMenu);
  8294. };
  8295. var getMenus = function () {
  8296. return menus.get();
  8297. };
  8298. return {
  8299. setMenuBuilt: setMenuBuilt,
  8300. setContents: setContents,
  8301. expand: expand,
  8302. refresh: refresh,
  8303. collapse: collapse,
  8304. lookupMenu: lookupMenu,
  8305. lookupItem: lookupItem,
  8306. otherMenus: otherMenus,
  8307. getPrimary: getPrimary,
  8308. getMenus: getMenus,
  8309. clear: clear,
  8310. isClear: isClear,
  8311. getTriggeringPath: getTriggeringPath
  8312. };
  8313. };
  8314. var extractPreparedMenu = function (prep) {
  8315. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8316. };
  8317. var LayeredState = {
  8318. init: init$3,
  8319. extractPreparedMenu: extractPreparedMenu
  8320. };
  8321. var make$3 = function (detail, _rawUiSpec) {
  8322. var submenuParentItems = Cell(Optional.none());
  8323. var buildMenus = function (container, primaryName, menus) {
  8324. return map$1(menus, function (spec, name) {
  8325. var makeSketch = function () {
  8326. return Menu.sketch(__assign(__assign({}, spec), {
  8327. value: name,
  8328. markers: detail.markers,
  8329. fakeFocus: detail.fakeFocus,
  8330. onHighlight: detail.onHighlight,
  8331. focusManager: detail.fakeFocus ? highlights() : dom()
  8332. }));
  8333. };
  8334. return name === primaryName ? {
  8335. type: 'prepared',
  8336. menu: container.getSystem().build(makeSketch())
  8337. } : {
  8338. type: 'notbuilt',
  8339. nbMenu: makeSketch
  8340. };
  8341. });
  8342. };
  8343. var layeredState = LayeredState.init();
  8344. var setup = function (container) {
  8345. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8346. var directory = toDirectory();
  8347. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8348. return layeredState.getPrimary();
  8349. };
  8350. var getItemValue = function (item) {
  8351. return Representing.getValue(item).value;
  8352. };
  8353. var getItemByValue = function (_container, menus, itemValue) {
  8354. return findMap(menus, function (menu) {
  8355. if (!menu.getSystem().isConnected()) {
  8356. return Optional.none();
  8357. }
  8358. var candidates = Highlighting.getCandidates(menu);
  8359. return find(candidates, function (c) {
  8360. return getItemValue(c) === itemValue;
  8361. });
  8362. });
  8363. };
  8364. var toDirectory = function (_container) {
  8365. return map$1(detail.data.menus, function (data, _menuName) {
  8366. return bind(data.items, function (item) {
  8367. return item.type === 'separator' ? [] : [item.data.value];
  8368. });
  8369. });
  8370. };
  8371. var setActiveMenu = function (container, menu) {
  8372. Highlighting.highlight(container, menu);
  8373. Highlighting.getHighlighted(menu).orThunk(function () {
  8374. return Highlighting.getFirst(menu);
  8375. }).each(function (item) {
  8376. dispatch(container, item.element, focusItem());
  8377. });
  8378. };
  8379. var getMenus = function (state, menuValues) {
  8380. return cat(map(menuValues, function (mv) {
  8381. return state.lookupMenu(mv).bind(function (prep) {
  8382. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8383. });
  8384. }));
  8385. };
  8386. var closeOthers = function (container, state, path) {
  8387. var others = getMenus(state, state.otherMenus(path));
  8388. each(others, function (o) {
  8389. remove$6(o.element, [detail.markers.backgroundMenu]);
  8390. if (!detail.stayInDom) {
  8391. Replacing.remove(container, o);
  8392. }
  8393. });
  8394. };
  8395. var getSubmenuParents = function (container) {
  8396. return submenuParentItems.get().getOrThunk(function () {
  8397. var r = {};
  8398. var items = descendants(container.element, '.' + detail.markers.item);
  8399. var parentItems = filter(items, function (i) {
  8400. return get$1(i, 'aria-haspopup') === 'true';
  8401. });
  8402. each(parentItems, function (i) {
  8403. container.getSystem().getByDom(i).each(function (itemComp) {
  8404. var key = getItemValue(itemComp);
  8405. r[key] = itemComp;
  8406. });
  8407. });
  8408. submenuParentItems.set(Optional.some(r));
  8409. return r;
  8410. });
  8411. };
  8412. var updateAriaExpansions = function (container, path) {
  8413. var parentItems = getSubmenuParents(container);
  8414. each$1(parentItems, function (v, k) {
  8415. var expanded = contains(path, k);
  8416. set(v.element, 'aria-expanded', expanded);
  8417. });
  8418. };
  8419. var updateMenuPath = function (container, state, path) {
  8420. return Optional.from(path[0]).bind(function (latestMenuName) {
  8421. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8422. if (menuPrep.type === 'notbuilt') {
  8423. return Optional.none();
  8424. } else {
  8425. var activeMenu = menuPrep.menu;
  8426. var rest = getMenus(state, path.slice(1));
  8427. each(rest, function (r) {
  8428. add$2(r.element, detail.markers.backgroundMenu);
  8429. });
  8430. if (!inBody(activeMenu.element)) {
  8431. Replacing.append(container, premade$1(activeMenu));
  8432. }
  8433. remove$6(activeMenu.element, [detail.markers.backgroundMenu]);
  8434. setActiveMenu(container, activeMenu);
  8435. closeOthers(container, state, path);
  8436. return Optional.some(activeMenu);
  8437. }
  8438. });
  8439. });
  8440. };
  8441. var ExpandHighlightDecision;
  8442. (function (ExpandHighlightDecision) {
  8443. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8444. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8445. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8446. var buildIfRequired = function (container, menuName, menuPrep) {
  8447. if (menuPrep.type === 'notbuilt') {
  8448. var menu = container.getSystem().build(menuPrep.nbMenu());
  8449. layeredState.setMenuBuilt(menuName, menu);
  8450. return menu;
  8451. } else {
  8452. return menuPrep.menu;
  8453. }
  8454. };
  8455. var expandRight = function (container, item, decision) {
  8456. if (decision === void 0) {
  8457. decision = ExpandHighlightDecision.HighlightSubmenu;
  8458. }
  8459. var value = getItemValue(item);
  8460. return layeredState.expand(value).bind(function (path) {
  8461. updateAriaExpansions(container, path);
  8462. return Optional.from(path[0]).bind(function (menuName) {
  8463. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8464. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8465. if (!inBody(activeMenu.element)) {
  8466. Replacing.append(container, premade$1(activeMenu));
  8467. }
  8468. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8469. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8470. Highlighting.highlightFirst(activeMenu);
  8471. return updateMenuPath(container, layeredState, path);
  8472. } else {
  8473. Highlighting.dehighlightAll(activeMenu);
  8474. return Optional.some(item);
  8475. }
  8476. });
  8477. });
  8478. });
  8479. };
  8480. var collapseLeft = function (container, item) {
  8481. var value = getItemValue(item);
  8482. return layeredState.collapse(value).bind(function (path) {
  8483. updateAriaExpansions(container, path);
  8484. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8485. detail.onCollapseMenu(container, item, activeMenu);
  8486. return activeMenu;
  8487. });
  8488. });
  8489. };
  8490. var updateView = function (container, item) {
  8491. var value = getItemValue(item);
  8492. return layeredState.refresh(value).bind(function (path) {
  8493. updateAriaExpansions(container, path);
  8494. return updateMenuPath(container, layeredState, path);
  8495. });
  8496. };
  8497. var onRight = function (container, item) {
  8498. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8499. };
  8500. var onLeft = function (container, item) {
  8501. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8502. };
  8503. var onEscape = function (container, item) {
  8504. return collapseLeft(container, item).orThunk(function () {
  8505. return detail.onEscape(container, item).map(function () {
  8506. return container;
  8507. });
  8508. });
  8509. };
  8510. var keyOnItem = function (f) {
  8511. return function (container, simulatedEvent) {
  8512. return closest$2(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8513. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8514. return f(container, item).map(function () {
  8515. return true;
  8516. });
  8517. });
  8518. });
  8519. };
  8520. };
  8521. var events = derive([
  8522. run(focus$4(), function (sandbox, simulatedEvent) {
  8523. var item = simulatedEvent.event.item;
  8524. layeredState.lookupItem(getItemValue(item)).each(function () {
  8525. var menu = simulatedEvent.event.menu;
  8526. Highlighting.highlight(sandbox, menu);
  8527. var value = getItemValue(simulatedEvent.event.item);
  8528. layeredState.refresh(value).each(function (path) {
  8529. return closeOthers(sandbox, layeredState, path);
  8530. });
  8531. });
  8532. }),
  8533. runOnExecute(function (component, simulatedEvent) {
  8534. var target = simulatedEvent.event.target;
  8535. component.getSystem().getByDom(target).each(function (item) {
  8536. var itemValue = getItemValue(item);
  8537. if (itemValue.indexOf('collapse-item') === 0) {
  8538. collapseLeft(component, item);
  8539. }
  8540. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8541. detail.onExecute(component, item);
  8542. }, function () {
  8543. });
  8544. });
  8545. }),
  8546. runOnAttached(function (container, _simulatedEvent) {
  8547. setup(container).each(function (primary) {
  8548. Replacing.append(container, premade$1(primary));
  8549. detail.onOpenMenu(container, primary);
  8550. if (detail.highlightImmediately) {
  8551. setActiveMenu(container, primary);
  8552. }
  8553. });
  8554. })
  8555. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8556. var item = simulatedEvent.event.item;
  8557. updateView(sandbox, item);
  8558. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8559. detail.onHover(sandbox, item);
  8560. })] : []));
  8561. var getActiveItem = function (container) {
  8562. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8563. };
  8564. var collapseMenuApi = function (container) {
  8565. getActiveItem(container).each(function (currentItem) {
  8566. collapseLeft(container, currentItem);
  8567. });
  8568. };
  8569. var highlightPrimary = function (container) {
  8570. layeredState.getPrimary().each(function (primary) {
  8571. setActiveMenu(container, primary);
  8572. });
  8573. };
  8574. var extractMenuFromContainer = function (container) {
  8575. return Optional.from(container.components()[0]).filter(function (comp) {
  8576. return get$1(comp.element, 'role') === 'menu';
  8577. });
  8578. };
  8579. var repositionMenus = function (container) {
  8580. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8581. return getActiveItem(container).bind(function (currentItem) {
  8582. var itemValue = getItemValue(currentItem);
  8583. var allMenus = values(layeredState.getMenus());
  8584. var preparedMenus = cat(map(allMenus, LayeredState.extractPreparedMenu));
  8585. return layeredState.getTriggeringPath(itemValue, function (v) {
  8586. return getItemByValue(container, preparedMenus, v);
  8587. });
  8588. }).map(function (triggeringPath) {
  8589. return {
  8590. primary: primary,
  8591. triggeringPath: triggeringPath
  8592. };
  8593. });
  8594. });
  8595. maybeActivePrimary.fold(function () {
  8596. extractMenuFromContainer(container).each(function (primaryMenu) {
  8597. detail.onRepositionMenu(container, primaryMenu, []);
  8598. });
  8599. }, function (_a) {
  8600. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8601. detail.onRepositionMenu(container, primary, triggeringPath);
  8602. });
  8603. };
  8604. var apis = {
  8605. collapseMenu: collapseMenuApi,
  8606. highlightPrimary: highlightPrimary,
  8607. repositionMenus: repositionMenus
  8608. };
  8609. return {
  8610. uid: detail.uid,
  8611. dom: detail.dom,
  8612. markers: detail.markers,
  8613. behaviours: augment(detail.tmenuBehaviours, [
  8614. Keying.config({
  8615. mode: 'special',
  8616. onRight: keyOnItem(onRight),
  8617. onLeft: keyOnItem(onLeft),
  8618. onEscape: keyOnItem(onEscape),
  8619. focusIn: function (container, _keyInfo) {
  8620. layeredState.getPrimary().each(function (primary) {
  8621. dispatch(container, primary.element, focusItem());
  8622. });
  8623. }
  8624. }),
  8625. Highlighting.config({
  8626. highlightClass: detail.markers.selectedMenu,
  8627. itemClass: detail.markers.menu
  8628. }),
  8629. Composing.config({
  8630. find: function (container) {
  8631. return Highlighting.getHighlighted(container);
  8632. }
  8633. }),
  8634. Replacing.config({})
  8635. ]),
  8636. eventOrder: detail.eventOrder,
  8637. apis: apis,
  8638. events: events
  8639. };
  8640. };
  8641. var collapseItem = constant('collapse-item');
  8642. var tieredData = function (primary, menus, expansions) {
  8643. return {
  8644. primary: primary,
  8645. menus: menus,
  8646. expansions: expansions
  8647. };
  8648. };
  8649. var singleData = function (name, menu) {
  8650. return {
  8651. primary: name,
  8652. menus: wrap$1(name, menu),
  8653. expansions: {}
  8654. };
  8655. };
  8656. var collapseItem$1 = function (text) {
  8657. return {
  8658. value: generate$1(collapseItem()),
  8659. meta: { text: text }
  8660. };
  8661. };
  8662. var tieredMenu = single$2({
  8663. name: 'TieredMenu',
  8664. configFields: [
  8665. onStrictKeyboardHandler('onExecute'),
  8666. onStrictKeyboardHandler('onEscape'),
  8667. onStrictHandler('onOpenMenu'),
  8668. onStrictHandler('onOpenSubmenu'),
  8669. onHandler('onRepositionMenu'),
  8670. onHandler('onCollapseMenu'),
  8671. defaulted$1('highlightImmediately', true),
  8672. strictObjOf('data', [
  8673. strict$1('primary'),
  8674. strict$1('menus'),
  8675. strict$1('expansions')
  8676. ]),
  8677. defaulted$1('fakeFocus', false),
  8678. onHandler('onHighlight'),
  8679. onHandler('onHover'),
  8680. tieredMenuMarkers(),
  8681. strict$1('dom'),
  8682. defaulted$1('navigateOnHover', true),
  8683. defaulted$1('stayInDom', false),
  8684. field$1('tmenuBehaviours', [
  8685. Keying,
  8686. Highlighting,
  8687. Composing,
  8688. Replacing
  8689. ]),
  8690. defaulted$1('eventOrder', {})
  8691. ],
  8692. apis: {
  8693. collapseMenu: function (apis, tmenu) {
  8694. apis.collapseMenu(tmenu);
  8695. },
  8696. highlightPrimary: function (apis, tmenu) {
  8697. apis.highlightPrimary(tmenu);
  8698. },
  8699. repositionMenus: function (apis, tmenu) {
  8700. apis.repositionMenus(tmenu);
  8701. }
  8702. },
  8703. factory: make$3,
  8704. extraApis: {
  8705. tieredData: tieredData,
  8706. singleData: singleData,
  8707. collapseItem: collapseItem$1
  8708. }
  8709. });
  8710. var findRoute = function (component, transConfig, transState, route) {
  8711. return get(transConfig.routes, route.start).bind(function (sConfig) {
  8712. return get(sConfig, route.destination);
  8713. });
  8714. };
  8715. var getTransition = function (comp, transConfig, transState) {
  8716. var route = getCurrentRoute(comp, transConfig);
  8717. return route.bind(function (r) {
  8718. return getTransitionOf(comp, transConfig, transState, r);
  8719. });
  8720. };
  8721. var getTransitionOf = function (comp, transConfig, transState, route) {
  8722. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8723. return r.transition.map(function (t) {
  8724. return {
  8725. transition: t,
  8726. route: r
  8727. };
  8728. });
  8729. });
  8730. };
  8731. var disableTransition = function (comp, transConfig, transState) {
  8732. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8733. var t = routeTransition.transition;
  8734. remove$4(comp.element, t.transitionClass);
  8735. remove$1(comp.element, transConfig.destinationAttr);
  8736. });
  8737. };
  8738. var getNewRoute = function (comp, transConfig, transState, destination) {
  8739. return {
  8740. start: get$1(comp.element, transConfig.stateAttr),
  8741. destination: destination
  8742. };
  8743. };
  8744. var getCurrentRoute = function (comp, transConfig, _transState) {
  8745. var el = comp.element;
  8746. return getOpt(el, transConfig.destinationAttr).map(function (destination) {
  8747. return {
  8748. start: get$1(comp.element, transConfig.stateAttr),
  8749. destination: destination
  8750. };
  8751. });
  8752. };
  8753. var jumpTo = function (comp, transConfig, transState, destination) {
  8754. disableTransition(comp, transConfig, transState);
  8755. if (has$1(comp.element, transConfig.stateAttr) && get$1(comp.element, transConfig.stateAttr) !== destination) {
  8756. transConfig.onFinish(comp, destination);
  8757. }
  8758. set(comp.element, transConfig.stateAttr, destination);
  8759. };
  8760. var fasttrack = function (comp, transConfig, _transState, _destination) {
  8761. if (has$1(comp.element, transConfig.destinationAttr)) {
  8762. getOpt(comp.element, transConfig.destinationAttr).each(function (destination) {
  8763. set(comp.element, transConfig.stateAttr, destination);
  8764. });
  8765. remove$1(comp.element, transConfig.destinationAttr);
  8766. }
  8767. };
  8768. var progressTo = function (comp, transConfig, transState, destination) {
  8769. fasttrack(comp, transConfig);
  8770. var route = getNewRoute(comp, transConfig, transState, destination);
  8771. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8772. jumpTo(comp, transConfig, transState, destination);
  8773. }, function (routeTransition) {
  8774. disableTransition(comp, transConfig, transState);
  8775. var t = routeTransition.transition;
  8776. add$2(comp.element, t.transitionClass);
  8777. set(comp.element, transConfig.destinationAttr, destination);
  8778. });
  8779. };
  8780. var getState$1 = function (comp, transConfig, _transState) {
  8781. return getOpt(comp.element, transConfig.stateAttr);
  8782. };
  8783. var TransitionApis = /*#__PURE__*/Object.freeze({
  8784. __proto__: null,
  8785. findRoute: findRoute,
  8786. disableTransition: disableTransition,
  8787. getCurrentRoute: getCurrentRoute,
  8788. jumpTo: jumpTo,
  8789. progressTo: progressTo,
  8790. getState: getState$1
  8791. });
  8792. var events$9 = function (transConfig, transState) {
  8793. return derive([
  8794. run(transitionend(), function (component, simulatedEvent) {
  8795. var raw = simulatedEvent.event.raw;
  8796. getCurrentRoute(component, transConfig).each(function (route) {
  8797. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8798. rInfo.transition.each(function (rTransition) {
  8799. if (raw.propertyName === rTransition.property) {
  8800. jumpTo(component, transConfig, transState, route.destination);
  8801. transConfig.onTransition(component, route);
  8802. }
  8803. });
  8804. });
  8805. });
  8806. }),
  8807. runOnAttached(function (comp, _se) {
  8808. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8809. })
  8810. ]);
  8811. };
  8812. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8813. __proto__: null,
  8814. events: events$9
  8815. });
  8816. var TransitionSchema = [
  8817. defaulted$1('destinationAttr', 'data-transitioning-destination'),
  8818. defaulted$1('stateAttr', 'data-transitioning-state'),
  8819. strict$1('initialState'),
  8820. onHandler('onTransition'),
  8821. onHandler('onFinish'),
  8822. strictOf('routes', setOf$1(Result.value, setOf$1(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8823. strict$1('property'),
  8824. strict$1('transitionClass')
  8825. ])]))))
  8826. ];
  8827. var createRoutes = function (routes) {
  8828. var r = {};
  8829. each$1(routes, function (v, k) {
  8830. var waypoints = k.split('<->');
  8831. r[waypoints[0]] = wrap$1(waypoints[1], v);
  8832. r[waypoints[1]] = wrap$1(waypoints[0], v);
  8833. });
  8834. return r;
  8835. };
  8836. var createBistate = function (first, second, transitions) {
  8837. return wrapAll$1([
  8838. {
  8839. key: first,
  8840. value: wrap$1(second, transitions)
  8841. },
  8842. {
  8843. key: second,
  8844. value: wrap$1(first, transitions)
  8845. }
  8846. ]);
  8847. };
  8848. var createTristate = function (first, second, third, transitions) {
  8849. return wrapAll$1([
  8850. {
  8851. key: first,
  8852. value: wrapAll$1([
  8853. {
  8854. key: second,
  8855. value: transitions
  8856. },
  8857. {
  8858. key: third,
  8859. value: transitions
  8860. }
  8861. ])
  8862. },
  8863. {
  8864. key: second,
  8865. value: wrapAll$1([
  8866. {
  8867. key: first,
  8868. value: transitions
  8869. },
  8870. {
  8871. key: third,
  8872. value: transitions
  8873. }
  8874. ])
  8875. },
  8876. {
  8877. key: third,
  8878. value: wrapAll$1([
  8879. {
  8880. key: first,
  8881. value: transitions
  8882. },
  8883. {
  8884. key: second,
  8885. value: transitions
  8886. }
  8887. ])
  8888. }
  8889. ]);
  8890. };
  8891. var Transitioning = create$1({
  8892. fields: TransitionSchema,
  8893. name: 'transitioning',
  8894. active: ActiveTransitioning,
  8895. apis: TransitionApis,
  8896. extra: {
  8897. createRoutes: createRoutes,
  8898. createBistate: createBistate,
  8899. createTristate: createTristate
  8900. }
  8901. });
  8902. var scrollableStyle = resolve('scrollable');
  8903. var register = function (element) {
  8904. add$2(element, scrollableStyle);
  8905. };
  8906. var deregister = function (element) {
  8907. remove$4(element, scrollableStyle);
  8908. };
  8909. var scrollable = scrollableStyle;
  8910. var getValue$4 = function (item) {
  8911. return get(item, 'format').getOr(item.title);
  8912. };
  8913. var convert$1 = function (formats, memMenuThunk) {
  8914. var mainMenu = makeMenu('Styles', [].concat(map(formats.items, function (k) {
  8915. return makeItem(getValue$4(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue$4(k)));
  8916. })), memMenuThunk, false);
  8917. var submenus = map$1(formats.menus, function (menuItems, menuName) {
  8918. var items = map(menuItems, function (item) {
  8919. return makeItem(getValue$4(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue$4(item)));
  8920. });
  8921. return makeMenu(menuName, items, memMenuThunk, true);
  8922. });
  8923. var menus = deepMerge(submenus, wrap$1('styles', mainMenu));
  8924. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  8925. return { tmenu: tmenu };
  8926. };
  8927. var makeItem = function (value, text, selected, preview, isMenu) {
  8928. return {
  8929. data: {
  8930. value: value,
  8931. text: text
  8932. },
  8933. type: 'item',
  8934. dom: {
  8935. tag: 'div',
  8936. classes: isMenu ? [resolve('styles-item-is-menu')] : []
  8937. },
  8938. toggling: {
  8939. toggleOnExecute: false,
  8940. toggleClass: resolve('format-matches'),
  8941. selected: selected
  8942. },
  8943. itemBehaviours: derive$1(isMenu ? [] : [format(value, function (comp, status) {
  8944. var toggle = status ? Toggling.on : Toggling.off;
  8945. toggle(comp);
  8946. })]),
  8947. components: [{
  8948. dom: {
  8949. tag: 'div',
  8950. attributes: { style: preview },
  8951. innerHtml: text
  8952. }
  8953. }]
  8954. };
  8955. };
  8956. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  8957. return {
  8958. value: value,
  8959. dom: { tag: 'div' },
  8960. components: [
  8961. Button.sketch({
  8962. dom: {
  8963. tag: 'div',
  8964. classes: [resolve('styles-collapser')]
  8965. },
  8966. components: collapsable ? [
  8967. {
  8968. dom: {
  8969. tag: 'span',
  8970. classes: [resolve('styles-collapse-icon')]
  8971. }
  8972. },
  8973. text(value)
  8974. ] : [text(value)],
  8975. action: function (item) {
  8976. if (collapsable) {
  8977. var comp = memMenuThunk().get(item);
  8978. tieredMenu.collapseMenu(comp);
  8979. }
  8980. }
  8981. }),
  8982. {
  8983. dom: {
  8984. tag: 'div',
  8985. classes: [resolve('styles-menu-items-container')]
  8986. },
  8987. components: [Menu.parts.items({})],
  8988. behaviours: derive$1([config('adhoc-scrollable-menu', [
  8989. runOnAttached(function (component, _simulatedEvent) {
  8990. set$3(component.element, 'overflow-y', 'auto');
  8991. set$3(component.element, '-webkit-overflow-scrolling', 'touch');
  8992. register(component.element);
  8993. }),
  8994. runOnDetached(function (component) {
  8995. remove$5(component.element, 'overflow-y');
  8996. remove$5(component.element, '-webkit-overflow-scrolling');
  8997. deregister(component.element);
  8998. })
  8999. ])])
  9000. }
  9001. ],
  9002. items: items,
  9003. menuBehaviours: derive$1([Transitioning.config({
  9004. initialState: 'after',
  9005. routes: Transitioning.createTristate('before', 'current', 'after', {
  9006. transition: {
  9007. property: 'transform',
  9008. transitionClass: 'transitioning'
  9009. }
  9010. })
  9011. })])
  9012. };
  9013. };
  9014. var sketch$8 = function (settings) {
  9015. var dataset = convert$1(settings.formats, function () {
  9016. return memMenu;
  9017. });
  9018. var memMenu = record(tieredMenu.sketch({
  9019. dom: {
  9020. tag: 'div',
  9021. classes: [resolve('styles-menu')]
  9022. },
  9023. components: [],
  9024. fakeFocus: true,
  9025. stayInDom: true,
  9026. onExecute: function (_tmenu, item) {
  9027. var v = Representing.getValue(item);
  9028. settings.handle(item, v.value);
  9029. return Optional.none();
  9030. },
  9031. onEscape: function () {
  9032. return Optional.none();
  9033. },
  9034. onOpenMenu: function (container, menu) {
  9035. var w = get$7(container.element);
  9036. set$4(menu.element, w);
  9037. Transitioning.jumpTo(menu, 'current');
  9038. },
  9039. onOpenSubmenu: function (container, item, submenu) {
  9040. var w = get$7(container.element);
  9041. var menu = ancestor$2(item.element, '[role="menu"]').getOrDie('hacky');
  9042. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9043. set$4(submenu.element, w);
  9044. Transitioning.progressTo(menuComp, 'before');
  9045. Transitioning.jumpTo(submenu, 'after');
  9046. Transitioning.progressTo(submenu, 'current');
  9047. },
  9048. onCollapseMenu: function (container, item, menu) {
  9049. var submenu = ancestor$2(item.element, '[role="menu"]').getOrDie('hacky');
  9050. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9051. Transitioning.progressTo(submenuComp, 'after');
  9052. Transitioning.progressTo(menu, 'current');
  9053. },
  9054. navigateOnHover: false,
  9055. highlightImmediately: true,
  9056. data: dataset.tmenu,
  9057. markers: {
  9058. backgroundMenu: resolve('styles-background-menu'),
  9059. menu: resolve('styles-menu'),
  9060. selectedMenu: resolve('styles-selected-menu'),
  9061. item: resolve('styles-item'),
  9062. selectedItem: resolve('styles-selected-item')
  9063. }
  9064. }));
  9065. return memMenu.asSpec();
  9066. };
  9067. var getFromExpandingItem = function (item) {
  9068. var newItem = deepMerge(exclude$1(item, ['items']), { menu: true });
  9069. var rest = expand(item.items);
  9070. var newMenus = deepMerge(rest.menus, wrap$1(item.title, rest.items));
  9071. var newExpansions = deepMerge(rest.expansions, wrap$1(item.title, item.title));
  9072. return {
  9073. item: newItem,
  9074. menus: newMenus,
  9075. expansions: newExpansions
  9076. };
  9077. };
  9078. var getFromItem = function (item) {
  9079. return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : {
  9080. item: item,
  9081. menus: {},
  9082. expansions: {}
  9083. };
  9084. };
  9085. var expand = function (items) {
  9086. return foldr(items, function (acc, item) {
  9087. var newData = getFromItem(item);
  9088. return {
  9089. menus: deepMerge(acc.menus, newData.menus),
  9090. items: [newData.item].concat(acc.items),
  9091. expansions: deepMerge(acc.expansions, newData.expansions)
  9092. };
  9093. }, {
  9094. menus: {},
  9095. expansions: {},
  9096. items: []
  9097. });
  9098. };
  9099. var register$1 = function (editor) {
  9100. var isSelectedFor = function (format) {
  9101. return function () {
  9102. return editor.formatter.match(format);
  9103. };
  9104. };
  9105. var getPreview = function (format) {
  9106. return function () {
  9107. return editor.formatter.getCssText(format);
  9108. };
  9109. };
  9110. var enrichSupported = function (item) {
  9111. return deepMerge(item, {
  9112. isSelected: isSelectedFor(item.format),
  9113. getPreview: getPreview(item.format)
  9114. });
  9115. };
  9116. var enrichMenu = function (item) {
  9117. return deepMerge(item, {
  9118. isSelected: never,
  9119. getPreview: constant('')
  9120. });
  9121. };
  9122. var enrichCustom = function (item) {
  9123. var formatName = generate$1(item.title);
  9124. var newItem = deepMerge(item, {
  9125. format: formatName,
  9126. isSelected: isSelectedFor(formatName),
  9127. getPreview: getPreview(formatName)
  9128. });
  9129. editor.formatter.register(formatName, newItem);
  9130. return newItem;
  9131. };
  9132. var doEnrich = function (items) {
  9133. return map(items, function (item) {
  9134. if (hasNonNullableKey(item, 'items')) {
  9135. var newItems = doEnrich(item.items);
  9136. return deepMerge(enrichMenu(item), { items: newItems });
  9137. } else if (hasNonNullableKey(item, 'format')) {
  9138. return enrichSupported(item);
  9139. } else {
  9140. return enrichCustom(item);
  9141. }
  9142. });
  9143. };
  9144. return doEnrich(getStyleFormats(editor));
  9145. };
  9146. var prune = function (editor, formats) {
  9147. var doPrune = function (items) {
  9148. return bind(items, function (item) {
  9149. if (item.items !== undefined) {
  9150. var newItems = doPrune(item.items);
  9151. return newItems.length > 0 ? [item] : [];
  9152. } else {
  9153. var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9154. return keep ? [item] : [];
  9155. }
  9156. });
  9157. };
  9158. var prunedItems = doPrune(formats);
  9159. return expand(prunedItems);
  9160. };
  9161. var ui = function (editor, formats, onDone) {
  9162. var pruned = prune(editor, formats);
  9163. return sketch$8({
  9164. formats: pruned,
  9165. handle: function (item, value) {
  9166. editor.undoManager.transact(function () {
  9167. if (Toggling.isOn(item)) {
  9168. editor.formatter.remove(value);
  9169. } else {
  9170. editor.formatter.apply(value);
  9171. }
  9172. });
  9173. onDone();
  9174. }
  9175. });
  9176. };
  9177. var extract$1 = function (rawToolbar) {
  9178. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9179. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9180. };
  9181. var identifyFromArray = function (toolbar) {
  9182. return bind(toolbar, function (item) {
  9183. return isArray(item) ? identifyFromArray(item) : extract$1(item);
  9184. });
  9185. };
  9186. var identify = function (editor) {
  9187. var toolbar = getToolbar(editor);
  9188. return isArray(toolbar) ? identifyFromArray(toolbar) : extract$1(toolbar);
  9189. };
  9190. var setup = function (realm, editor) {
  9191. var commandSketch = function (name) {
  9192. return function () {
  9193. return forToolbarCommand(editor, name);
  9194. };
  9195. };
  9196. var stateCommandSketch = function (name) {
  9197. return function () {
  9198. return forToolbarStateCommand(editor, name);
  9199. };
  9200. };
  9201. var actionSketch = function (name, query, action) {
  9202. return function () {
  9203. return forToolbarStateAction(editor, name, query, action);
  9204. };
  9205. };
  9206. var undo = commandSketch('undo');
  9207. var redo = commandSketch('redo');
  9208. var bold = stateCommandSketch('bold');
  9209. var italic = stateCommandSketch('italic');
  9210. var underline = stateCommandSketch('underline');
  9211. var removeformat = commandSketch('removeformat');
  9212. var link = function () {
  9213. return sketch$7(realm, editor);
  9214. };
  9215. var unlink = actionSketch('unlink', 'link', function () {
  9216. editor.execCommand('unlink', null, false);
  9217. });
  9218. var image = function () {
  9219. return sketch$4(editor);
  9220. };
  9221. var bullist = actionSketch('unordered-list', 'ul', function () {
  9222. editor.execCommand('InsertUnorderedList', null, false);
  9223. });
  9224. var numlist = actionSketch('ordered-list', 'ol', function () {
  9225. editor.execCommand('InsertOrderedList', null, false);
  9226. });
  9227. var fontsizeselect = function () {
  9228. return sketch$3(realm, editor);
  9229. };
  9230. var forecolor = function () {
  9231. return sketch$1(realm, editor);
  9232. };
  9233. var styleFormats = register$1(editor);
  9234. var styleFormatsMenu = function () {
  9235. return ui(editor, styleFormats, function () {
  9236. editor.fire('scrollIntoView');
  9237. });
  9238. };
  9239. var styleselect = function () {
  9240. return forToolbar('style-formats', function (button) {
  9241. editor.fire('toReading');
  9242. realm.dropup.appear(styleFormatsMenu, Toggling.on, button);
  9243. }, derive$1([
  9244. Toggling.config({
  9245. toggleClass: resolve('toolbar-button-selected'),
  9246. toggleOnExecute: false,
  9247. aria: { mode: 'pressed' }
  9248. }),
  9249. Receiving.config({
  9250. channels: wrapAll$1([
  9251. receive$1(orientationChanged, Toggling.off),
  9252. receive$1(dropupDismissed, Toggling.off)
  9253. ])
  9254. })
  9255. ]), editor);
  9256. };
  9257. var feature = function (prereq, sketch) {
  9258. return {
  9259. isSupported: function () {
  9260. var buttons = editor.ui.registry.getAll().buttons;
  9261. return prereq.forall(function (p) {
  9262. return hasNonNullableKey(buttons, p);
  9263. });
  9264. },
  9265. sketch: sketch
  9266. };
  9267. };
  9268. return {
  9269. undo: feature(Optional.none(), undo),
  9270. redo: feature(Optional.none(), redo),
  9271. bold: feature(Optional.none(), bold),
  9272. italic: feature(Optional.none(), italic),
  9273. underline: feature(Optional.none(), underline),
  9274. removeformat: feature(Optional.none(), removeformat),
  9275. link: feature(Optional.none(), link),
  9276. unlink: feature(Optional.none(), unlink),
  9277. image: feature(Optional.none(), image),
  9278. bullist: feature(Optional.some('bullist'), bullist),
  9279. numlist: feature(Optional.some('numlist'), numlist),
  9280. fontsizeselect: feature(Optional.none(), fontsizeselect),
  9281. forecolor: feature(Optional.none(), forecolor),
  9282. styleselect: feature(Optional.none(), styleselect)
  9283. };
  9284. };
  9285. var detect$4 = function (editor, features) {
  9286. var itemNames = identify(editor);
  9287. var present = {};
  9288. return bind(itemNames, function (iName) {
  9289. var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9290. present[iName] = true;
  9291. return r;
  9292. });
  9293. };
  9294. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9295. return {
  9296. target: target,
  9297. x: x,
  9298. y: y,
  9299. stop: stop,
  9300. prevent: prevent,
  9301. kill: kill,
  9302. raw: raw
  9303. };
  9304. };
  9305. var fromRawEvent = function (rawEvent) {
  9306. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  9307. var stop = function () {
  9308. return rawEvent.stopPropagation();
  9309. };
  9310. var prevent = function () {
  9311. return rawEvent.preventDefault();
  9312. };
  9313. var kill = compose(prevent, stop);
  9314. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9315. };
  9316. var handle = function (filter, handler) {
  9317. return function (rawEvent) {
  9318. if (filter(rawEvent)) {
  9319. handler(fromRawEvent(rawEvent));
  9320. }
  9321. };
  9322. };
  9323. var binder = function (element, event, filter, handler, useCapture) {
  9324. var wrapped = handle(filter, handler);
  9325. element.dom.addEventListener(event, wrapped, useCapture);
  9326. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9327. };
  9328. var bind$2 = function (element, event, filter, handler) {
  9329. return binder(element, event, filter, handler, false);
  9330. };
  9331. var capture = function (element, event, filter, handler) {
  9332. return binder(element, event, filter, handler, true);
  9333. };
  9334. var unbind = function (element, event, handler, useCapture) {
  9335. element.dom.removeEventListener(event, handler, useCapture);
  9336. };
  9337. var filter$2 = always;
  9338. var bind$3 = function (element, event, handler) {
  9339. return bind$2(element, event, filter$2, handler);
  9340. };
  9341. var capture$1 = function (element, event, handler) {
  9342. return capture(element, event, filter$2, handler);
  9343. };
  9344. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9345. var INTERVAL = 50;
  9346. var INSURANCE = 1000 / INTERVAL;
  9347. var get$b = function (outerWindow) {
  9348. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9349. return { isPortrait: constant(isPortrait) };
  9350. };
  9351. var getActualWidth = function (outerWindow) {
  9352. var isIos = detect$3().os.isiOS();
  9353. var isPortrait = get$b(outerWindow).isPortrait();
  9354. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9355. };
  9356. var onChange = function (outerWindow, listeners) {
  9357. var win = SugarElement.fromDom(outerWindow);
  9358. var poller = null;
  9359. var change = function () {
  9360. global$4.clearInterval(poller);
  9361. var orientation = get$b(outerWindow);
  9362. listeners.onChange(orientation);
  9363. onAdjustment(function () {
  9364. listeners.onReady(orientation);
  9365. });
  9366. };
  9367. var orientationHandle = bind$3(win, 'orientationchange', change);
  9368. var onAdjustment = function (f) {
  9369. global$4.clearInterval(poller);
  9370. var flag = outerWindow.innerHeight;
  9371. var insurance = 0;
  9372. poller = global$4.setInterval(function () {
  9373. if (flag !== outerWindow.innerHeight) {
  9374. global$4.clearInterval(poller);
  9375. f(Optional.some(outerWindow.innerHeight));
  9376. } else if (insurance > INSURANCE) {
  9377. global$4.clearInterval(poller);
  9378. f(Optional.none());
  9379. }
  9380. insurance++;
  9381. }, INTERVAL);
  9382. };
  9383. var destroy = function () {
  9384. orientationHandle.unbind();
  9385. };
  9386. return {
  9387. onAdjustment: onAdjustment,
  9388. destroy: destroy
  9389. };
  9390. };
  9391. var setStart = function (rng, situ) {
  9392. situ.fold(function (e) {
  9393. rng.setStartBefore(e.dom);
  9394. }, function (e, o) {
  9395. rng.setStart(e.dom, o);
  9396. }, function (e) {
  9397. rng.setStartAfter(e.dom);
  9398. });
  9399. };
  9400. var setFinish = function (rng, situ) {
  9401. situ.fold(function (e) {
  9402. rng.setEndBefore(e.dom);
  9403. }, function (e, o) {
  9404. rng.setEnd(e.dom, o);
  9405. }, function (e) {
  9406. rng.setEndAfter(e.dom);
  9407. });
  9408. };
  9409. var relativeToNative = function (win, startSitu, finishSitu) {
  9410. var range = win.document.createRange();
  9411. setStart(range, startSitu);
  9412. setFinish(range, finishSitu);
  9413. return range;
  9414. };
  9415. var exactToNative = function (win, start, soffset, finish, foffset) {
  9416. var rng = win.document.createRange();
  9417. rng.setStart(start.dom, soffset);
  9418. rng.setEnd(finish.dom, foffset);
  9419. return rng;
  9420. };
  9421. var toRect = function (rect) {
  9422. return {
  9423. left: rect.left,
  9424. top: rect.top,
  9425. right: rect.right,
  9426. bottom: rect.bottom,
  9427. width: rect.width,
  9428. height: rect.height
  9429. };
  9430. };
  9431. var getFirstRect = function (rng) {
  9432. var rects = rng.getClientRects();
  9433. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9434. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  9435. };
  9436. var adt$4 = Adt.generate([
  9437. {
  9438. ltr: [
  9439. 'start',
  9440. 'soffset',
  9441. 'finish',
  9442. 'foffset'
  9443. ]
  9444. },
  9445. {
  9446. rtl: [
  9447. 'start',
  9448. 'soffset',
  9449. 'finish',
  9450. 'foffset'
  9451. ]
  9452. }
  9453. ]);
  9454. var fromRange = function (win, type, range) {
  9455. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  9456. };
  9457. var getRanges = function (win, selection) {
  9458. return selection.match({
  9459. domRange: function (rng) {
  9460. return {
  9461. ltr: constant(rng),
  9462. rtl: Optional.none
  9463. };
  9464. },
  9465. relative: function (startSitu, finishSitu) {
  9466. return {
  9467. ltr: cached(function () {
  9468. return relativeToNative(win, startSitu, finishSitu);
  9469. }),
  9470. rtl: cached(function () {
  9471. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  9472. })
  9473. };
  9474. },
  9475. exact: function (start, soffset, finish, foffset) {
  9476. return {
  9477. ltr: cached(function () {
  9478. return exactToNative(win, start, soffset, finish, foffset);
  9479. }),
  9480. rtl: cached(function () {
  9481. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  9482. })
  9483. };
  9484. }
  9485. });
  9486. };
  9487. var doDiagnose = function (win, ranges) {
  9488. var rng = ranges.ltr();
  9489. if (rng.collapsed) {
  9490. var reversed = ranges.rtl().filter(function (rev) {
  9491. return rev.collapsed === false;
  9492. });
  9493. return reversed.map(function (rev) {
  9494. return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  9495. }).getOrThunk(function () {
  9496. return fromRange(win, adt$4.ltr, rng);
  9497. });
  9498. } else {
  9499. return fromRange(win, adt$4.ltr, rng);
  9500. }
  9501. };
  9502. var diagnose = function (win, selection) {
  9503. var ranges = getRanges(win, selection);
  9504. return doDiagnose(win, ranges);
  9505. };
  9506. var asLtrRange = function (win, selection) {
  9507. var diagnosis = diagnose(win, selection);
  9508. return diagnosis.match({
  9509. ltr: function (start, soffset, finish, foffset) {
  9510. var rng = win.document.createRange();
  9511. rng.setStart(start.dom, soffset);
  9512. rng.setEnd(finish.dom, foffset);
  9513. return rng;
  9514. },
  9515. rtl: function (start, soffset, finish, foffset) {
  9516. var rng = win.document.createRange();
  9517. rng.setStart(finish.dom, foffset);
  9518. rng.setEnd(start.dom, soffset);
  9519. return rng;
  9520. }
  9521. });
  9522. };
  9523. var ltr = adt$4.ltr;
  9524. var rtl = adt$4.rtl;
  9525. var create$3 = function (start, soffset, finish, foffset) {
  9526. return {
  9527. start: start,
  9528. soffset: soffset,
  9529. finish: finish,
  9530. foffset: foffset
  9531. };
  9532. };
  9533. var SimRange = { create: create$3 };
  9534. function NodeValue (is, name) {
  9535. var get = function (element) {
  9536. if (!is(element)) {
  9537. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9538. }
  9539. return getOption(element).getOr('');
  9540. };
  9541. var getOption = function (element) {
  9542. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  9543. };
  9544. var set = function (element, value) {
  9545. if (!is(element)) {
  9546. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9547. }
  9548. element.dom.nodeValue = value;
  9549. };
  9550. return {
  9551. get: get,
  9552. getOption: getOption,
  9553. set: set
  9554. };
  9555. }
  9556. var api$3 = NodeValue(isText, 'text');
  9557. var getOption = function (element) {
  9558. return api$3.getOption(element);
  9559. };
  9560. var getEnd = function (element) {
  9561. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  9562. return children(element).length;
  9563. }, function (v) {
  9564. return v.length;
  9565. });
  9566. };
  9567. var adt$5 = Adt.generate([
  9568. { before: ['element'] },
  9569. {
  9570. on: [
  9571. 'element',
  9572. 'offset'
  9573. ]
  9574. },
  9575. { after: ['element'] }
  9576. ]);
  9577. var cata = function (subject, onBefore, onOn, onAfter) {
  9578. return subject.fold(onBefore, onOn, onAfter);
  9579. };
  9580. var getStart = function (situ) {
  9581. return situ.fold(identity, identity, identity);
  9582. };
  9583. var before$1 = adt$5.before;
  9584. var on$1 = adt$5.on;
  9585. var after$1 = adt$5.after;
  9586. var Situ = {
  9587. before: before$1,
  9588. on: on$1,
  9589. after: after$1,
  9590. cata: cata,
  9591. getStart: getStart
  9592. };
  9593. var adt$6 = Adt.generate([
  9594. { domRange: ['rng'] },
  9595. {
  9596. relative: [
  9597. 'startSitu',
  9598. 'finishSitu'
  9599. ]
  9600. },
  9601. {
  9602. exact: [
  9603. 'start',
  9604. 'soffset',
  9605. 'finish',
  9606. 'foffset'
  9607. ]
  9608. }
  9609. ]);
  9610. var exactFromRange = function (simRange) {
  9611. return adt$6.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9612. };
  9613. var getStart$1 = function (selection) {
  9614. return selection.match({
  9615. domRange: function (rng) {
  9616. return SugarElement.fromDom(rng.startContainer);
  9617. },
  9618. relative: function (startSitu, _finishSitu) {
  9619. return Situ.getStart(startSitu);
  9620. },
  9621. exact: function (start, _soffset, _finish, _foffset) {
  9622. return start;
  9623. }
  9624. });
  9625. };
  9626. var domRange = adt$6.domRange;
  9627. var relative = adt$6.relative;
  9628. var exact = adt$6.exact;
  9629. var getWin = function (selection) {
  9630. var start = getStart$1(selection);
  9631. return defaultView(start);
  9632. };
  9633. var range$1 = SimRange.create;
  9634. var SimSelection = {
  9635. domRange: domRange,
  9636. relative: relative,
  9637. exact: exact,
  9638. exactFromRange: exactFromRange,
  9639. getWin: getWin,
  9640. range: range$1
  9641. };
  9642. var beforeSpecial = function (element, offset) {
  9643. var name$1 = name(element);
  9644. if ('input' === name$1) {
  9645. return Situ.after(element);
  9646. } else if (!contains([
  9647. 'br',
  9648. 'img'
  9649. ], name$1)) {
  9650. return Situ.on(element, offset);
  9651. } else {
  9652. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9653. }
  9654. };
  9655. var preprocessExact = function (start, soffset, finish, foffset) {
  9656. var startSitu = beforeSpecial(start, soffset);
  9657. var finishSitu = beforeSpecial(finish, foffset);
  9658. return SimSelection.relative(startSitu, finishSitu);
  9659. };
  9660. var makeRange = function (start, soffset, finish, foffset) {
  9661. var doc = owner(start);
  9662. var rng = doc.dom.createRange();
  9663. rng.setStart(start.dom, soffset);
  9664. rng.setEnd(finish.dom, foffset);
  9665. return rng;
  9666. };
  9667. var after$2 = function (start, soffset, finish, foffset) {
  9668. var r = makeRange(start, soffset, finish, foffset);
  9669. var same = eq(start, finish) && soffset === foffset;
  9670. return r.collapsed && !same;
  9671. };
  9672. var getNativeSelection = function (win) {
  9673. return Optional.from(win.getSelection());
  9674. };
  9675. var doSetNativeRange = function (win, rng) {
  9676. getNativeSelection(win).each(function (selection) {
  9677. selection.removeAllRanges();
  9678. selection.addRange(rng);
  9679. });
  9680. };
  9681. var doSetRange = function (win, start, soffset, finish, foffset) {
  9682. var rng = exactToNative(win, start, soffset, finish, foffset);
  9683. doSetNativeRange(win, rng);
  9684. };
  9685. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9686. selection.collapse(start.dom, soffset);
  9687. selection.extend(finish.dom, foffset);
  9688. };
  9689. var setRangeFromRelative = function (win, relative) {
  9690. return diagnose(win, relative).match({
  9691. ltr: function (start, soffset, finish, foffset) {
  9692. doSetRange(win, start, soffset, finish, foffset);
  9693. },
  9694. rtl: function (start, soffset, finish, foffset) {
  9695. getNativeSelection(win).each(function (selection) {
  9696. if (selection.setBaseAndExtent) {
  9697. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9698. } else if (selection.extend) {
  9699. try {
  9700. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9701. } catch (e) {
  9702. doSetRange(win, finish, foffset, start, soffset);
  9703. }
  9704. } else {
  9705. doSetRange(win, finish, foffset, start, soffset);
  9706. }
  9707. });
  9708. }
  9709. });
  9710. };
  9711. var setExact = function (win, start, soffset, finish, foffset) {
  9712. var relative = preprocessExact(start, soffset, finish, foffset);
  9713. setRangeFromRelative(win, relative);
  9714. };
  9715. var readRange = function (selection) {
  9716. if (selection.rangeCount > 0) {
  9717. var firstRng = selection.getRangeAt(0);
  9718. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9719. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9720. } else {
  9721. return Optional.none();
  9722. }
  9723. };
  9724. var doGetExact = function (selection) {
  9725. if (selection.anchorNode === null || selection.focusNode === null) {
  9726. return readRange(selection);
  9727. } else {
  9728. var anchor = SugarElement.fromDom(selection.anchorNode);
  9729. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9730. return after$2(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9731. }
  9732. };
  9733. var getExact = function (win) {
  9734. return getNativeSelection(win).filter(function (sel) {
  9735. return sel.rangeCount > 0;
  9736. }).bind(doGetExact);
  9737. };
  9738. var get$c = function (win) {
  9739. return getExact(win).map(function (range) {
  9740. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9741. });
  9742. };
  9743. var getFirstRect$1 = function (win, selection) {
  9744. var rng = asLtrRange(win, selection);
  9745. return getFirstRect(rng);
  9746. };
  9747. var clear$1 = function (win) {
  9748. getNativeSelection(win).each(function (selection) {
  9749. return selection.removeAllRanges();
  9750. });
  9751. };
  9752. var getBodyFromFrame = function (frame) {
  9753. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document.body));
  9754. };
  9755. var getDocFromFrame = function (frame) {
  9756. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document));
  9757. };
  9758. var getWinFromFrame = function (frame) {
  9759. return Optional.from(frame.dom.contentWindow);
  9760. };
  9761. var getSelectionFromFrame = function (frame) {
  9762. var optWin = getWinFromFrame(frame);
  9763. return optWin.bind(getExact);
  9764. };
  9765. var getFrame = function (editor) {
  9766. return editor.getFrame();
  9767. };
  9768. var getOrDerive = function (name, f) {
  9769. return function (editor) {
  9770. var g = editor[name].getOrThunk(function () {
  9771. var frame = getFrame(editor);
  9772. return function () {
  9773. return f(frame);
  9774. };
  9775. });
  9776. return g();
  9777. };
  9778. };
  9779. var getOrListen = function (editor, doc, name, type) {
  9780. return editor[name].getOrThunk(function () {
  9781. return function (handler) {
  9782. return bind$3(doc, type, handler);
  9783. };
  9784. });
  9785. };
  9786. var getActiveApi = function (editor) {
  9787. var frame = getFrame(editor);
  9788. var tryFallbackBox = function (win) {
  9789. var isCollapsed = function (sel) {
  9790. return eq(sel.start, sel.finish) && sel.soffset === sel.foffset;
  9791. };
  9792. var toStartRect = function (sel) {
  9793. var rect = sel.start.dom.getBoundingClientRect();
  9794. return rect.width > 0 || rect.height > 0 ? Optional.some(rect) : Optional.none();
  9795. };
  9796. return getExact(win).filter(isCollapsed).bind(toStartRect);
  9797. };
  9798. return getBodyFromFrame(frame).bind(function (body) {
  9799. return getDocFromFrame(frame).bind(function (doc) {
  9800. return getWinFromFrame(frame).map(function (win) {
  9801. var html = SugarElement.fromDom(doc.dom.documentElement);
  9802. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  9803. return function () {
  9804. return get$c(win).bind(function (sel) {
  9805. return getFirstRect$1(win, sel).orThunk(function () {
  9806. return tryFallbackBox(win);
  9807. });
  9808. });
  9809. };
  9810. });
  9811. var setSelection = editor.setSelection.getOrThunk(function () {
  9812. return function (start, soffset, finish, foffset) {
  9813. setExact(win, start, soffset, finish, foffset);
  9814. };
  9815. });
  9816. var clearSelection = editor.clearSelection.getOrThunk(function () {
  9817. return function () {
  9818. clear$1(win);
  9819. };
  9820. });
  9821. return {
  9822. body: body,
  9823. doc: doc,
  9824. win: win,
  9825. html: html,
  9826. getSelection: curry(getSelectionFromFrame, frame),
  9827. setSelection: setSelection,
  9828. clearSelection: clearSelection,
  9829. frame: frame,
  9830. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  9831. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  9832. onDomChanged: editor.onDomChanged,
  9833. onScrollToCursor: editor.onScrollToCursor,
  9834. onScrollToElement: editor.onScrollToElement,
  9835. onToReading: editor.onToReading,
  9836. onToEditing: editor.onToEditing,
  9837. onToolbarScrollStart: editor.onToolbarScrollStart,
  9838. onTouchContent: editor.onTouchContent,
  9839. onTapContent: editor.onTapContent,
  9840. onTouchToolstrip: editor.onTouchToolstrip,
  9841. getCursorBox: getCursorBox
  9842. };
  9843. });
  9844. });
  9845. });
  9846. };
  9847. var getWin$1 = getOrDerive('getWin', getWinFromFrame);
  9848. var tag = function () {
  9849. var head = first('head').getOrDie();
  9850. var nu = function () {
  9851. var meta = SugarElement.fromTag('meta');
  9852. set(meta, 'name', 'viewport');
  9853. append(head, meta);
  9854. return meta;
  9855. };
  9856. var element = first('meta[name="viewport"]').getOrThunk(nu);
  9857. var backup = get$1(element, 'content');
  9858. var maximize = function () {
  9859. set(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  9860. };
  9861. var restore = function () {
  9862. if (backup !== undefined && backup !== null && backup.length > 0) {
  9863. set(element, 'content', backup);
  9864. } else {
  9865. set(element, 'content', 'user-scalable=yes');
  9866. }
  9867. };
  9868. return {
  9869. maximize: maximize,
  9870. restore: restore
  9871. };
  9872. };
  9873. var attr = 'data-ephox-mobile-fullscreen-style';
  9874. var siblingStyles = 'display:none!important;';
  9875. var ancestorPosition = 'position:absolute!important;';
  9876. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  9877. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  9878. var isAndroid = detect$3().os.isAndroid();
  9879. var matchColor = function (editorBody) {
  9880. var color = get$4(editorBody, 'background-color');
  9881. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  9882. };
  9883. var clobberStyles = function (container, editorBody) {
  9884. var gatherSiblings = function (element) {
  9885. return siblings$2(element, '*');
  9886. };
  9887. var clobber = function (clobberStyle) {
  9888. return function (element) {
  9889. var styles = get$1(element, 'style');
  9890. var backup = styles === undefined ? 'no-styles' : styles.trim();
  9891. if (backup === clobberStyle) {
  9892. return;
  9893. } else {
  9894. set(element, attr, backup);
  9895. set(element, 'style', clobberStyle);
  9896. }
  9897. };
  9898. };
  9899. var ancestors = ancestors$1(container, '*');
  9900. var siblings = bind(ancestors, gatherSiblings);
  9901. var bgColor = matchColor(editorBody);
  9902. each(siblings, clobber(siblingStyles));
  9903. each(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor));
  9904. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  9905. clobber(containerStyles + ancestorStyles + bgColor)(container);
  9906. };
  9907. var restoreStyles = function () {
  9908. var clobberedEls = all$2('[' + attr + ']');
  9909. each(clobberedEls, function (element) {
  9910. var restore = get$1(element, attr);
  9911. if (restore !== 'no-styles') {
  9912. set(element, 'style', restore);
  9913. } else {
  9914. remove$1(element, 'style');
  9915. }
  9916. remove$1(element, attr);
  9917. });
  9918. };
  9919. function DelayedFunction (fun, delay) {
  9920. var ref = null;
  9921. var schedule = function () {
  9922. var args = [];
  9923. for (var _i = 0; _i < arguments.length; _i++) {
  9924. args[_i] = arguments[_i];
  9925. }
  9926. ref = setTimeout(function () {
  9927. fun.apply(null, args);
  9928. ref = null;
  9929. }, delay);
  9930. };
  9931. var cancel = function () {
  9932. if (ref !== null) {
  9933. clearTimeout(ref);
  9934. ref = null;
  9935. }
  9936. };
  9937. return {
  9938. cancel: cancel,
  9939. schedule: schedule
  9940. };
  9941. }
  9942. var SIGNIFICANT_MOVE = 5;
  9943. var LONGPRESS_DELAY = 400;
  9944. var getTouch = function (event) {
  9945. var raw = event.raw;
  9946. if (raw.touches === undefined || raw.touches.length !== 1) {
  9947. return Optional.none();
  9948. }
  9949. return Optional.some(raw.touches[0]);
  9950. };
  9951. var isFarEnough = function (touch, data) {
  9952. var distX = Math.abs(touch.clientX - data.x);
  9953. var distY = Math.abs(touch.clientY - data.y);
  9954. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  9955. };
  9956. var monitor = function (settings) {
  9957. var startData = Cell(Optional.none());
  9958. var longpressFired = Cell(false);
  9959. var longpress$1 = DelayedFunction(function (event) {
  9960. settings.triggerEvent(longpress(), event);
  9961. longpressFired.set(true);
  9962. }, LONGPRESS_DELAY);
  9963. var handleTouchstart = function (event) {
  9964. getTouch(event).each(function (touch) {
  9965. longpress$1.cancel();
  9966. var data = {
  9967. x: touch.clientX,
  9968. y: touch.clientY,
  9969. target: event.target
  9970. };
  9971. longpress$1.schedule(event);
  9972. longpressFired.set(false);
  9973. startData.set(Optional.some(data));
  9974. });
  9975. return Optional.none();
  9976. };
  9977. var handleTouchmove = function (event) {
  9978. longpress$1.cancel();
  9979. getTouch(event).each(function (touch) {
  9980. startData.get().each(function (data) {
  9981. if (isFarEnough(touch, data)) {
  9982. startData.set(Optional.none());
  9983. }
  9984. });
  9985. });
  9986. return Optional.none();
  9987. };
  9988. var handleTouchend = function (event) {
  9989. longpress$1.cancel();
  9990. var isSame = function (data) {
  9991. return eq(data.target, event.target);
  9992. };
  9993. return startData.get().filter(isSame).map(function (_data) {
  9994. if (longpressFired.get()) {
  9995. event.prevent();
  9996. return false;
  9997. } else {
  9998. return settings.triggerEvent(tap(), event);
  9999. }
  10000. });
  10001. };
  10002. var handlers = wrapAll$1([
  10003. {
  10004. key: touchstart(),
  10005. value: handleTouchstart
  10006. },
  10007. {
  10008. key: touchmove(),
  10009. value: handleTouchmove
  10010. },
  10011. {
  10012. key: touchend(),
  10013. value: handleTouchend
  10014. }
  10015. ]);
  10016. var fireIfReady = function (event, type) {
  10017. return get(handlers, type).bind(function (handler) {
  10018. return handler(event);
  10019. });
  10020. };
  10021. return { fireIfReady: fireIfReady };
  10022. };
  10023. var monitor$1 = function (editorApi) {
  10024. var tapEvent = monitor({
  10025. triggerEvent: function (type, evt) {
  10026. editorApi.onTapContent(evt);
  10027. }
  10028. });
  10029. var onTouchend = function () {
  10030. return bind$3(editorApi.body, 'touchend', function (evt) {
  10031. tapEvent.fireIfReady(evt, 'touchend');
  10032. });
  10033. };
  10034. var onTouchmove = function () {
  10035. return bind$3(editorApi.body, 'touchmove', function (evt) {
  10036. tapEvent.fireIfReady(evt, 'touchmove');
  10037. });
  10038. };
  10039. var fireTouchstart = function (evt) {
  10040. tapEvent.fireIfReady(evt, 'touchstart');
  10041. };
  10042. return {
  10043. fireTouchstart: fireTouchstart,
  10044. onTouchend: onTouchend,
  10045. onTouchmove: onTouchmove
  10046. };
  10047. };
  10048. var isAndroid6 = detect$3().os.version.major >= 6;
  10049. var initEvents = function (editorApi, toolstrip, alloy) {
  10050. var tapping = monitor$1(editorApi);
  10051. var outerDoc = owner(toolstrip);
  10052. var isRanged = function (sel) {
  10053. return !eq(sel.start, sel.finish) || sel.soffset !== sel.foffset;
  10054. };
  10055. var hasRangeInUi = function () {
  10056. return active(outerDoc).filter(function (input) {
  10057. return name(input) === 'input';
  10058. }).exists(function (input) {
  10059. return input.dom.selectionStart !== input.dom.selectionEnd;
  10060. });
  10061. };
  10062. var updateMargin = function () {
  10063. var rangeInContent = editorApi.doc.dom.hasFocus() && editorApi.getSelection().exists(isRanged);
  10064. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  10065. };
  10066. var listeners = [
  10067. bind$3(editorApi.body, 'touchstart', function (evt) {
  10068. editorApi.onTouchContent();
  10069. tapping.fireTouchstart(evt);
  10070. }),
  10071. tapping.onTouchmove(),
  10072. tapping.onTouchend(),
  10073. bind$3(toolstrip, 'touchstart', function (_evt) {
  10074. editorApi.onTouchToolstrip();
  10075. }),
  10076. editorApi.onToReading(function () {
  10077. blur(editorApi.body);
  10078. }),
  10079. editorApi.onToEditing(noop),
  10080. editorApi.onScrollToCursor(function (tinyEvent) {
  10081. tinyEvent.preventDefault();
  10082. editorApi.getCursorBox().each(function (bounds) {
  10083. var cWin = editorApi.win;
  10084. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10085. var cScrollBy = isOutside ? bounds.bottom - cWin.innerHeight + 50 : 0;
  10086. if (cScrollBy !== 0) {
  10087. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10088. }
  10089. });
  10090. })
  10091. ].concat(isAndroid6 === true ? [] : [
  10092. bind$3(SugarElement.fromDom(editorApi.win), 'blur', function () {
  10093. alloy.getByDom(toolstrip).each(Toggling.off);
  10094. }),
  10095. bind$3(outerDoc, 'select', updateMargin),
  10096. bind$3(editorApi.doc, 'selectionchange', updateMargin)
  10097. ]);
  10098. var destroy = function () {
  10099. each(listeners, function (l) {
  10100. l.unbind();
  10101. });
  10102. };
  10103. return { destroy: destroy };
  10104. };
  10105. var safeParse = function (element, attribute) {
  10106. var parsed = parseInt(get$1(element, attribute), 10);
  10107. return isNaN(parsed) ? 0 : parsed;
  10108. };
  10109. var COLLAPSED_WIDTH = 2;
  10110. var collapsedRect = function (rect) {
  10111. return __assign(__assign({}, rect), { width: COLLAPSED_WIDTH });
  10112. };
  10113. var toRect$1 = function (rawRect) {
  10114. return {
  10115. left: rawRect.left,
  10116. top: rawRect.top,
  10117. right: rawRect.right,
  10118. bottom: rawRect.bottom,
  10119. width: rawRect.width,
  10120. height: rawRect.height
  10121. };
  10122. };
  10123. var getRectsFromRange = function (range) {
  10124. if (!range.collapsed) {
  10125. return map(range.getClientRects(), toRect$1);
  10126. } else {
  10127. var start_1 = SugarElement.fromDom(range.startContainer);
  10128. return parent(start_1).bind(function (parent) {
  10129. var selection = SimSelection.exact(start_1, range.startOffset, parent, getEnd(parent));
  10130. var optRect = getFirstRect$1(range.startContainer.ownerDocument.defaultView, selection);
  10131. return optRect.map(collapsedRect).map(pure);
  10132. }).getOr([]);
  10133. }
  10134. };
  10135. var getRectangles = function (cWin) {
  10136. var sel = cWin.getSelection();
  10137. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  10138. };
  10139. var autocompleteHack = function () {
  10140. return function (f) {
  10141. global$4.setTimeout(function () {
  10142. f();
  10143. }, 0);
  10144. };
  10145. };
  10146. var resume = function (cWin) {
  10147. cWin.focus();
  10148. var iBody = SugarElement.fromDom(cWin.document.body);
  10149. var inInput = active().exists(function (elem) {
  10150. return contains([
  10151. 'input',
  10152. 'textarea'
  10153. ], name(elem));
  10154. });
  10155. var transaction = inInput ? autocompleteHack() : apply;
  10156. transaction(function () {
  10157. active().each(blur);
  10158. focus$1(iBody);
  10159. });
  10160. };
  10161. var EXTRA_SPACING = 50;
  10162. var data = 'data-' + resolve('last-outer-height');
  10163. var setLastHeight = function (cBody, value) {
  10164. set(cBody, data, value);
  10165. };
  10166. var getLastHeight = function (cBody) {
  10167. return safeParse(cBody, data);
  10168. };
  10169. var getBoundsFrom = function (rect) {
  10170. return {
  10171. top: rect.top,
  10172. bottom: rect.top + rect.height
  10173. };
  10174. };
  10175. var getBounds$1 = function (cWin) {
  10176. var rects = getRectangles(cWin);
  10177. return rects.length > 0 ? Optional.some(rects[0]).map(getBoundsFrom) : Optional.none();
  10178. };
  10179. var findDelta = function (outerWindow, cBody) {
  10180. var last = getLastHeight(cBody);
  10181. var current = outerWindow.innerHeight;
  10182. return last > current ? Optional.some(last - current) : Optional.none();
  10183. };
  10184. var calculate = function (cWin, bounds, delta) {
  10185. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10186. return isOutside ? Math.min(delta, bounds.bottom - cWin.innerHeight + EXTRA_SPACING) : 0;
  10187. };
  10188. var setup$1 = function (outerWindow, cWin) {
  10189. var cBody = SugarElement.fromDom(cWin.document.body);
  10190. var toEditing = function () {
  10191. resume(cWin);
  10192. };
  10193. var onResize = bind$3(SugarElement.fromDom(outerWindow), 'resize', function () {
  10194. findDelta(outerWindow, cBody).each(function (delta) {
  10195. getBounds$1(cWin).each(function (bounds) {
  10196. var cScrollBy = calculate(cWin, bounds, delta);
  10197. if (cScrollBy !== 0) {
  10198. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10199. }
  10200. });
  10201. });
  10202. setLastHeight(cBody, outerWindow.innerHeight);
  10203. });
  10204. setLastHeight(cBody, outerWindow.innerHeight);
  10205. var destroy = function () {
  10206. onResize.unbind();
  10207. };
  10208. return {
  10209. toEditing: toEditing,
  10210. destroy: destroy
  10211. };
  10212. };
  10213. var create$4 = function (platform, mask) {
  10214. var meta = tag();
  10215. var androidApi = api$2();
  10216. var androidEvents = api$2();
  10217. var enter = function () {
  10218. mask.hide();
  10219. add$2(platform.container, resolve('fullscreen-maximized'));
  10220. add$2(platform.container, resolve('android-maximized'));
  10221. meta.maximize();
  10222. add$2(platform.body, resolve('android-scroll-reload'));
  10223. androidApi.set(setup$1(platform.win, getWin$1(platform.editor).getOrDie('no')));
  10224. getActiveApi(platform.editor).each(function (editorApi) {
  10225. clobberStyles(platform.container, editorApi.body);
  10226. androidEvents.set(initEvents(editorApi, platform.toolstrip, platform.alloy));
  10227. });
  10228. };
  10229. var exit = function () {
  10230. meta.restore();
  10231. mask.show();
  10232. remove$4(platform.container, resolve('fullscreen-maximized'));
  10233. remove$4(platform.container, resolve('android-maximized'));
  10234. restoreStyles();
  10235. remove$4(platform.body, resolve('android-scroll-reload'));
  10236. androidEvents.clear();
  10237. androidApi.clear();
  10238. };
  10239. return {
  10240. enter: enter,
  10241. exit: exit
  10242. };
  10243. };
  10244. var first$1 = function (fn, rate) {
  10245. var timer = null;
  10246. var cancel = function () {
  10247. if (timer !== null) {
  10248. clearTimeout(timer);
  10249. timer = null;
  10250. }
  10251. };
  10252. var throttle = function () {
  10253. var args = [];
  10254. for (var _i = 0; _i < arguments.length; _i++) {
  10255. args[_i] = arguments[_i];
  10256. }
  10257. if (timer === null) {
  10258. timer = setTimeout(function () {
  10259. fn.apply(null, args);
  10260. timer = null;
  10261. }, rate);
  10262. }
  10263. };
  10264. return {
  10265. cancel: cancel,
  10266. throttle: throttle
  10267. };
  10268. };
  10269. var last = function (fn, rate) {
  10270. var timer = null;
  10271. var cancel = function () {
  10272. if (timer !== null) {
  10273. clearTimeout(timer);
  10274. timer = null;
  10275. }
  10276. };
  10277. var throttle = function () {
  10278. var args = [];
  10279. for (var _i = 0; _i < arguments.length; _i++) {
  10280. args[_i] = arguments[_i];
  10281. }
  10282. if (timer !== null) {
  10283. clearTimeout(timer);
  10284. }
  10285. timer = setTimeout(function () {
  10286. fn.apply(null, args);
  10287. timer = null;
  10288. }, rate);
  10289. };
  10290. return {
  10291. cancel: cancel,
  10292. throttle: throttle
  10293. };
  10294. };
  10295. var sketch$9 = function (onView, _translate) {
  10296. var memIcon = record(Container.sketch({
  10297. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10298. containerBehaviours: derive$1([Toggling.config({
  10299. toggleClass: resolve('mask-tap-icon-selected'),
  10300. toggleOnExecute: false
  10301. })])
  10302. }));
  10303. var onViewThrottle = first$1(onView, 200);
  10304. return Container.sketch({
  10305. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10306. components: [Container.sketch({
  10307. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10308. components: [Button.sketch({
  10309. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10310. components: [memIcon.asSpec()],
  10311. action: function (_button) {
  10312. onViewThrottle.throttle();
  10313. },
  10314. buttonBehaviours: derive$1([Toggling.config({ toggleClass: resolve('mask-tap-icon-selected') })])
  10315. })]
  10316. })]
  10317. });
  10318. };
  10319. var unbindNoop = constant({ unbind: noop });
  10320. var MobileSchema = objOf([
  10321. strictObjOf('editor', [
  10322. strict$1('getFrame'),
  10323. option('getBody'),
  10324. option('getDoc'),
  10325. option('getWin'),
  10326. option('getSelection'),
  10327. option('setSelection'),
  10328. option('clearSelection'),
  10329. option('cursorSaver'),
  10330. option('onKeyup'),
  10331. option('onNodeChanged'),
  10332. option('getCursorBox'),
  10333. strict$1('onDomChanged'),
  10334. defaulted$1('onTouchContent', noop),
  10335. defaulted$1('onTapContent', noop),
  10336. defaulted$1('onTouchToolstrip', noop),
  10337. defaulted$1('onScrollToCursor', unbindNoop),
  10338. defaulted$1('onScrollToElement', unbindNoop),
  10339. defaulted$1('onToEditing', unbindNoop),
  10340. defaulted$1('onToReading', unbindNoop),
  10341. defaulted$1('onToolbarScrollStart', identity)
  10342. ]),
  10343. strict$1('socket'),
  10344. strict$1('toolstrip'),
  10345. strict$1('dropup'),
  10346. strict$1('toolbar'),
  10347. strict$1('container'),
  10348. strict$1('alloy'),
  10349. state$1('win', function (spec) {
  10350. return owner(spec.socket).dom.defaultView;
  10351. }),
  10352. state$1('body', function (spec) {
  10353. return SugarElement.fromDom(spec.socket.dom.ownerDocument.body);
  10354. }),
  10355. defaulted$1('translate', identity),
  10356. defaulted$1('setReadOnly', noop),
  10357. defaulted$1('readOnlyOnInit', always)
  10358. ]);
  10359. var produce = function (raw) {
  10360. var mobile = asRawOrDie('Getting AndroidWebapp schema', MobileSchema, raw);
  10361. set$3(mobile.toolstrip, 'width', '100%');
  10362. var onTap = function () {
  10363. mobile.setReadOnly(mobile.readOnlyOnInit());
  10364. mode.enter();
  10365. };
  10366. var mask = build$1(sketch$9(onTap, mobile.translate));
  10367. mobile.alloy.add(mask);
  10368. var maskApi = {
  10369. show: function () {
  10370. mobile.alloy.add(mask);
  10371. },
  10372. hide: function () {
  10373. mobile.alloy.remove(mask);
  10374. }
  10375. };
  10376. append(mobile.container, mask.element);
  10377. var mode = create$4(mobile, maskApi);
  10378. return {
  10379. setReadOnly: mobile.setReadOnly,
  10380. refreshStructure: noop,
  10381. enter: mode.enter,
  10382. exit: mode.exit,
  10383. destroy: noop
  10384. };
  10385. };
  10386. var schema$e = constant([
  10387. strict$1('dom'),
  10388. defaulted$1('shell', true),
  10389. field$1('toolbarBehaviours', [Replacing])
  10390. ]);
  10391. var enhanceGroups = function () {
  10392. return { behaviours: derive$1([Replacing.config({})]) };
  10393. };
  10394. var parts$2 = constant([optional({
  10395. name: 'groups',
  10396. overrides: enhanceGroups
  10397. })]);
  10398. var factory$4 = function (detail, components, _spec, _externals) {
  10399. var setGroups = function (toolbar, groups) {
  10400. getGroupContainer(toolbar).fold(function () {
  10401. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10402. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10403. }, function (container) {
  10404. Replacing.set(container, groups);
  10405. });
  10406. };
  10407. var getGroupContainer = function (component) {
  10408. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  10409. };
  10410. var extra = detail.shell ? {
  10411. behaviours: [Replacing.config({})],
  10412. components: []
  10413. } : {
  10414. behaviours: [],
  10415. components: components
  10416. };
  10417. return {
  10418. uid: detail.uid,
  10419. dom: detail.dom,
  10420. components: extra.components,
  10421. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10422. apis: { setGroups: setGroups },
  10423. domModification: { attributes: { role: 'group' } }
  10424. };
  10425. };
  10426. var Toolbar = composite$1({
  10427. name: 'Toolbar',
  10428. configFields: schema$e(),
  10429. partFields: parts$2(),
  10430. factory: factory$4,
  10431. apis: {
  10432. setGroups: function (apis, toolbar, groups) {
  10433. apis.setGroups(toolbar, groups);
  10434. }
  10435. }
  10436. });
  10437. var schema$f = constant([
  10438. strict$1('items'),
  10439. markers(['itemSelector']),
  10440. field$1('tgroupBehaviours', [Keying])
  10441. ]);
  10442. var parts$3 = constant([group({
  10443. name: 'items',
  10444. unit: 'item'
  10445. })]);
  10446. var factory$5 = function (detail, components, _spec, _externals) {
  10447. return {
  10448. uid: detail.uid,
  10449. dom: detail.dom,
  10450. components: components,
  10451. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10452. mode: 'flow',
  10453. selector: detail.markers.itemSelector
  10454. })]),
  10455. domModification: { attributes: { role: 'toolbar' } }
  10456. };
  10457. };
  10458. var ToolbarGroup = composite$1({
  10459. name: 'ToolbarGroup',
  10460. configFields: schema$f(),
  10461. partFields: parts$3(),
  10462. factory: factory$5
  10463. });
  10464. var dataHorizontal = 'data-' + resolve('horizontal-scroll');
  10465. var canScrollVertically = function (container) {
  10466. container.dom.scrollTop = 1;
  10467. var result = container.dom.scrollTop !== 0;
  10468. container.dom.scrollTop = 0;
  10469. return result;
  10470. };
  10471. var canScrollHorizontally = function (container) {
  10472. container.dom.scrollLeft = 1;
  10473. var result = container.dom.scrollLeft !== 0;
  10474. container.dom.scrollLeft = 0;
  10475. return result;
  10476. };
  10477. var hasVerticalScroll = function (container) {
  10478. return container.dom.scrollTop > 0 || canScrollVertically(container);
  10479. };
  10480. var hasHorizontalScroll = function (container) {
  10481. return container.dom.scrollLeft > 0 || canScrollHorizontally(container);
  10482. };
  10483. var markAsHorizontal = function (container) {
  10484. set(container, dataHorizontal, 'true');
  10485. };
  10486. var hasScroll = function (container) {
  10487. return get$1(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10488. };
  10489. var exclusive = function (scope, selector) {
  10490. return bind$3(scope, 'touchmove', function (event) {
  10491. closest$2(event.target, selector).filter(hasScroll).fold(function () {
  10492. event.prevent();
  10493. }, noop);
  10494. });
  10495. };
  10496. var ScrollingToolbar = function () {
  10497. var makeGroup = function (gSpec) {
  10498. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10499. return {
  10500. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10501. tgroupBehaviours: derive$1([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, _simulatedEvent) {
  10502. set$3(component.element, 'overflow-x', 'auto');
  10503. markAsHorizontal(component.element);
  10504. register(component.element);
  10505. })] : [])]),
  10506. components: [Container.sketch({ components: [ToolbarGroup.parts.items({})] })],
  10507. markers: { itemSelector: '.' + resolve('toolbar-group-item') },
  10508. items: gSpec.items
  10509. };
  10510. };
  10511. var toolbar = build$1(Toolbar.sketch({
  10512. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10513. components: [Toolbar.parts.groups({})],
  10514. toolbarBehaviours: derive$1([
  10515. Toggling.config({
  10516. toggleClass: resolve('context-toolbar'),
  10517. toggleOnExecute: false,
  10518. aria: { mode: 'none' }
  10519. }),
  10520. Keying.config({ mode: 'cyclic' })
  10521. ]),
  10522. shell: true
  10523. }));
  10524. var wrapper = build$1(Container.sketch({
  10525. dom: { classes: [resolve('toolstrip')] },
  10526. components: [premade$1(toolbar)],
  10527. containerBehaviours: derive$1([Toggling.config({
  10528. toggleClass: resolve('android-selection-context-toolbar'),
  10529. toggleOnExecute: false
  10530. })])
  10531. }));
  10532. var resetGroups = function () {
  10533. Toolbar.setGroups(toolbar, initGroups.get());
  10534. Toggling.off(toolbar);
  10535. };
  10536. var initGroups = Cell([]);
  10537. var setGroups = function (gs) {
  10538. initGroups.set(gs);
  10539. resetGroups();
  10540. };
  10541. var createGroups = function (gs) {
  10542. return map(gs, compose(ToolbarGroup.sketch, makeGroup));
  10543. };
  10544. var refresh = function () {
  10545. };
  10546. var setContextToolbar = function (gs) {
  10547. Toggling.on(toolbar);
  10548. Toolbar.setGroups(toolbar, gs);
  10549. };
  10550. var restoreToolbar = function () {
  10551. if (Toggling.isOn(toolbar)) {
  10552. resetGroups();
  10553. }
  10554. };
  10555. var focus = function () {
  10556. Keying.focusIn(toolbar);
  10557. };
  10558. return {
  10559. wrapper: wrapper,
  10560. toolbar: toolbar,
  10561. createGroups: createGroups,
  10562. setGroups: setGroups,
  10563. setContextToolbar: setContextToolbar,
  10564. restoreToolbar: restoreToolbar,
  10565. refresh: refresh,
  10566. focus: focus
  10567. };
  10568. };
  10569. var makeEditSwitch = function (webapp) {
  10570. return build$1(Button.sketch({
  10571. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10572. action: function () {
  10573. webapp.run(function (w) {
  10574. w.setReadOnly(false);
  10575. });
  10576. }
  10577. }));
  10578. };
  10579. var makeSocket = function () {
  10580. return build$1(Container.sketch({
  10581. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10582. components: [],
  10583. containerBehaviours: derive$1([Replacing.config({})])
  10584. }));
  10585. };
  10586. var showEdit = function (socket, switchToEdit) {
  10587. Replacing.append(socket, premade$1(switchToEdit));
  10588. };
  10589. var hideEdit = function (socket, switchToEdit) {
  10590. Replacing.remove(socket, switchToEdit);
  10591. };
  10592. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10593. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10594. swap(root);
  10595. var f = readOnly ? showEdit : hideEdit;
  10596. f(socket, switchToEdit);
  10597. };
  10598. var getAnimationRoot = function (component, slideConfig) {
  10599. return slideConfig.getAnimationRoot.fold(function () {
  10600. return component.element;
  10601. }, function (get) {
  10602. return get(component);
  10603. });
  10604. };
  10605. var getDimensionProperty = function (slideConfig) {
  10606. return slideConfig.dimension.property;
  10607. };
  10608. var getDimension = function (slideConfig, elem) {
  10609. return slideConfig.dimension.getDimension(elem);
  10610. };
  10611. var disableTransitions = function (component, slideConfig) {
  10612. var root = getAnimationRoot(component, slideConfig);
  10613. remove$6(root, [
  10614. slideConfig.shrinkingClass,
  10615. slideConfig.growingClass
  10616. ]);
  10617. };
  10618. var setShrunk = function (component, slideConfig) {
  10619. remove$4(component.element, slideConfig.openClass);
  10620. add$2(component.element, slideConfig.closedClass);
  10621. set$3(component.element, getDimensionProperty(slideConfig), '0px');
  10622. reflow(component.element);
  10623. };
  10624. var setGrown = function (component, slideConfig) {
  10625. remove$4(component.element, slideConfig.closedClass);
  10626. add$2(component.element, slideConfig.openClass);
  10627. remove$5(component.element, getDimensionProperty(slideConfig));
  10628. };
  10629. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10630. slideState.setCollapsed();
  10631. set$3(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  10632. reflow(component.element);
  10633. disableTransitions(component, slideConfig);
  10634. setShrunk(component, slideConfig);
  10635. slideConfig.onStartShrink(component);
  10636. slideConfig.onShrunk(component);
  10637. };
  10638. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10639. var size = calculatedSize.getOrThunk(function () {
  10640. return getDimension(slideConfig, component.element);
  10641. });
  10642. slideState.setCollapsed();
  10643. set$3(component.element, getDimensionProperty(slideConfig), size);
  10644. reflow(component.element);
  10645. var root = getAnimationRoot(component, slideConfig);
  10646. remove$4(root, slideConfig.growingClass);
  10647. add$2(root, slideConfig.shrinkingClass);
  10648. setShrunk(component, slideConfig);
  10649. slideConfig.onStartShrink(component);
  10650. };
  10651. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10652. var size = getDimension(slideConfig, component.element);
  10653. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10654. shrinker(component, slideConfig, slideState, Optional.some(size));
  10655. };
  10656. var doStartGrow = function (component, slideConfig, slideState) {
  10657. var root = getAnimationRoot(component, slideConfig);
  10658. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  10659. var beforeSize = getDimension(slideConfig, component.element);
  10660. setGrown(component, slideConfig);
  10661. var fullSize = getDimension(slideConfig, component.element);
  10662. var startPartialGrow = function () {
  10663. set$3(component.element, getDimensionProperty(slideConfig), beforeSize);
  10664. reflow(component.element);
  10665. };
  10666. var startCompleteGrow = function () {
  10667. setShrunk(component, slideConfig);
  10668. };
  10669. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  10670. setStartSize();
  10671. remove$4(root, slideConfig.shrinkingClass);
  10672. add$2(root, slideConfig.growingClass);
  10673. setGrown(component, slideConfig);
  10674. set$3(component.element, getDimensionProperty(slideConfig), fullSize);
  10675. slideState.setExpanded();
  10676. slideConfig.onStartGrow(component);
  10677. };
  10678. var refresh = function (component, slideConfig, slideState) {
  10679. if (slideState.isExpanded()) {
  10680. remove$5(component.element, getDimensionProperty(slideConfig));
  10681. var fullSize = getDimension(slideConfig, component.element);
  10682. set$3(component.element, getDimensionProperty(slideConfig), fullSize);
  10683. }
  10684. };
  10685. var grow = function (component, slideConfig, slideState) {
  10686. if (!slideState.isExpanded()) {
  10687. doStartGrow(component, slideConfig, slideState);
  10688. }
  10689. };
  10690. var shrink = function (component, slideConfig, slideState) {
  10691. if (slideState.isExpanded()) {
  10692. doStartSmartShrink(component, slideConfig, slideState);
  10693. }
  10694. };
  10695. var immediateShrink = function (component, slideConfig, slideState) {
  10696. if (slideState.isExpanded()) {
  10697. doImmediateShrink(component, slideConfig, slideState, Optional.none());
  10698. }
  10699. };
  10700. var hasGrown = function (component, slideConfig, slideState) {
  10701. return slideState.isExpanded();
  10702. };
  10703. var hasShrunk = function (component, slideConfig, slideState) {
  10704. return slideState.isCollapsed();
  10705. };
  10706. var isGrowing = function (component, slideConfig, _slideState) {
  10707. var root = getAnimationRoot(component, slideConfig);
  10708. return has$2(root, slideConfig.growingClass) === true;
  10709. };
  10710. var isShrinking = function (component, slideConfig, _slideState) {
  10711. var root = getAnimationRoot(component, slideConfig);
  10712. return has$2(root, slideConfig.shrinkingClass) === true;
  10713. };
  10714. var isTransitioning = function (component, slideConfig, slideState) {
  10715. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  10716. };
  10717. var toggleGrow = function (component, slideConfig, slideState) {
  10718. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  10719. f(component, slideConfig, slideState);
  10720. };
  10721. var SlidingApis = /*#__PURE__*/Object.freeze({
  10722. __proto__: null,
  10723. refresh: refresh,
  10724. grow: grow,
  10725. shrink: shrink,
  10726. immediateShrink: immediateShrink,
  10727. hasGrown: hasGrown,
  10728. hasShrunk: hasShrunk,
  10729. isGrowing: isGrowing,
  10730. isShrinking: isShrinking,
  10731. isTransitioning: isTransitioning,
  10732. toggleGrow: toggleGrow,
  10733. disableTransitions: disableTransitions
  10734. });
  10735. var exhibit$5 = function (base, slideConfig, _slideState) {
  10736. var expanded = slideConfig.expanded;
  10737. return expanded ? nu$5({
  10738. classes: [slideConfig.openClass],
  10739. styles: {}
  10740. }) : nu$5({
  10741. classes: [slideConfig.closedClass],
  10742. styles: wrap$1(slideConfig.dimension.property, '0px')
  10743. });
  10744. };
  10745. var events$a = function (slideConfig, slideState) {
  10746. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  10747. var raw = simulatedEvent.event.raw;
  10748. if (raw.propertyName === slideConfig.dimension.property) {
  10749. disableTransitions(component, slideConfig);
  10750. if (slideState.isExpanded()) {
  10751. remove$5(component.element, slideConfig.dimension.property);
  10752. }
  10753. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  10754. notify(component);
  10755. }
  10756. })]);
  10757. };
  10758. var ActiveSliding = /*#__PURE__*/Object.freeze({
  10759. __proto__: null,
  10760. exhibit: exhibit$5,
  10761. events: events$a
  10762. });
  10763. var SlidingSchema = [
  10764. strict$1('closedClass'),
  10765. strict$1('openClass'),
  10766. strict$1('shrinkingClass'),
  10767. strict$1('growingClass'),
  10768. option('getAnimationRoot'),
  10769. onHandler('onShrunk'),
  10770. onHandler('onStartShrink'),
  10771. onHandler('onGrown'),
  10772. onHandler('onStartGrow'),
  10773. defaulted$1('expanded', false),
  10774. strictOf('dimension', choose$1('property', {
  10775. width: [
  10776. output('property', 'width'),
  10777. output('getDimension', function (elem) {
  10778. return get$7(elem) + 'px';
  10779. })
  10780. ],
  10781. height: [
  10782. output('property', 'height'),
  10783. output('getDimension', function (elem) {
  10784. return get$5(elem) + 'px';
  10785. })
  10786. ]
  10787. }))
  10788. ];
  10789. var init$4 = function (spec) {
  10790. var state = Cell(spec.expanded);
  10791. var readState = function () {
  10792. return 'expanded: ' + state.get();
  10793. };
  10794. return nu$6({
  10795. isExpanded: function () {
  10796. return state.get() === true;
  10797. },
  10798. isCollapsed: function () {
  10799. return state.get() === false;
  10800. },
  10801. setCollapsed: curry(state.set, false),
  10802. setExpanded: curry(state.set, true),
  10803. readState: readState
  10804. });
  10805. };
  10806. var SlidingState = /*#__PURE__*/Object.freeze({
  10807. __proto__: null,
  10808. init: init$4
  10809. });
  10810. var Sliding = create$1({
  10811. fields: SlidingSchema,
  10812. name: 'sliding',
  10813. active: ActiveSliding,
  10814. apis: SlidingApis,
  10815. state: SlidingState
  10816. });
  10817. var build$2 = function (refresh, scrollIntoView) {
  10818. var dropup = build$1(Container.sketch({
  10819. dom: {
  10820. tag: 'div',
  10821. classes: [resolve('dropup')]
  10822. },
  10823. components: [],
  10824. containerBehaviours: derive$1([
  10825. Replacing.config({}),
  10826. Sliding.config({
  10827. closedClass: resolve('dropup-closed'),
  10828. openClass: resolve('dropup-open'),
  10829. shrinkingClass: resolve('dropup-shrinking'),
  10830. growingClass: resolve('dropup-growing'),
  10831. dimension: { property: 'height' },
  10832. onShrunk: function (component) {
  10833. refresh();
  10834. scrollIntoView();
  10835. Replacing.set(component, []);
  10836. },
  10837. onGrown: function (_component) {
  10838. refresh();
  10839. scrollIntoView();
  10840. }
  10841. }),
  10842. orientation(function (_component, _data) {
  10843. disappear(noop);
  10844. })
  10845. ])
  10846. }));
  10847. var appear = function (menu, update, component) {
  10848. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  10849. window.requestAnimationFrame(function () {
  10850. update(component);
  10851. Replacing.set(dropup, [menu()]);
  10852. Sliding.grow(dropup);
  10853. });
  10854. }
  10855. };
  10856. var disappear = function (onReadyToShrink) {
  10857. window.requestAnimationFrame(function () {
  10858. onReadyToShrink();
  10859. Sliding.shrink(dropup);
  10860. });
  10861. };
  10862. return {
  10863. appear: appear,
  10864. disappear: disappear,
  10865. component: dropup,
  10866. element: dropup.element
  10867. };
  10868. };
  10869. var closest$3 = function (scope, selector, isRoot) {
  10870. return closest$2(scope, selector, isRoot).isSome();
  10871. };
  10872. var isDangerous = function (event) {
  10873. var keyEv = event.raw;
  10874. return keyEv.which === BACKSPACE[0] && !contains([
  10875. 'input',
  10876. 'textarea'
  10877. ], name(event.target)) && !closest$3(event.target, '[contenteditable="true"]');
  10878. };
  10879. var isFirefox = function () {
  10880. return detect$3().browser.isFirefox();
  10881. };
  10882. var settingsSchema = objOfOnly([
  10883. strictFunction('triggerEvent'),
  10884. defaulted$1('stopBackspace', true)
  10885. ]);
  10886. var bindFocus = function (container, handler) {
  10887. if (isFirefox()) {
  10888. return capture$1(container, 'focus', handler);
  10889. } else {
  10890. return bind$3(container, 'focusin', handler);
  10891. }
  10892. };
  10893. var bindBlur = function (container, handler) {
  10894. if (isFirefox()) {
  10895. return capture$1(container, 'blur', handler);
  10896. } else {
  10897. return bind$3(container, 'focusout', handler);
  10898. }
  10899. };
  10900. var setup$2 = function (container, rawSettings) {
  10901. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  10902. var pointerEvents = [
  10903. 'touchstart',
  10904. 'touchmove',
  10905. 'touchend',
  10906. 'touchcancel',
  10907. 'gesturestart',
  10908. 'mousedown',
  10909. 'mouseup',
  10910. 'mouseover',
  10911. 'mousemove',
  10912. 'mouseout',
  10913. 'click'
  10914. ];
  10915. var tapEvent = monitor(settings);
  10916. var simpleEvents = map(pointerEvents.concat([
  10917. 'selectstart',
  10918. 'input',
  10919. 'contextmenu',
  10920. 'change',
  10921. 'transitionend',
  10922. 'drag',
  10923. 'dragstart',
  10924. 'dragend',
  10925. 'dragenter',
  10926. 'dragleave',
  10927. 'dragover',
  10928. 'drop',
  10929. 'keyup'
  10930. ]), function (type) {
  10931. return bind$3(container, type, function (event) {
  10932. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  10933. if (tapStopped) {
  10934. event.kill();
  10935. }
  10936. });
  10937. var stopped = settings.triggerEvent(type, event);
  10938. if (stopped) {
  10939. event.kill();
  10940. }
  10941. });
  10942. });
  10943. var pasteTimeout = Cell(Optional.none());
  10944. var onPaste = bind$3(container, 'paste', function (event) {
  10945. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  10946. if (tapStopped) {
  10947. event.kill();
  10948. }
  10949. });
  10950. var stopped = settings.triggerEvent('paste', event);
  10951. if (stopped) {
  10952. event.kill();
  10953. }
  10954. pasteTimeout.set(Optional.some(setTimeout(function () {
  10955. settings.triggerEvent(postPaste(), event);
  10956. }, 0)));
  10957. });
  10958. var onKeydown = bind$3(container, 'keydown', function (event) {
  10959. var stopped = settings.triggerEvent('keydown', event);
  10960. if (stopped) {
  10961. event.kill();
  10962. } else if (settings.stopBackspace === true && isDangerous(event)) {
  10963. event.prevent();
  10964. }
  10965. });
  10966. var onFocusIn = bindFocus(container, function (event) {
  10967. var stopped = settings.triggerEvent('focusin', event);
  10968. if (stopped) {
  10969. event.kill();
  10970. }
  10971. });
  10972. var focusoutTimeout = Cell(Optional.none());
  10973. var onFocusOut = bindBlur(container, function (event) {
  10974. var stopped = settings.triggerEvent('focusout', event);
  10975. if (stopped) {
  10976. event.kill();
  10977. }
  10978. focusoutTimeout.set(Optional.some(setTimeout(function () {
  10979. settings.triggerEvent(postBlur(), event);
  10980. }, 0)));
  10981. });
  10982. var unbind = function () {
  10983. each(simpleEvents, function (e) {
  10984. e.unbind();
  10985. });
  10986. onKeydown.unbind();
  10987. onFocusIn.unbind();
  10988. onFocusOut.unbind();
  10989. onPaste.unbind();
  10990. pasteTimeout.get().each(clearTimeout);
  10991. focusoutTimeout.get().each(clearTimeout);
  10992. };
  10993. return { unbind: unbind };
  10994. };
  10995. var derive$2 = function (rawEvent, rawTarget) {
  10996. var source = get(rawEvent, 'target').getOr(rawTarget);
  10997. return Cell(source);
  10998. };
  10999. var fromSource = function (event, source) {
  11000. var stopper = Cell(false);
  11001. var cutter = Cell(false);
  11002. var stop = function () {
  11003. stopper.set(true);
  11004. };
  11005. var cut = function () {
  11006. cutter.set(true);
  11007. };
  11008. return {
  11009. stop: stop,
  11010. cut: cut,
  11011. isStopped: stopper.get,
  11012. isCut: cutter.get,
  11013. event: event,
  11014. setSource: source.set,
  11015. getSource: source.get
  11016. };
  11017. };
  11018. var fromExternal = function (event) {
  11019. var stopper = Cell(false);
  11020. var stop = function () {
  11021. stopper.set(true);
  11022. };
  11023. return {
  11024. stop: stop,
  11025. cut: noop,
  11026. isStopped: stopper.get,
  11027. isCut: never,
  11028. event: event,
  11029. setSource: die('Cannot set source of a broadcasted event'),
  11030. getSource: die('Cannot get source of a broadcasted event')
  11031. };
  11032. };
  11033. var adt$7 = Adt.generate([
  11034. { stopped: [] },
  11035. { resume: ['element'] },
  11036. { complete: [] }
  11037. ]);
  11038. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11039. var handler = lookup(eventType, target);
  11040. var simulatedEvent = fromSource(rawEvent, source);
  11041. return handler.fold(function () {
  11042. logger.logEventNoHandlers(eventType, target);
  11043. return adt$7.complete();
  11044. }, function (handlerInfo) {
  11045. var descHandler = handlerInfo.descHandler;
  11046. var eventHandler = getCurried(descHandler);
  11047. eventHandler(simulatedEvent);
  11048. if (simulatedEvent.isStopped()) {
  11049. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  11050. return adt$7.stopped();
  11051. } else if (simulatedEvent.isCut()) {
  11052. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  11053. return adt$7.complete();
  11054. } else {
  11055. return parent(handlerInfo.element).fold(function () {
  11056. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  11057. return adt$7.complete();
  11058. }, function (parent) {
  11059. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  11060. return adt$7.resume(parent);
  11061. });
  11062. }
  11063. });
  11064. };
  11065. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11066. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  11067. return true;
  11068. }, function (parent) {
  11069. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11070. }, function () {
  11071. return false;
  11072. });
  11073. };
  11074. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11075. var source = derive$2(rawEvent, target);
  11076. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11077. };
  11078. var broadcast = function (listeners, rawEvent, _logger) {
  11079. var simulatedEvent = fromExternal(rawEvent);
  11080. each(listeners, function (listener) {
  11081. var descHandler = listener.descHandler;
  11082. var handler = getCurried(descHandler);
  11083. handler(simulatedEvent);
  11084. });
  11085. return simulatedEvent.isStopped();
  11086. };
  11087. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11088. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  11089. };
  11090. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11091. var source = derive$2(rawEvent, rawTarget);
  11092. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11093. };
  11094. var eventHandler = function (element, descHandler) {
  11095. return {
  11096. element: element,
  11097. descHandler: descHandler
  11098. };
  11099. };
  11100. var broadcastHandler = function (id, handler) {
  11101. return {
  11102. id: id,
  11103. descHandler: handler
  11104. };
  11105. };
  11106. function EventRegistry () {
  11107. var registry = {};
  11108. var registerId = function (extraArgs, id, events) {
  11109. each$1(events, function (v, k) {
  11110. var handlers = registry[k] !== undefined ? registry[k] : {};
  11111. handlers[id] = curryArgs(v, extraArgs);
  11112. registry[k] = handlers;
  11113. });
  11114. };
  11115. var findHandler = function (handlers, elem) {
  11116. return read$2(elem).fold(function () {
  11117. return Optional.none();
  11118. }, function (id) {
  11119. return handlers.bind(function (h) {
  11120. return get(h, id);
  11121. }).map(function (descHandler) {
  11122. return eventHandler(elem, descHandler);
  11123. });
  11124. });
  11125. };
  11126. var filterByType = function (type) {
  11127. return get(registry, type).map(function (handlers) {
  11128. return mapToArray(handlers, function (f, id) {
  11129. return broadcastHandler(id, f);
  11130. });
  11131. }).getOr([]);
  11132. };
  11133. var find = function (isAboveRoot, type, target) {
  11134. var handlers = get(registry, type);
  11135. return closest(target, function (elem) {
  11136. return findHandler(handlers, elem);
  11137. }, isAboveRoot);
  11138. };
  11139. var unregisterId = function (id) {
  11140. each$1(registry, function (handlersById, _eventName) {
  11141. if (handlersById.hasOwnProperty(id)) {
  11142. delete handlersById[id];
  11143. }
  11144. });
  11145. };
  11146. return {
  11147. registerId: registerId,
  11148. unregisterId: unregisterId,
  11149. filterByType: filterByType,
  11150. find: find
  11151. };
  11152. }
  11153. function Registry () {
  11154. var events = EventRegistry();
  11155. var components = {};
  11156. var readOrTag = function (component) {
  11157. var elem = component.element;
  11158. return read$2(elem).fold(function () {
  11159. return write('uid-', component.element);
  11160. }, function (uid) {
  11161. return uid;
  11162. });
  11163. };
  11164. var failOnDuplicate = function (component, tagId) {
  11165. var conflict = components[tagId];
  11166. if (conflict === component) {
  11167. unregister(component);
  11168. } else {
  11169. 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');
  11170. }
  11171. };
  11172. var register = function (component) {
  11173. var tagId = readOrTag(component);
  11174. if (hasNonNullableKey(components, tagId)) {
  11175. failOnDuplicate(component, tagId);
  11176. }
  11177. var extraArgs = [component];
  11178. events.registerId(extraArgs, tagId, component.events);
  11179. components[tagId] = component;
  11180. };
  11181. var unregister = function (component) {
  11182. read$2(component.element).each(function (tagId) {
  11183. delete components[tagId];
  11184. events.unregisterId(tagId);
  11185. });
  11186. };
  11187. var filter = function (type) {
  11188. return events.filterByType(type);
  11189. };
  11190. var find = function (isAboveRoot, type, target) {
  11191. return events.find(isAboveRoot, type, target);
  11192. };
  11193. var getById = function (id) {
  11194. return get(components, id);
  11195. };
  11196. return {
  11197. find: find,
  11198. filter: filter,
  11199. register: register,
  11200. unregister: unregister,
  11201. getById: getById
  11202. };
  11203. }
  11204. var takeover = function (root) {
  11205. var isAboveRoot = function (el) {
  11206. return parent(root.element).fold(function () {
  11207. return true;
  11208. }, function (parent) {
  11209. return eq(el, parent);
  11210. });
  11211. };
  11212. var registry = Registry();
  11213. var lookup = function (eventName, target) {
  11214. return registry.find(isAboveRoot, eventName, target);
  11215. };
  11216. var domEvents = setup$2(root.element, {
  11217. triggerEvent: function (eventName, event) {
  11218. return monitorEvent(eventName, event.target, function (logger) {
  11219. return triggerUntilStopped(lookup, eventName, event, logger);
  11220. });
  11221. }
  11222. });
  11223. var systemApi = {
  11224. debugInfo: constant('real'),
  11225. triggerEvent: function (eventName, target, data) {
  11226. monitorEvent(eventName, target, function (logger) {
  11227. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11228. });
  11229. },
  11230. triggerFocus: function (target, originator) {
  11231. read$2(target).fold(function () {
  11232. focus$1(target);
  11233. }, function (_alloyId) {
  11234. monitorEvent(focus(), target, function (logger) {
  11235. triggerHandler(lookup, focus(), {
  11236. originator: originator,
  11237. kill: noop,
  11238. prevent: noop,
  11239. target: target
  11240. }, target, logger);
  11241. return false;
  11242. });
  11243. });
  11244. },
  11245. triggerEscape: function (comp, simulatedEvent) {
  11246. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  11247. },
  11248. getByUid: function (uid) {
  11249. return getByUid(uid);
  11250. },
  11251. getByDom: function (elem) {
  11252. return getByDom(elem);
  11253. },
  11254. build: build$1,
  11255. addToGui: function (c) {
  11256. add(c);
  11257. },
  11258. removeFromGui: function (c) {
  11259. remove$1(c);
  11260. },
  11261. addToWorld: function (c) {
  11262. addToWorld(c);
  11263. },
  11264. removeFromWorld: function (c) {
  11265. removeFromWorld(c);
  11266. },
  11267. broadcast: function (message) {
  11268. broadcast$1(message);
  11269. },
  11270. broadcastOn: function (channels, message) {
  11271. broadcastOn(channels, message);
  11272. },
  11273. broadcastEvent: function (eventName, event) {
  11274. broadcastEvent(eventName, event);
  11275. },
  11276. isConnected: always
  11277. };
  11278. var addToWorld = function (component) {
  11279. component.connect(systemApi);
  11280. if (!isText(component.element)) {
  11281. registry.register(component);
  11282. each(component.components(), addToWorld);
  11283. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  11284. }
  11285. };
  11286. var removeFromWorld = function (component) {
  11287. if (!isText(component.element)) {
  11288. each(component.components(), removeFromWorld);
  11289. registry.unregister(component);
  11290. }
  11291. component.disconnect();
  11292. };
  11293. var add = function (component) {
  11294. attach$1(root, component);
  11295. };
  11296. var remove$1 = function (component) {
  11297. detach(component);
  11298. };
  11299. var destroy = function () {
  11300. domEvents.unbind();
  11301. remove(root.element);
  11302. };
  11303. var broadcastData = function (data) {
  11304. var receivers = registry.filter(receive());
  11305. each(receivers, function (receiver) {
  11306. var descHandler = receiver.descHandler;
  11307. var handler = getCurried(descHandler);
  11308. handler(data);
  11309. });
  11310. };
  11311. var broadcast$1 = function (message) {
  11312. broadcastData({
  11313. universal: true,
  11314. data: message
  11315. });
  11316. };
  11317. var broadcastOn = function (channels, message) {
  11318. broadcastData({
  11319. universal: false,
  11320. channels: channels,
  11321. data: message
  11322. });
  11323. };
  11324. var broadcastEvent = function (eventName, event) {
  11325. var listeners = registry.filter(eventName);
  11326. return broadcast(listeners, event);
  11327. };
  11328. var getByUid = function (uid) {
  11329. return registry.getById(uid).fold(function () {
  11330. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11331. }, Result.value);
  11332. };
  11333. var getByDom = function (elem) {
  11334. var uid = read$2(elem).getOr('not found');
  11335. return getByUid(uid);
  11336. };
  11337. addToWorld(root);
  11338. return {
  11339. root: root,
  11340. element: root.element,
  11341. destroy: destroy,
  11342. add: add,
  11343. remove: remove$1,
  11344. getByUid: getByUid,
  11345. getByDom: getByDom,
  11346. addToWorld: addToWorld,
  11347. removeFromWorld: removeFromWorld,
  11348. broadcast: broadcast$1,
  11349. broadcastOn: broadcastOn,
  11350. broadcastEvent: broadcastEvent
  11351. };
  11352. };
  11353. var READ_ONLY_MODE_CLASS = resolve('readonly-mode');
  11354. var EDIT_MODE_CLASS = resolve('edit-mode');
  11355. function OuterContainer (spec) {
  11356. var root = build$1(Container.sketch({
  11357. dom: { classes: [resolve('outer-container')].concat(spec.classes) },
  11358. containerBehaviours: derive$1([Swapping.config({
  11359. alpha: READ_ONLY_MODE_CLASS,
  11360. omega: EDIT_MODE_CLASS
  11361. })])
  11362. }));
  11363. return takeover(root);
  11364. }
  11365. function AndroidRealm (scrollIntoView) {
  11366. var alloy = OuterContainer({ classes: [resolve('android-container')] });
  11367. var toolbar = ScrollingToolbar();
  11368. var webapp = api$2();
  11369. var switchToEdit = makeEditSwitch(webapp);
  11370. var socket = makeSocket();
  11371. var dropup = build$2(noop, scrollIntoView);
  11372. alloy.add(toolbar.wrapper);
  11373. alloy.add(socket);
  11374. alloy.add(dropup.component);
  11375. var setToolbarGroups = function (rawGroups) {
  11376. var groups = toolbar.createGroups(rawGroups);
  11377. toolbar.setGroups(groups);
  11378. };
  11379. var setContextToolbar = function (rawGroups) {
  11380. var groups = toolbar.createGroups(rawGroups);
  11381. toolbar.setContextToolbar(groups);
  11382. };
  11383. var focusToolbar = function () {
  11384. toolbar.focus();
  11385. };
  11386. var restoreToolbar = function () {
  11387. toolbar.restoreToolbar();
  11388. };
  11389. var init = function (spec) {
  11390. webapp.set(produce(spec));
  11391. };
  11392. var exit = function () {
  11393. webapp.run(function (w) {
  11394. w.exit();
  11395. Replacing.remove(socket, switchToEdit);
  11396. });
  11397. };
  11398. var updateMode$1 = function (readOnly) {
  11399. updateMode(socket, switchToEdit, readOnly, alloy.root);
  11400. };
  11401. return {
  11402. system: alloy,
  11403. element: alloy.element,
  11404. init: init,
  11405. exit: exit,
  11406. setToolbarGroups: setToolbarGroups,
  11407. setContextToolbar: setContextToolbar,
  11408. focusToolbar: focusToolbar,
  11409. restoreToolbar: restoreToolbar,
  11410. updateMode: updateMode$1,
  11411. socket: socket,
  11412. dropup: dropup
  11413. };
  11414. }
  11415. var input$1 = function (parent, operation) {
  11416. var input = SugarElement.fromTag('input');
  11417. setAll$1(input, {
  11418. opacity: '0',
  11419. position: 'absolute',
  11420. top: '-1000px',
  11421. left: '-1000px'
  11422. });
  11423. append(parent, input);
  11424. focus$1(input);
  11425. operation(input);
  11426. remove(input);
  11427. };
  11428. var refresh$1 = function (winScope) {
  11429. var sel = winScope.getSelection();
  11430. if (sel.rangeCount > 0) {
  11431. var br = sel.getRangeAt(0);
  11432. var r = winScope.document.createRange();
  11433. r.setStart(br.startContainer, br.startOffset);
  11434. r.setEnd(br.endContainer, br.endOffset);
  11435. sel.removeAllRanges();
  11436. sel.addRange(r);
  11437. }
  11438. };
  11439. var resume$1 = function (cWin, frame) {
  11440. active().each(function (active) {
  11441. if (!eq(active, frame)) {
  11442. blur(active);
  11443. }
  11444. });
  11445. cWin.focus();
  11446. focus$1(SugarElement.fromDom(cWin.document.body));
  11447. refresh$1(cWin);
  11448. };
  11449. var stubborn = function (outerBody, cWin, page, frame) {
  11450. var toEditing = function () {
  11451. resume$1(cWin, frame);
  11452. };
  11453. var toReading = function () {
  11454. input$1(outerBody, blur);
  11455. };
  11456. var captureInput = bind$3(page, 'keydown', function (evt) {
  11457. if (!contains([
  11458. 'input',
  11459. 'textarea'
  11460. ], name(evt.target))) {
  11461. toEditing();
  11462. }
  11463. });
  11464. var onToolbarTouch = function () {
  11465. };
  11466. var destroy = function () {
  11467. captureInput.unbind();
  11468. };
  11469. return {
  11470. toReading: toReading,
  11471. toEditing: toEditing,
  11472. onToolbarTouch: onToolbarTouch,
  11473. destroy: destroy
  11474. };
  11475. };
  11476. var initEvents$1 = function (editorApi, iosApi, toolstrip, socket, _dropup) {
  11477. var saveSelectionFirst = function () {
  11478. iosApi.run(function (api) {
  11479. api.highlightSelection();
  11480. });
  11481. };
  11482. var refreshIosSelection = function () {
  11483. iosApi.run(function (api) {
  11484. api.refreshSelection();
  11485. });
  11486. };
  11487. var scrollToY = function (yTop, height) {
  11488. var y = yTop - socket.dom.scrollTop;
  11489. iosApi.run(function (api) {
  11490. api.scrollIntoView(y, y + height);
  11491. });
  11492. };
  11493. var scrollToElement = function (_target) {
  11494. scrollToY(iosApi, socket);
  11495. };
  11496. var scrollToCursor = function () {
  11497. editorApi.getCursorBox().each(function (box) {
  11498. scrollToY(box.top, box.height);
  11499. });
  11500. };
  11501. var clearSelection = function () {
  11502. iosApi.run(function (api) {
  11503. api.clearSelection();
  11504. });
  11505. };
  11506. var clearAndRefresh = function () {
  11507. clearSelection();
  11508. refreshThrottle.throttle();
  11509. };
  11510. var refreshView = function () {
  11511. scrollToCursor();
  11512. iosApi.run(function (api) {
  11513. api.syncHeight();
  11514. });
  11515. };
  11516. var reposition = function () {
  11517. var toolbarHeight = get$5(toolstrip);
  11518. iosApi.run(function (api) {
  11519. api.setViewportOffset(toolbarHeight);
  11520. });
  11521. refreshIosSelection();
  11522. refreshView();
  11523. };
  11524. var toEditing = function () {
  11525. iosApi.run(function (api) {
  11526. api.toEditing();
  11527. });
  11528. };
  11529. var toReading = function () {
  11530. iosApi.run(function (api) {
  11531. api.toReading();
  11532. });
  11533. };
  11534. var onToolbarTouch = function (event) {
  11535. iosApi.run(function (api) {
  11536. api.onToolbarTouch(event);
  11537. });
  11538. };
  11539. var tapping = monitor$1(editorApi);
  11540. var refreshThrottle = last(refreshView, 300);
  11541. var listeners = [
  11542. editorApi.onKeyup(clearAndRefresh),
  11543. editorApi.onNodeChanged(refreshIosSelection),
  11544. editorApi.onDomChanged(refreshThrottle.throttle),
  11545. editorApi.onDomChanged(refreshIosSelection),
  11546. editorApi.onScrollToCursor(function (tinyEvent) {
  11547. tinyEvent.preventDefault();
  11548. refreshThrottle.throttle();
  11549. }),
  11550. editorApi.onScrollToElement(function (event) {
  11551. scrollToElement(event.element);
  11552. }),
  11553. editorApi.onToEditing(toEditing),
  11554. editorApi.onToReading(toReading),
  11555. bind$3(editorApi.doc, 'touchend', function (touchEvent) {
  11556. if (eq(editorApi.html, touchEvent.target) || eq(editorApi.body, touchEvent.target)) ;
  11557. }),
  11558. bind$3(toolstrip, 'transitionend', function (transitionEvent) {
  11559. if (transitionEvent.raw.propertyName === 'height') {
  11560. reposition();
  11561. }
  11562. }),
  11563. capture$1(toolstrip, 'touchstart', function (touchEvent) {
  11564. saveSelectionFirst();
  11565. onToolbarTouch(touchEvent);
  11566. editorApi.onTouchToolstrip();
  11567. }),
  11568. bind$3(editorApi.body, 'touchstart', function (evt) {
  11569. clearSelection();
  11570. editorApi.onTouchContent();
  11571. tapping.fireTouchstart(evt);
  11572. }),
  11573. tapping.onTouchmove(),
  11574. tapping.onTouchend(),
  11575. bind$3(editorApi.body, 'click', function (event) {
  11576. event.kill();
  11577. }),
  11578. bind$3(toolstrip, 'touchmove', function () {
  11579. editorApi.onToolbarScrollStart();
  11580. })
  11581. ];
  11582. var destroy = function () {
  11583. each(listeners, function (l) {
  11584. l.unbind();
  11585. });
  11586. };
  11587. return { destroy: destroy };
  11588. };
  11589. function FakeSelection (win, frame) {
  11590. var doc = win.document;
  11591. var container = SugarElement.fromTag('div');
  11592. add$2(container, resolve('unfocused-selections'));
  11593. append(SugarElement.fromDom(doc.documentElement), container);
  11594. var onTouch = bind$3(container, 'touchstart', function (event) {
  11595. event.prevent();
  11596. resume$1(win, frame);
  11597. clear();
  11598. });
  11599. var make = function (rectangle) {
  11600. var span = SugarElement.fromTag('span');
  11601. add$3(span, [
  11602. resolve('layer-editor'),
  11603. resolve('unfocused-selection')
  11604. ]);
  11605. setAll$1(span, {
  11606. left: rectangle.left + 'px',
  11607. top: rectangle.top + 'px',
  11608. width: rectangle.width + 'px',
  11609. height: rectangle.height + 'px'
  11610. });
  11611. return span;
  11612. };
  11613. var update = function () {
  11614. clear();
  11615. var rectangles = getRectangles(win);
  11616. var spans = map(rectangles, make);
  11617. append$1(container, spans);
  11618. };
  11619. var clear = function () {
  11620. empty(container);
  11621. };
  11622. var destroy = function () {
  11623. onTouch.unbind();
  11624. remove(container);
  11625. };
  11626. var isActive = function () {
  11627. return children(container).length > 0;
  11628. };
  11629. return {
  11630. update: update,
  11631. isActive: isActive,
  11632. destroy: destroy,
  11633. clear: clear
  11634. };
  11635. }
  11636. var exports$1 = {}, module = { exports: exports$1 };
  11637. (function (define, exports, module, require) {
  11638. (function (f) {
  11639. if (typeof exports === 'object' && typeof module !== 'undefined') {
  11640. module.exports = f();
  11641. } else if (typeof define === 'function' && define.amd) {
  11642. define([], f);
  11643. } else {
  11644. var g;
  11645. if (typeof window !== 'undefined') {
  11646. g = window;
  11647. } else if (typeof global !== 'undefined') {
  11648. g = global;
  11649. } else if (typeof self !== 'undefined') {
  11650. g = self;
  11651. } else {
  11652. g = this;
  11653. }
  11654. g.EphoxContactWrapper = f();
  11655. }
  11656. }(function () {
  11657. return function () {
  11658. function r(e, n, t) {
  11659. function o(i, f) {
  11660. if (!n[i]) {
  11661. if (!e[i]) {
  11662. var c = 'function' == typeof require && require;
  11663. if (!f && c)
  11664. return c(i, !0);
  11665. if (u)
  11666. return u(i, !0);
  11667. var a = new Error('Cannot find module \'' + i + '\'');
  11668. throw a.code = 'MODULE_NOT_FOUND', a;
  11669. }
  11670. var p = n[i] = { exports: {} };
  11671. e[i][0].call(p.exports, function (r) {
  11672. var n = e[i][1][r];
  11673. return o(n || r);
  11674. }, p, p.exports, r, e, n, t);
  11675. }
  11676. return n[i].exports;
  11677. }
  11678. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  11679. o(t[i]);
  11680. return o;
  11681. }
  11682. return r;
  11683. }()({
  11684. 1: [
  11685. function (require, module, exports) {
  11686. var process = module.exports = {};
  11687. var cachedSetTimeout;
  11688. var cachedClearTimeout;
  11689. function defaultSetTimout() {
  11690. throw new Error('setTimeout has not been defined');
  11691. }
  11692. function defaultClearTimeout() {
  11693. throw new Error('clearTimeout has not been defined');
  11694. }
  11695. (function () {
  11696. try {
  11697. if (typeof setTimeout === 'function') {
  11698. cachedSetTimeout = setTimeout;
  11699. } else {
  11700. cachedSetTimeout = defaultSetTimout;
  11701. }
  11702. } catch (e) {
  11703. cachedSetTimeout = defaultSetTimout;
  11704. }
  11705. try {
  11706. if (typeof clearTimeout === 'function') {
  11707. cachedClearTimeout = clearTimeout;
  11708. } else {
  11709. cachedClearTimeout = defaultClearTimeout;
  11710. }
  11711. } catch (e) {
  11712. cachedClearTimeout = defaultClearTimeout;
  11713. }
  11714. }());
  11715. function runTimeout(fun) {
  11716. if (cachedSetTimeout === setTimeout) {
  11717. return setTimeout(fun, 0);
  11718. }
  11719. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11720. cachedSetTimeout = setTimeout;
  11721. return setTimeout(fun, 0);
  11722. }
  11723. try {
  11724. return cachedSetTimeout(fun, 0);
  11725. } catch (e) {
  11726. try {
  11727. return cachedSetTimeout.call(null, fun, 0);
  11728. } catch (e) {
  11729. return cachedSetTimeout.call(this, fun, 0);
  11730. }
  11731. }
  11732. }
  11733. function runClearTimeout(marker) {
  11734. if (cachedClearTimeout === clearTimeout) {
  11735. return clearTimeout(marker);
  11736. }
  11737. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11738. cachedClearTimeout = clearTimeout;
  11739. return clearTimeout(marker);
  11740. }
  11741. try {
  11742. return cachedClearTimeout(marker);
  11743. } catch (e) {
  11744. try {
  11745. return cachedClearTimeout.call(null, marker);
  11746. } catch (e) {
  11747. return cachedClearTimeout.call(this, marker);
  11748. }
  11749. }
  11750. }
  11751. var queue = [];
  11752. var draining = false;
  11753. var currentQueue;
  11754. var queueIndex = -1;
  11755. function cleanUpNextTick() {
  11756. if (!draining || !currentQueue) {
  11757. return;
  11758. }
  11759. draining = false;
  11760. if (currentQueue.length) {
  11761. queue = currentQueue.concat(queue);
  11762. } else {
  11763. queueIndex = -1;
  11764. }
  11765. if (queue.length) {
  11766. drainQueue();
  11767. }
  11768. }
  11769. function drainQueue() {
  11770. if (draining) {
  11771. return;
  11772. }
  11773. var timeout = runTimeout(cleanUpNextTick);
  11774. draining = true;
  11775. var len = queue.length;
  11776. while (len) {
  11777. currentQueue = queue;
  11778. queue = [];
  11779. while (++queueIndex < len) {
  11780. if (currentQueue) {
  11781. currentQueue[queueIndex].run();
  11782. }
  11783. }
  11784. queueIndex = -1;
  11785. len = queue.length;
  11786. }
  11787. currentQueue = null;
  11788. draining = false;
  11789. runClearTimeout(timeout);
  11790. }
  11791. process.nextTick = function (fun) {
  11792. var args = new Array(arguments.length - 1);
  11793. if (arguments.length > 1) {
  11794. for (var i = 1; i < arguments.length; i++) {
  11795. args[i - 1] = arguments[i];
  11796. }
  11797. }
  11798. queue.push(new Item(fun, args));
  11799. if (queue.length === 1 && !draining) {
  11800. runTimeout(drainQueue);
  11801. }
  11802. };
  11803. function Item(fun, array) {
  11804. this.fun = fun;
  11805. this.array = array;
  11806. }
  11807. Item.prototype.run = function () {
  11808. this.fun.apply(null, this.array);
  11809. };
  11810. process.title = 'browser';
  11811. process.browser = true;
  11812. process.env = {};
  11813. process.argv = [];
  11814. process.version = '';
  11815. process.versions = {};
  11816. function noop() {
  11817. }
  11818. process.on = noop;
  11819. process.addListener = noop;
  11820. process.once = noop;
  11821. process.off = noop;
  11822. process.removeListener = noop;
  11823. process.removeAllListeners = noop;
  11824. process.emit = noop;
  11825. process.prependListener = noop;
  11826. process.prependOnceListener = noop;
  11827. process.listeners = function (name) {
  11828. return [];
  11829. };
  11830. process.binding = function (name) {
  11831. throw new Error('process.binding is not supported');
  11832. };
  11833. process.cwd = function () {
  11834. return '/';
  11835. };
  11836. process.chdir = function (dir) {
  11837. throw new Error('process.chdir is not supported');
  11838. };
  11839. process.umask = function () {
  11840. return 0;
  11841. };
  11842. },
  11843. {}
  11844. ],
  11845. 2: [
  11846. function (require, module, exports) {
  11847. (function (setImmediate) {
  11848. (function (root) {
  11849. var setTimeoutFunc = setTimeout;
  11850. function noop() {
  11851. }
  11852. function bind(fn, thisArg) {
  11853. return function () {
  11854. fn.apply(thisArg, arguments);
  11855. };
  11856. }
  11857. function Promise(fn) {
  11858. if (typeof this !== 'object')
  11859. throw new TypeError('Promises must be constructed via new');
  11860. if (typeof fn !== 'function')
  11861. throw new TypeError('not a function');
  11862. this._state = 0;
  11863. this._handled = false;
  11864. this._value = undefined;
  11865. this._deferreds = [];
  11866. doResolve(fn, this);
  11867. }
  11868. function handle(self, deferred) {
  11869. while (self._state === 3) {
  11870. self = self._value;
  11871. }
  11872. if (self._state === 0) {
  11873. self._deferreds.push(deferred);
  11874. return;
  11875. }
  11876. self._handled = true;
  11877. Promise._immediateFn(function () {
  11878. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  11879. if (cb === null) {
  11880. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  11881. return;
  11882. }
  11883. var ret;
  11884. try {
  11885. ret = cb(self._value);
  11886. } catch (e) {
  11887. reject(deferred.promise, e);
  11888. return;
  11889. }
  11890. resolve(deferred.promise, ret);
  11891. });
  11892. }
  11893. function resolve(self, newValue) {
  11894. try {
  11895. if (newValue === self)
  11896. throw new TypeError('A promise cannot be resolved with itself.');
  11897. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  11898. var then = newValue.then;
  11899. if (newValue instanceof Promise) {
  11900. self._state = 3;
  11901. self._value = newValue;
  11902. finale(self);
  11903. return;
  11904. } else if (typeof then === 'function') {
  11905. doResolve(bind(then, newValue), self);
  11906. return;
  11907. }
  11908. }
  11909. self._state = 1;
  11910. self._value = newValue;
  11911. finale(self);
  11912. } catch (e) {
  11913. reject(self, e);
  11914. }
  11915. }
  11916. function reject(self, newValue) {
  11917. self._state = 2;
  11918. self._value = newValue;
  11919. finale(self);
  11920. }
  11921. function finale(self) {
  11922. if (self._state === 2 && self._deferreds.length === 0) {
  11923. Promise._immediateFn(function () {
  11924. if (!self._handled) {
  11925. Promise._unhandledRejectionFn(self._value);
  11926. }
  11927. });
  11928. }
  11929. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  11930. handle(self, self._deferreds[i]);
  11931. }
  11932. self._deferreds = null;
  11933. }
  11934. function Handler(onFulfilled, onRejected, promise) {
  11935. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  11936. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  11937. this.promise = promise;
  11938. }
  11939. function doResolve(fn, self) {
  11940. var done = false;
  11941. try {
  11942. fn(function (value) {
  11943. if (done)
  11944. return;
  11945. done = true;
  11946. resolve(self, value);
  11947. }, function (reason) {
  11948. if (done)
  11949. return;
  11950. done = true;
  11951. reject(self, reason);
  11952. });
  11953. } catch (ex) {
  11954. if (done)
  11955. return;
  11956. done = true;
  11957. reject(self, ex);
  11958. }
  11959. }
  11960. Promise.prototype['catch'] = function (onRejected) {
  11961. return this.then(null, onRejected);
  11962. };
  11963. Promise.prototype.then = function (onFulfilled, onRejected) {
  11964. var prom = new this.constructor(noop);
  11965. handle(this, new Handler(onFulfilled, onRejected, prom));
  11966. return prom;
  11967. };
  11968. Promise.all = function (arr) {
  11969. var args = Array.prototype.slice.call(arr);
  11970. return new Promise(function (resolve, reject) {
  11971. if (args.length === 0)
  11972. return resolve([]);
  11973. var remaining = args.length;
  11974. function res(i, val) {
  11975. try {
  11976. if (val && (typeof val === 'object' || typeof val === 'function')) {
  11977. var then = val.then;
  11978. if (typeof then === 'function') {
  11979. then.call(val, function (val) {
  11980. res(i, val);
  11981. }, reject);
  11982. return;
  11983. }
  11984. }
  11985. args[i] = val;
  11986. if (--remaining === 0) {
  11987. resolve(args);
  11988. }
  11989. } catch (ex) {
  11990. reject(ex);
  11991. }
  11992. }
  11993. for (var i = 0; i < args.length; i++) {
  11994. res(i, args[i]);
  11995. }
  11996. });
  11997. };
  11998. Promise.resolve = function (value) {
  11999. if (value && typeof value === 'object' && value.constructor === Promise) {
  12000. return value;
  12001. }
  12002. return new Promise(function (resolve) {
  12003. resolve(value);
  12004. });
  12005. };
  12006. Promise.reject = function (value) {
  12007. return new Promise(function (resolve, reject) {
  12008. reject(value);
  12009. });
  12010. };
  12011. Promise.race = function (values) {
  12012. return new Promise(function (resolve, reject) {
  12013. for (var i = 0, len = values.length; i < len; i++) {
  12014. values[i].then(resolve, reject);
  12015. }
  12016. });
  12017. };
  12018. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  12019. setImmediate(fn);
  12020. } : function (fn) {
  12021. setTimeoutFunc(fn, 0);
  12022. };
  12023. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  12024. if (typeof console !== 'undefined' && console) {
  12025. console.warn('Possible Unhandled Promise Rejection:', err);
  12026. }
  12027. };
  12028. Promise._setImmediateFn = function _setImmediateFn(fn) {
  12029. Promise._immediateFn = fn;
  12030. };
  12031. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  12032. Promise._unhandledRejectionFn = fn;
  12033. };
  12034. if (typeof module !== 'undefined' && module.exports) {
  12035. module.exports = Promise;
  12036. } else if (!root.Promise) {
  12037. root.Promise = Promise;
  12038. }
  12039. }(this));
  12040. }.call(this, require('timers').setImmediate));
  12041. },
  12042. { 'timers': 3 }
  12043. ],
  12044. 3: [
  12045. function (require, module, exports) {
  12046. (function (setImmediate, clearImmediate) {
  12047. var nextTick = require('process/browser.js').nextTick;
  12048. var apply = Function.prototype.apply;
  12049. var slice = Array.prototype.slice;
  12050. var immediateIds = {};
  12051. var nextImmediateId = 0;
  12052. exports.setTimeout = function () {
  12053. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  12054. };
  12055. exports.setInterval = function () {
  12056. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12057. };
  12058. exports.clearTimeout = exports.clearInterval = function (timeout) {
  12059. timeout.close();
  12060. };
  12061. function Timeout(id, clearFn) {
  12062. this._id = id;
  12063. this._clearFn = clearFn;
  12064. }
  12065. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  12066. };
  12067. Timeout.prototype.close = function () {
  12068. this._clearFn.call(window, this._id);
  12069. };
  12070. exports.enroll = function (item, msecs) {
  12071. clearTimeout(item._idleTimeoutId);
  12072. item._idleTimeout = msecs;
  12073. };
  12074. exports.unenroll = function (item) {
  12075. clearTimeout(item._idleTimeoutId);
  12076. item._idleTimeout = -1;
  12077. };
  12078. exports._unrefActive = exports.active = function (item) {
  12079. clearTimeout(item._idleTimeoutId);
  12080. var msecs = item._idleTimeout;
  12081. if (msecs >= 0) {
  12082. item._idleTimeoutId = setTimeout(function onTimeout() {
  12083. if (item._onTimeout)
  12084. item._onTimeout();
  12085. }, msecs);
  12086. }
  12087. };
  12088. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  12089. var id = nextImmediateId++;
  12090. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  12091. immediateIds[id] = true;
  12092. nextTick(function onNextTick() {
  12093. if (immediateIds[id]) {
  12094. if (args) {
  12095. fn.apply(null, args);
  12096. } else {
  12097. fn.call(null);
  12098. }
  12099. exports.clearImmediate(id);
  12100. }
  12101. });
  12102. return id;
  12103. };
  12104. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  12105. delete immediateIds[id];
  12106. };
  12107. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  12108. },
  12109. {
  12110. 'process/browser.js': 1,
  12111. 'timers': 3
  12112. }
  12113. ],
  12114. 4: [
  12115. function (require, module, exports) {
  12116. var promisePolyfill = require('promise-polyfill');
  12117. var Global = function () {
  12118. if (typeof window !== 'undefined') {
  12119. return window;
  12120. } else {
  12121. return Function('return this;')();
  12122. }
  12123. }();
  12124. module.exports = { boltExport: Global.Promise || promisePolyfill };
  12125. },
  12126. { 'promise-polyfill': 2 }
  12127. ]
  12128. }, {}, [4])(4);
  12129. }));
  12130. }(undefined, exports$1, module, undefined));
  12131. var Promise$1 = module.exports.boltExport;
  12132. var nu$7 = function (baseFn) {
  12133. var data = Optional.none();
  12134. var callbacks = [];
  12135. var map = function (f) {
  12136. return nu$7(function (nCallback) {
  12137. get(function (data) {
  12138. nCallback(f(data));
  12139. });
  12140. });
  12141. };
  12142. var get = function (nCallback) {
  12143. if (isReady()) {
  12144. call(nCallback);
  12145. } else {
  12146. callbacks.push(nCallback);
  12147. }
  12148. };
  12149. var set = function (x) {
  12150. if (!isReady()) {
  12151. data = Optional.some(x);
  12152. run(callbacks);
  12153. callbacks = [];
  12154. }
  12155. };
  12156. var isReady = function () {
  12157. return data.isSome();
  12158. };
  12159. var run = function (cbs) {
  12160. each(cbs, call);
  12161. };
  12162. var call = function (cb) {
  12163. data.each(function (x) {
  12164. setTimeout(function () {
  12165. cb(x);
  12166. }, 0);
  12167. });
  12168. };
  12169. baseFn(set);
  12170. return {
  12171. get: get,
  12172. map: map,
  12173. isReady: isReady
  12174. };
  12175. };
  12176. var pure$1 = function (a) {
  12177. return nu$7(function (callback) {
  12178. callback(a);
  12179. });
  12180. };
  12181. var LazyValue = {
  12182. nu: nu$7,
  12183. pure: pure$1
  12184. };
  12185. var errorReporter = function (err) {
  12186. setTimeout(function () {
  12187. throw err;
  12188. }, 0);
  12189. };
  12190. var make$4 = function (run) {
  12191. var get = function (callback) {
  12192. run().then(callback, errorReporter);
  12193. };
  12194. var map = function (fab) {
  12195. return make$4(function () {
  12196. return run().then(fab);
  12197. });
  12198. };
  12199. var bind = function (aFutureB) {
  12200. return make$4(function () {
  12201. return run().then(function (v) {
  12202. return aFutureB(v).toPromise();
  12203. });
  12204. });
  12205. };
  12206. var anonBind = function (futureB) {
  12207. return make$4(function () {
  12208. return run().then(function () {
  12209. return futureB.toPromise();
  12210. });
  12211. });
  12212. };
  12213. var toLazy = function () {
  12214. return LazyValue.nu(get);
  12215. };
  12216. var toCached = function () {
  12217. var cache = null;
  12218. return make$4(function () {
  12219. if (cache === null) {
  12220. cache = run();
  12221. }
  12222. return cache;
  12223. });
  12224. };
  12225. var toPromise = run;
  12226. return {
  12227. map: map,
  12228. bind: bind,
  12229. anonBind: anonBind,
  12230. toLazy: toLazy,
  12231. toCached: toCached,
  12232. toPromise: toPromise,
  12233. get: get
  12234. };
  12235. };
  12236. var nu$8 = function (baseFn) {
  12237. return make$4(function () {
  12238. return new Promise$1(baseFn);
  12239. });
  12240. };
  12241. var pure$2 = function (a) {
  12242. return make$4(function () {
  12243. return Promise$1.resolve(a);
  12244. });
  12245. };
  12246. var Future = {
  12247. nu: nu$8,
  12248. pure: pure$2
  12249. };
  12250. var adjust = function (value, destination, amount) {
  12251. if (Math.abs(value - destination) <= amount) {
  12252. return Optional.none();
  12253. } else if (value < destination) {
  12254. return Optional.some(value + amount);
  12255. } else {
  12256. return Optional.some(value - amount);
  12257. }
  12258. };
  12259. var create$5 = function () {
  12260. var interval = null;
  12261. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  12262. var finished = false;
  12263. var finish = function (v) {
  12264. finished = true;
  12265. doFinish(v);
  12266. };
  12267. global$4.clearInterval(interval);
  12268. var abort = function (v) {
  12269. global$4.clearInterval(interval);
  12270. finish(v);
  12271. };
  12272. interval = global$4.setInterval(function () {
  12273. var value = getCurrent();
  12274. adjust(value, destination, amount).fold(function () {
  12275. global$4.clearInterval(interval);
  12276. finish(destination);
  12277. }, function (s) {
  12278. increment(s, abort);
  12279. if (!finished) {
  12280. var newValue = getCurrent();
  12281. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  12282. global$4.clearInterval(interval);
  12283. finish(destination);
  12284. }
  12285. }
  12286. });
  12287. }, rate);
  12288. };
  12289. return { animate: animate };
  12290. };
  12291. var findDevice = function (deviceWidth, deviceHeight) {
  12292. var devices = [
  12293. {
  12294. width: 320,
  12295. height: 480,
  12296. keyboard: {
  12297. portrait: 300,
  12298. landscape: 240
  12299. }
  12300. },
  12301. {
  12302. width: 320,
  12303. height: 568,
  12304. keyboard: {
  12305. portrait: 300,
  12306. landscape: 240
  12307. }
  12308. },
  12309. {
  12310. width: 375,
  12311. height: 667,
  12312. keyboard: {
  12313. portrait: 305,
  12314. landscape: 240
  12315. }
  12316. },
  12317. {
  12318. width: 414,
  12319. height: 736,
  12320. keyboard: {
  12321. portrait: 320,
  12322. landscape: 240
  12323. }
  12324. },
  12325. {
  12326. width: 768,
  12327. height: 1024,
  12328. keyboard: {
  12329. portrait: 320,
  12330. landscape: 400
  12331. }
  12332. },
  12333. {
  12334. width: 1024,
  12335. height: 1366,
  12336. keyboard: {
  12337. portrait: 380,
  12338. landscape: 460
  12339. }
  12340. }
  12341. ];
  12342. return findMap(devices, function (device) {
  12343. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  12344. }).getOr({
  12345. portrait: deviceHeight / 5,
  12346. landscape: deviceWidth / 4
  12347. });
  12348. };
  12349. var softKeyboardLimits = function (outerWindow) {
  12350. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  12351. };
  12352. var accountableKeyboardHeight = function (outerWindow) {
  12353. var portrait = get$b(outerWindow).isPortrait();
  12354. var limits = softKeyboardLimits(outerWindow);
  12355. var keyboard = portrait ? limits.portrait : limits.landscape;
  12356. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  12357. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  12358. };
  12359. var getGreenzone = function (socket, dropup) {
  12360. var outerWindow = owner(socket).dom.defaultView;
  12361. var viewportHeight = get$5(socket) + get$5(dropup);
  12362. var acc = accountableKeyboardHeight(outerWindow);
  12363. return viewportHeight - acc;
  12364. };
  12365. var updatePadding = function (contentBody, socket, dropup) {
  12366. var greenzoneHeight = getGreenzone(socket, dropup);
  12367. var deltaHeight = get$5(socket) + get$5(dropup) - greenzoneHeight;
  12368. set$3(contentBody, 'padding-bottom', deltaHeight + 'px');
  12369. };
  12370. var fixture = Adt.generate([
  12371. {
  12372. fixed: [
  12373. 'element',
  12374. 'property',
  12375. 'offsetY'
  12376. ]
  12377. },
  12378. {
  12379. scroller: [
  12380. 'element',
  12381. 'offsetY'
  12382. ]
  12383. }
  12384. ]);
  12385. var yFixedData = 'data-' + resolve('position-y-fixed');
  12386. var yFixedProperty = 'data-' + resolve('y-property');
  12387. var yScrollingData = 'data-' + resolve('scrolling');
  12388. var windowSizeData = 'data-' + resolve('last-window-height');
  12389. var getYFixedData = function (element) {
  12390. return safeParse(element, yFixedData);
  12391. };
  12392. var getYFixedProperty = function (element) {
  12393. return get$1(element, yFixedProperty);
  12394. };
  12395. var getLastWindowSize = function (element) {
  12396. return safeParse(element, windowSizeData);
  12397. };
  12398. var classifyFixed = function (element, offsetY) {
  12399. var prop = getYFixedProperty(element);
  12400. return fixture.fixed(element, prop, offsetY);
  12401. };
  12402. var classifyScrolling = function (element, offsetY) {
  12403. return fixture.scroller(element, offsetY);
  12404. };
  12405. var classify = function (element) {
  12406. var offsetY = getYFixedData(element);
  12407. var classifier = get$1(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  12408. return classifier(element, offsetY);
  12409. };
  12410. var findFixtures = function (container) {
  12411. var candidates = descendants(container, '[' + yFixedData + ']');
  12412. return map(candidates, classify);
  12413. };
  12414. var takeoverToolbar = function (toolbar) {
  12415. var oldToolbarStyle = get$1(toolbar, 'style');
  12416. setAll$1(toolbar, {
  12417. position: 'absolute',
  12418. top: '0px'
  12419. });
  12420. set(toolbar, yFixedData, '0px');
  12421. set(toolbar, yFixedProperty, 'top');
  12422. var restore = function () {
  12423. set(toolbar, 'style', oldToolbarStyle || '');
  12424. remove$1(toolbar, yFixedData);
  12425. remove$1(toolbar, yFixedProperty);
  12426. };
  12427. return { restore: restore };
  12428. };
  12429. var takeoverViewport = function (toolbarHeight, height, viewport) {
  12430. var oldViewportStyle = get$1(viewport, 'style');
  12431. register(viewport);
  12432. setAll$1(viewport, {
  12433. position: 'absolute',
  12434. height: height + 'px',
  12435. width: '100%',
  12436. top: toolbarHeight + 'px'
  12437. });
  12438. set(viewport, yFixedData, toolbarHeight + 'px');
  12439. set(viewport, yScrollingData, 'true');
  12440. set(viewport, yFixedProperty, 'top');
  12441. var restore = function () {
  12442. deregister(viewport);
  12443. set(viewport, 'style', oldViewportStyle || '');
  12444. remove$1(viewport, yFixedData);
  12445. remove$1(viewport, yScrollingData);
  12446. remove$1(viewport, yFixedProperty);
  12447. };
  12448. return { restore: restore };
  12449. };
  12450. var takeoverDropup = function (dropup) {
  12451. var oldDropupStyle = get$1(dropup, 'style');
  12452. setAll$1(dropup, {
  12453. position: 'absolute',
  12454. bottom: '0px'
  12455. });
  12456. set(dropup, yFixedData, '0px');
  12457. set(dropup, yFixedProperty, 'bottom');
  12458. var restore = function () {
  12459. set(dropup, 'style', oldDropupStyle || '');
  12460. remove$1(dropup, yFixedData);
  12461. remove$1(dropup, yFixedProperty);
  12462. };
  12463. return { restore: restore };
  12464. };
  12465. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12466. var outerWindow = owner(viewport).dom.defaultView;
  12467. var winH = outerWindow.innerHeight;
  12468. set(viewport, windowSizeData, winH + 'px');
  12469. return winH - toolbarHeight - dropupHeight;
  12470. };
  12471. var takeover$1 = function (viewport, contentBody, toolbar, dropup) {
  12472. var outerWindow = owner(viewport).dom.defaultView;
  12473. var toolbarSetup = takeoverToolbar(toolbar);
  12474. var toolbarHeight = get$5(toolbar);
  12475. var dropupHeight = get$5(dropup);
  12476. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12477. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12478. var dropupSetup = takeoverDropup(dropup);
  12479. var isActive = true;
  12480. var restore = function () {
  12481. isActive = false;
  12482. toolbarSetup.restore();
  12483. viewportSetup.restore();
  12484. dropupSetup.restore();
  12485. };
  12486. var isExpanding = function () {
  12487. var currentWinHeight = outerWindow.innerHeight;
  12488. var lastWinHeight = getLastWindowSize(viewport);
  12489. return currentWinHeight > lastWinHeight;
  12490. };
  12491. var refresh = function () {
  12492. if (isActive) {
  12493. var newToolbarHeight = get$5(toolbar);
  12494. var dropupHeight_1 = get$5(dropup);
  12495. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12496. set(viewport, yFixedData, newToolbarHeight + 'px');
  12497. set$3(viewport, 'height', newHeight + 'px');
  12498. updatePadding(contentBody, viewport, dropup);
  12499. }
  12500. };
  12501. var setViewportOffset = function (newYOffset) {
  12502. var offsetPx = newYOffset + 'px';
  12503. set(viewport, yFixedData, offsetPx);
  12504. refresh();
  12505. };
  12506. updatePadding(contentBody, viewport, dropup);
  12507. return {
  12508. setViewportOffset: setViewportOffset,
  12509. isExpanding: isExpanding,
  12510. isShrinking: not(isExpanding),
  12511. refresh: refresh,
  12512. restore: restore
  12513. };
  12514. };
  12515. var animator = create$5();
  12516. var ANIMATION_STEP = 15;
  12517. var NUM_TOP_ANIMATION_FRAMES = 10;
  12518. var ANIMATION_RATE = 10;
  12519. var lastScroll = 'data-' + resolve('last-scroll-top');
  12520. var getTop = function (element) {
  12521. var raw = getRaw(element, 'top').getOr('0');
  12522. return parseInt(raw, 10);
  12523. };
  12524. var getScrollTop = function (element) {
  12525. return parseInt(element.dom.scrollTop, 10);
  12526. };
  12527. var moveScrollAndTop = function (element, destination, finalTop) {
  12528. return Future.nu(function (callback) {
  12529. var getCurrent = curry(getScrollTop, element);
  12530. var update = function (newScroll) {
  12531. element.dom.scrollTop = newScroll;
  12532. set$3(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12533. };
  12534. var finish = function () {
  12535. element.dom.scrollTop = destination;
  12536. set$3(element, 'top', finalTop + 'px');
  12537. callback(destination);
  12538. };
  12539. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12540. });
  12541. };
  12542. var moveOnlyScroll = function (element, destination) {
  12543. return Future.nu(function (callback) {
  12544. var getCurrent = curry(getScrollTop, element);
  12545. set(element, lastScroll, getCurrent());
  12546. var update = function (newScroll, abort) {
  12547. var previous = safeParse(element, lastScroll);
  12548. if (previous !== element.dom.scrollTop) {
  12549. abort(element.dom.scrollTop);
  12550. } else {
  12551. element.dom.scrollTop = newScroll;
  12552. set(element, lastScroll, newScroll);
  12553. }
  12554. };
  12555. var finish = function () {
  12556. element.dom.scrollTop = destination;
  12557. set(element, lastScroll, destination);
  12558. callback(destination);
  12559. };
  12560. var distance = Math.abs(destination - getCurrent());
  12561. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12562. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12563. });
  12564. };
  12565. var moveOnlyTop = function (element, destination) {
  12566. return Future.nu(function (callback) {
  12567. var getCurrent = curry(getTop, element);
  12568. var update = function (newTop) {
  12569. set$3(element, 'top', newTop + 'px');
  12570. };
  12571. var finish = function () {
  12572. update(destination);
  12573. callback(destination);
  12574. };
  12575. var distance = Math.abs(destination - getCurrent());
  12576. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12577. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12578. });
  12579. };
  12580. var updateTop = function (element, amount) {
  12581. var newTop = amount + getYFixedData(element) + 'px';
  12582. set$3(element, 'top', newTop);
  12583. };
  12584. var moveWindowScroll = function (toolbar, viewport, destY) {
  12585. var outerWindow = owner(toolbar).dom.defaultView;
  12586. return Future.nu(function (callback) {
  12587. updateTop(toolbar, destY);
  12588. updateTop(viewport, destY);
  12589. outerWindow.scrollTo(0, destY);
  12590. callback(destY);
  12591. });
  12592. };
  12593. function BackgroundActivity (doAction) {
  12594. var action = Cell(LazyValue.pure({}));
  12595. var start = function (value) {
  12596. var future = LazyValue.nu(function (callback) {
  12597. return doAction(value).get(callback);
  12598. });
  12599. action.set(future);
  12600. };
  12601. var idle = function (g) {
  12602. action.get().get(function () {
  12603. g();
  12604. });
  12605. };
  12606. return {
  12607. start: start,
  12608. idle: idle
  12609. };
  12610. }
  12611. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12612. var greenzone = getGreenzone(socket, dropup);
  12613. var refreshCursor = curry(refresh$1, cWin);
  12614. if (top > greenzone || bottom > greenzone) {
  12615. moveOnlyScroll(socket, socket.dom.scrollTop - greenzone + bottom).get(refreshCursor);
  12616. } else if (top < 0) {
  12617. moveOnlyScroll(socket, socket.dom.scrollTop + top).get(refreshCursor);
  12618. }
  12619. };
  12620. var par = function (asyncValues, nu) {
  12621. return nu(function (callback) {
  12622. var r = [];
  12623. var count = 0;
  12624. var cb = function (i) {
  12625. return function (value) {
  12626. r[i] = value;
  12627. count++;
  12628. if (count >= asyncValues.length) {
  12629. callback(r);
  12630. }
  12631. };
  12632. };
  12633. if (asyncValues.length === 0) {
  12634. callback([]);
  12635. } else {
  12636. each(asyncValues, function (asyncValue, i) {
  12637. asyncValue.get(cb(i));
  12638. });
  12639. }
  12640. });
  12641. };
  12642. var par$1 = function (futures) {
  12643. return par(futures, Future.nu);
  12644. };
  12645. var updateFixed = function (element, property, winY, offsetY) {
  12646. var destination = winY + offsetY;
  12647. set$3(element, property, destination + 'px');
  12648. return Future.pure(offsetY);
  12649. };
  12650. var updateScrollingFixed = function (element, winY, offsetY) {
  12651. var destTop = winY + offsetY;
  12652. var oldProp = getRaw(element, 'top').getOr(offsetY);
  12653. var delta = destTop - parseInt(oldProp, 10);
  12654. var destScroll = element.dom.scrollTop + delta;
  12655. return moveScrollAndTop(element, destScroll, destTop);
  12656. };
  12657. var updateFixture = function (fixture, winY) {
  12658. return fixture.fold(function (element, property, offsetY) {
  12659. return updateFixed(element, property, winY, offsetY);
  12660. }, function (element, offsetY) {
  12661. return updateScrollingFixed(element, winY, offsetY);
  12662. });
  12663. };
  12664. var updatePositions = function (container, winY) {
  12665. var fixtures = findFixtures(container);
  12666. var updates = map(fixtures, function (fixture) {
  12667. return updateFixture(fixture, winY);
  12668. });
  12669. return par$1(updates);
  12670. };
  12671. var VIEW_MARGIN = 5;
  12672. var register$2 = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  12673. var scroller = BackgroundActivity(function (y) {
  12674. return moveWindowScroll(toolstrip, socket, y);
  12675. });
  12676. var scrollBounds = function () {
  12677. var rects = getRectangles(cWin);
  12678. return Optional.from(rects[0]).bind(function (rect) {
  12679. var viewTop = rect.top - socket.dom.scrollTop;
  12680. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  12681. return outside ? Optional.some({
  12682. top: viewTop,
  12683. bottom: viewTop + rect.height
  12684. }) : Optional.none();
  12685. });
  12686. };
  12687. var scrollThrottle = last(function () {
  12688. scroller.idle(function () {
  12689. updatePositions(container, outerWindow.pageYOffset).get(function () {
  12690. var extraScroll = scrollBounds();
  12691. extraScroll.each(function (extra) {
  12692. socket.dom.scrollTop = socket.dom.scrollTop + extra.top;
  12693. });
  12694. scroller.start(0);
  12695. structure.refresh();
  12696. });
  12697. });
  12698. }, 1000);
  12699. var onScroll = bind$3(SugarElement.fromDom(outerWindow), 'scroll', function () {
  12700. if (outerWindow.pageYOffset < 0) {
  12701. return;
  12702. }
  12703. scrollThrottle.throttle();
  12704. });
  12705. updatePositions(container, outerWindow.pageYOffset).get(identity);
  12706. return { unbind: onScroll.unbind };
  12707. };
  12708. var setup$3 = function (bag) {
  12709. var cWin = bag.cWin;
  12710. var ceBody = bag.ceBody;
  12711. var socket = bag.socket;
  12712. var toolstrip = bag.toolstrip;
  12713. var contentElement = bag.contentElement;
  12714. var keyboardType = bag.keyboardType;
  12715. var outerWindow = bag.outerWindow;
  12716. var dropup = bag.dropup;
  12717. var outerBody = bag.outerBody;
  12718. var structure = takeover$1(socket, ceBody, toolstrip, dropup);
  12719. var keyboardModel = keyboardType(outerBody, cWin, body(), contentElement);
  12720. var toEditing = function () {
  12721. keyboardModel.toEditing();
  12722. clearSelection();
  12723. };
  12724. var toReading = function () {
  12725. keyboardModel.toReading();
  12726. };
  12727. var onToolbarTouch = function (_event) {
  12728. keyboardModel.onToolbarTouch();
  12729. };
  12730. var onOrientation = onChange(outerWindow, {
  12731. onChange: noop,
  12732. onReady: structure.refresh
  12733. });
  12734. onOrientation.onAdjustment(function () {
  12735. structure.refresh();
  12736. });
  12737. var onResize = bind$3(SugarElement.fromDom(outerWindow), 'resize', function () {
  12738. if (structure.isExpanding()) {
  12739. structure.refresh();
  12740. }
  12741. });
  12742. var onScroll = register$2(toolstrip, socket, outerBody, outerWindow, structure, cWin);
  12743. var unfocusedSelection = FakeSelection(cWin, contentElement);
  12744. var refreshSelection = function () {
  12745. if (unfocusedSelection.isActive()) {
  12746. unfocusedSelection.update();
  12747. }
  12748. };
  12749. var highlightSelection = function () {
  12750. unfocusedSelection.update();
  12751. };
  12752. var clearSelection = function () {
  12753. unfocusedSelection.clear();
  12754. };
  12755. var scrollIntoView$1 = function (top, bottom) {
  12756. scrollIntoView(cWin, socket, dropup, top, bottom);
  12757. };
  12758. var syncHeight = function () {
  12759. set$3(contentElement, 'height', contentElement.dom.contentWindow.document.body.scrollHeight + 'px');
  12760. };
  12761. var setViewportOffset = function (newYOffset) {
  12762. structure.setViewportOffset(newYOffset);
  12763. moveOnlyTop(socket, newYOffset).get(identity);
  12764. };
  12765. var destroy = function () {
  12766. structure.restore();
  12767. onOrientation.destroy();
  12768. onScroll.unbind();
  12769. onResize.unbind();
  12770. keyboardModel.destroy();
  12771. unfocusedSelection.destroy();
  12772. input$1(body(), blur);
  12773. };
  12774. return {
  12775. toEditing: toEditing,
  12776. toReading: toReading,
  12777. onToolbarTouch: onToolbarTouch,
  12778. refreshSelection: refreshSelection,
  12779. clearSelection: clearSelection,
  12780. highlightSelection: highlightSelection,
  12781. scrollIntoView: scrollIntoView$1,
  12782. updateToolbarPadding: noop,
  12783. setViewportOffset: setViewportOffset,
  12784. syncHeight: syncHeight,
  12785. refreshStructure: structure.refresh,
  12786. destroy: destroy
  12787. };
  12788. };
  12789. var create$6 = function (platform, mask) {
  12790. var meta = tag();
  12791. var priorState = value$2();
  12792. var scrollEvents = value$2();
  12793. var iosApi = api$2();
  12794. var iosEvents = api$2();
  12795. var enter = function () {
  12796. mask.hide();
  12797. var doc = SugarElement.fromDom(document);
  12798. getActiveApi(platform.editor).each(function (editorApi) {
  12799. priorState.set({
  12800. socketHeight: getRaw(platform.socket, 'height'),
  12801. iframeHeight: getRaw(editorApi.frame, 'height'),
  12802. outerScroll: document.body.scrollTop
  12803. });
  12804. scrollEvents.set({ exclusives: exclusive(doc, '.' + scrollable) });
  12805. add$2(platform.container, resolve('fullscreen-maximized'));
  12806. clobberStyles(platform.container, editorApi.body);
  12807. meta.maximize();
  12808. set$3(platform.socket, 'overflow', 'scroll');
  12809. set$3(platform.socket, '-webkit-overflow-scrolling', 'touch');
  12810. focus$1(editorApi.body);
  12811. iosApi.set(setup$3({
  12812. cWin: editorApi.win,
  12813. ceBody: editorApi.body,
  12814. socket: platform.socket,
  12815. toolstrip: platform.toolstrip,
  12816. dropup: platform.dropup.element,
  12817. contentElement: editorApi.frame,
  12818. outerBody: platform.body,
  12819. outerWindow: platform.win,
  12820. keyboardType: stubborn
  12821. }));
  12822. iosApi.run(function (api) {
  12823. api.syncHeight();
  12824. });
  12825. iosEvents.set(initEvents$1(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  12826. });
  12827. };
  12828. var exit = function () {
  12829. meta.restore();
  12830. iosEvents.clear();
  12831. iosApi.clear();
  12832. mask.show();
  12833. priorState.on(function (s) {
  12834. s.socketHeight.each(function (h) {
  12835. set$3(platform.socket, 'height', h);
  12836. });
  12837. s.iframeHeight.each(function (h) {
  12838. set$3(platform.editor.getFrame(), 'height', h);
  12839. });
  12840. document.body.scrollTop = s.scrollTop;
  12841. });
  12842. priorState.clear();
  12843. scrollEvents.on(function (s) {
  12844. s.exclusives.unbind();
  12845. });
  12846. scrollEvents.clear();
  12847. remove$4(platform.container, resolve('fullscreen-maximized'));
  12848. restoreStyles();
  12849. deregister(platform.toolbar);
  12850. remove$5(platform.socket, 'overflow');
  12851. remove$5(platform.socket, '-webkit-overflow-scrolling');
  12852. blur(platform.editor.getFrame());
  12853. getActiveApi(platform.editor).each(function (editorApi) {
  12854. editorApi.clearSelection();
  12855. });
  12856. };
  12857. var refreshStructure = function () {
  12858. iosApi.run(function (api) {
  12859. api.refreshStructure();
  12860. });
  12861. };
  12862. return {
  12863. enter: enter,
  12864. refreshStructure: refreshStructure,
  12865. exit: exit
  12866. };
  12867. };
  12868. var produce$1 = function (raw) {
  12869. var mobile = asRawOrDie('Getting IosWebapp schema', MobileSchema, raw);
  12870. set$3(mobile.toolstrip, 'width', '100%');
  12871. set$3(mobile.container, 'position', 'relative');
  12872. var onView = function () {
  12873. mobile.setReadOnly(mobile.readOnlyOnInit());
  12874. mode.enter();
  12875. };
  12876. var mask = build$1(sketch$9(onView, mobile.translate));
  12877. mobile.alloy.add(mask);
  12878. var maskApi = {
  12879. show: function () {
  12880. mobile.alloy.add(mask);
  12881. },
  12882. hide: function () {
  12883. mobile.alloy.remove(mask);
  12884. }
  12885. };
  12886. var mode = create$6(mobile, maskApi);
  12887. return {
  12888. setReadOnly: mobile.setReadOnly,
  12889. refreshStructure: mode.refreshStructure,
  12890. enter: mode.enter,
  12891. exit: mode.exit,
  12892. destroy: noop
  12893. };
  12894. };
  12895. function IosRealm (scrollIntoView) {
  12896. var alloy = OuterContainer({ classes: [resolve('ios-container')] });
  12897. var toolbar = ScrollingToolbar();
  12898. var webapp = api$2();
  12899. var switchToEdit = makeEditSwitch(webapp);
  12900. var socket = makeSocket();
  12901. var dropup = build$2(function () {
  12902. webapp.run(function (w) {
  12903. w.refreshStructure();
  12904. });
  12905. }, scrollIntoView);
  12906. alloy.add(toolbar.wrapper);
  12907. alloy.add(socket);
  12908. alloy.add(dropup.component);
  12909. var setToolbarGroups = function (rawGroups) {
  12910. var groups = toolbar.createGroups(rawGroups);
  12911. toolbar.setGroups(groups);
  12912. };
  12913. var setContextToolbar = function (rawGroups) {
  12914. var groups = toolbar.createGroups(rawGroups);
  12915. toolbar.setContextToolbar(groups);
  12916. };
  12917. var focusToolbar = function () {
  12918. toolbar.focus();
  12919. };
  12920. var restoreToolbar = function () {
  12921. toolbar.restoreToolbar();
  12922. };
  12923. var init = function (spec) {
  12924. webapp.set(produce$1(spec));
  12925. };
  12926. var exit = function () {
  12927. webapp.run(function (w) {
  12928. Replacing.remove(socket, switchToEdit);
  12929. w.exit();
  12930. });
  12931. };
  12932. var updateMode$1 = function (readOnly) {
  12933. updateMode(socket, switchToEdit, readOnly, alloy.root);
  12934. };
  12935. return {
  12936. system: alloy,
  12937. element: alloy.element,
  12938. init: init,
  12939. exit: exit,
  12940. setToolbarGroups: setToolbarGroups,
  12941. setContextToolbar: setContextToolbar,
  12942. focusToolbar: focusToolbar,
  12943. restoreToolbar: restoreToolbar,
  12944. updateMode: updateMode$1,
  12945. socket: socket,
  12946. dropup: dropup
  12947. };
  12948. }
  12949. var global$5 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12950. var derive$3 = function (editor) {
  12951. var base = Optional.from(getSkinUrl(editor)).fold(function () {
  12952. return global$5.baseURL + '/skins/ui/oxide';
  12953. }, function (url) {
  12954. return url;
  12955. });
  12956. return {
  12957. content: base + '/content.mobile.min.css',
  12958. ui: base + '/skin.mobile.min.css'
  12959. };
  12960. };
  12961. var fireChange = function (realm, command, state) {
  12962. realm.system.broadcastOn([formatChanged], {
  12963. command: command,
  12964. state: state
  12965. });
  12966. };
  12967. var init$5 = function (realm, editor) {
  12968. var allFormats = keys(editor.formatter.get());
  12969. each(allFormats, function (command) {
  12970. editor.formatter.formatChanged(command, function (state) {
  12971. fireChange(realm, command, state);
  12972. });
  12973. });
  12974. each([
  12975. 'ul',
  12976. 'ol'
  12977. ], function (command) {
  12978. editor.selection.selectorChanged(command, function (state, _data) {
  12979. fireChange(realm, command, state);
  12980. });
  12981. });
  12982. };
  12983. var fireSkinLoaded = function (editor) {
  12984. return function () {
  12985. var done = function () {
  12986. editor._skinLoaded = true;
  12987. editor.fire('SkinLoaded');
  12988. };
  12989. if (editor.initialized) {
  12990. done();
  12991. } else {
  12992. editor.on('init', done);
  12993. }
  12994. };
  12995. };
  12996. var READING = 'toReading';
  12997. var EDITING = 'toEditing';
  12998. var renderMobileTheme = function (editor) {
  12999. var renderUI = function () {
  13000. var targetNode = editor.getElement();
  13001. var cssUrls = derive$3(editor);
  13002. if (isSkinDisabled(editor) === false) {
  13003. var styleSheetLoader_1 = global$1.DOM.styleSheetLoader;
  13004. editor.contentCSS.push(cssUrls.content);
  13005. styleSheetLoader_1.load(cssUrls.ui, fireSkinLoaded(editor));
  13006. editor.on('remove', function () {
  13007. return styleSheetLoader_1.unload(cssUrls.ui);
  13008. });
  13009. } else {
  13010. fireSkinLoaded(editor)();
  13011. }
  13012. var doScrollIntoView = function () {
  13013. editor.fire('ScrollIntoView');
  13014. };
  13015. var realm = detect$3().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  13016. var original = SugarElement.fromDom(targetNode);
  13017. attachSystemAfter(original, realm.system);
  13018. var findFocusIn = function (elem) {
  13019. return search(elem).bind(function (focused) {
  13020. return realm.system.getByDom(focused).toOptional();
  13021. });
  13022. };
  13023. var outerWindow = targetNode.ownerDocument.defaultView;
  13024. var orientation = onChange(outerWindow, {
  13025. onChange: function () {
  13026. var alloy = realm.system;
  13027. alloy.broadcastOn([orientationChanged], { width: getActualWidth(outerWindow) });
  13028. },
  13029. onReady: noop
  13030. });
  13031. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  13032. if (ro === false) {
  13033. editor.selection.collapse();
  13034. }
  13035. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  13036. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  13037. editor.setMode(ro === true ? 'readonly' : 'design');
  13038. editor.fire(ro === true ? READING : EDITING);
  13039. realm.updateMode(ro);
  13040. };
  13041. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  13042. var dynamic = dynamicGroup.get();
  13043. var toolbars = {
  13044. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  13045. main: dynamic.backToMask.concat(mainGroups.get())
  13046. };
  13047. return toolbars;
  13048. };
  13049. var bindHandler = function (label, handler) {
  13050. editor.on(label, handler);
  13051. return {
  13052. unbind: function () {
  13053. editor.off(label);
  13054. }
  13055. };
  13056. };
  13057. editor.on('init', function () {
  13058. realm.init({
  13059. editor: {
  13060. getFrame: function () {
  13061. return SugarElement.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  13062. },
  13063. onDomChanged: function () {
  13064. return { unbind: noop };
  13065. },
  13066. onToReading: function (handler) {
  13067. return bindHandler(READING, handler);
  13068. },
  13069. onToEditing: function (handler) {
  13070. return bindHandler(EDITING, handler);
  13071. },
  13072. onScrollToCursor: function (handler) {
  13073. editor.on('ScrollIntoView', function (tinyEvent) {
  13074. handler(tinyEvent);
  13075. });
  13076. var unbind = function () {
  13077. editor.off('ScrollIntoView');
  13078. orientation.destroy();
  13079. };
  13080. return { unbind: unbind };
  13081. },
  13082. onTouchToolstrip: function () {
  13083. hideDropup();
  13084. },
  13085. onTouchContent: function () {
  13086. var toolbar = SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar')));
  13087. findFocusIn(toolbar).each(emitExecute);
  13088. realm.restoreToolbar();
  13089. hideDropup();
  13090. },
  13091. onTapContent: function (evt) {
  13092. var target = evt.target;
  13093. if (name(target) === 'img') {
  13094. editor.selection.select(target.dom);
  13095. evt.kill();
  13096. } else if (name(target) === 'a') {
  13097. var component = realm.system.getByDom(SugarElement.fromDom(editor.editorContainer));
  13098. component.each(function (container) {
  13099. if (Swapping.isAlpha(container)) {
  13100. openLink(target.dom);
  13101. }
  13102. });
  13103. }
  13104. }
  13105. },
  13106. container: SugarElement.fromDom(editor.editorContainer),
  13107. socket: SugarElement.fromDom(editor.contentAreaContainer),
  13108. toolstrip: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolstrip'))),
  13109. toolbar: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))),
  13110. dropup: realm.dropup,
  13111. alloy: realm.system,
  13112. translate: noop,
  13113. setReadOnly: function (ro) {
  13114. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  13115. },
  13116. readOnlyOnInit: function () {
  13117. return readOnlyOnInit();
  13118. }
  13119. });
  13120. var hideDropup = function () {
  13121. realm.dropup.disappear(function () {
  13122. realm.system.broadcastOn([dropupDismissed], {});
  13123. });
  13124. };
  13125. var backToMaskGroup = {
  13126. label: 'The first group',
  13127. scrollable: false,
  13128. items: [forToolbar('back', function () {
  13129. editor.selection.collapse();
  13130. realm.exit();
  13131. }, {}, editor)]
  13132. };
  13133. var backToReadOnlyGroup = {
  13134. label: 'Back to read only',
  13135. scrollable: false,
  13136. items: [forToolbar('readonly-back', function () {
  13137. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  13138. }, {}, editor)]
  13139. };
  13140. var readOnlyGroup = {
  13141. label: 'The read only mode group',
  13142. scrollable: true,
  13143. items: []
  13144. };
  13145. var features = setup(realm, editor);
  13146. var items = detect$4(editor, features);
  13147. var actionGroup = {
  13148. label: 'the action group',
  13149. scrollable: true,
  13150. items: items
  13151. };
  13152. var extraGroup = {
  13153. label: 'The extra group',
  13154. scrollable: false,
  13155. items: []
  13156. };
  13157. var mainGroups = Cell([
  13158. actionGroup,
  13159. extraGroup
  13160. ]);
  13161. var readOnlyGroups = Cell([
  13162. readOnlyGroup,
  13163. extraGroup
  13164. ]);
  13165. var dynamicGroup = Cell({
  13166. backToMask: [backToMaskGroup],
  13167. backToReadOnly: [backToReadOnlyGroup]
  13168. });
  13169. init$5(realm, editor);
  13170. });
  13171. editor.on('remove', function () {
  13172. realm.exit();
  13173. });
  13174. editor.on('detach', function () {
  13175. detachSystem(realm.system);
  13176. realm.system.destroy();
  13177. });
  13178. return {
  13179. iframeContainer: realm.socket.element.dom,
  13180. editorContainer: realm.element.dom
  13181. };
  13182. };
  13183. return {
  13184. getNotificationManagerImpl: function () {
  13185. return {
  13186. open: constant({
  13187. progressBar: { value: noop },
  13188. close: noop,
  13189. text: noop,
  13190. getEl: constant(null),
  13191. moveTo: noop,
  13192. moveRel: noop,
  13193. settings: {}
  13194. }),
  13195. close: noop,
  13196. reposition: noop,
  13197. getArgs: constant({})
  13198. };
  13199. },
  13200. renderUI: renderUI
  13201. };
  13202. };
  13203. function Theme () {
  13204. global$2.add('mobile', renderMobileTheme);
  13205. }
  13206. Theme();
  13207. }());