theme.js 454 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809
  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.2.0 (2020-02-13)
  8. */
  9. (function (domGlobals) {
  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 constant = function (value) {
  55. return function () {
  56. return value;
  57. };
  58. };
  59. var identity = function (x) {
  60. return x;
  61. };
  62. function curry(fn) {
  63. var initialArgs = [];
  64. for (var _i = 1; _i < arguments.length; _i++) {
  65. initialArgs[_i - 1] = arguments[_i];
  66. }
  67. return function () {
  68. var restArgs = [];
  69. for (var _i = 0; _i < arguments.length; _i++) {
  70. restArgs[_i] = arguments[_i];
  71. }
  72. var all = initialArgs.concat(restArgs);
  73. return fn.apply(null, all);
  74. };
  75. }
  76. var not = function (f) {
  77. return function () {
  78. var args = [];
  79. for (var _i = 0; _i < arguments.length; _i++) {
  80. args[_i] = arguments[_i];
  81. }
  82. return !f.apply(null, args);
  83. };
  84. };
  85. var die = function (msg) {
  86. return function () {
  87. throw new Error(msg);
  88. };
  89. };
  90. var apply = function (f) {
  91. return f();
  92. };
  93. var never = constant(false);
  94. var always = constant(true);
  95. var none = function () {
  96. return NONE;
  97. };
  98. var NONE = function () {
  99. var eq = function (o) {
  100. return o.isNone();
  101. };
  102. var call = function (thunk) {
  103. return thunk();
  104. };
  105. var id = function (n) {
  106. return n;
  107. };
  108. var me = {
  109. fold: function (n, s) {
  110. return n();
  111. },
  112. is: never,
  113. isSome: never,
  114. isNone: always,
  115. getOr: id,
  116. getOrThunk: call,
  117. getOrDie: function (msg) {
  118. throw new Error(msg || 'error: getOrDie called on none.');
  119. },
  120. getOrNull: constant(null),
  121. getOrUndefined: constant(undefined),
  122. or: id,
  123. orThunk: call,
  124. map: none,
  125. each: noop,
  126. bind: none,
  127. exists: never,
  128. forall: always,
  129. filter: none,
  130. equals: eq,
  131. equals_: eq,
  132. toArray: function () {
  133. return [];
  134. },
  135. toString: constant('none()')
  136. };
  137. if (Object.freeze) {
  138. Object.freeze(me);
  139. }
  140. return me;
  141. }();
  142. var some = function (a) {
  143. var constant_a = constant(a);
  144. var self = function () {
  145. return me;
  146. };
  147. var bind = function (f) {
  148. return f(a);
  149. };
  150. var me = {
  151. fold: function (n, s) {
  152. return s(a);
  153. },
  154. is: function (v) {
  155. return a === v;
  156. },
  157. isSome: always,
  158. isNone: never,
  159. getOr: constant_a,
  160. getOrThunk: constant_a,
  161. getOrDie: constant_a,
  162. getOrNull: constant_a,
  163. getOrUndefined: constant_a,
  164. or: self,
  165. orThunk: self,
  166. map: function (f) {
  167. return some(f(a));
  168. },
  169. each: function (f) {
  170. f(a);
  171. },
  172. bind: bind,
  173. exists: bind,
  174. forall: bind,
  175. filter: function (f) {
  176. return f(a) ? me : NONE;
  177. },
  178. toArray: function () {
  179. return [a];
  180. },
  181. toString: function () {
  182. return 'some(' + a + ')';
  183. },
  184. equals: function (o) {
  185. return o.is(a);
  186. },
  187. equals_: function (o, elementEq) {
  188. return o.fold(never, function (b) {
  189. return elementEq(a, b);
  190. });
  191. }
  192. };
  193. return me;
  194. };
  195. var from = function (value) {
  196. return value === null || value === undefined ? NONE : some(value);
  197. };
  198. var Option = {
  199. some: some,
  200. none: none,
  201. from: from
  202. };
  203. var keys = Object.keys;
  204. var hasOwnProperty = Object.hasOwnProperty;
  205. var each = function (obj, f) {
  206. var props = keys(obj);
  207. for (var k = 0, len = props.length; k < len; k++) {
  208. var i = props[k];
  209. var x = obj[i];
  210. f(x, i);
  211. }
  212. };
  213. var map = function (obj, f) {
  214. return tupleMap(obj, function (x, i) {
  215. return {
  216. k: i,
  217. v: f(x, i)
  218. };
  219. });
  220. };
  221. var tupleMap = function (obj, f) {
  222. var r = {};
  223. each(obj, function (x, i) {
  224. var tuple = f(x, i);
  225. r[tuple.k] = tuple.v;
  226. });
  227. return r;
  228. };
  229. var mapToArray = function (obj, f) {
  230. var r = [];
  231. each(obj, function (value, name) {
  232. r.push(f(value, name));
  233. });
  234. return r;
  235. };
  236. var find = function (obj, pred) {
  237. var props = keys(obj);
  238. for (var k = 0, len = props.length; k < len; k++) {
  239. var i = props[k];
  240. var x = obj[i];
  241. if (pred(x, i, obj)) {
  242. return Option.some(x);
  243. }
  244. }
  245. return Option.none();
  246. };
  247. var values = function (obj) {
  248. return mapToArray(obj, function (v) {
  249. return v;
  250. });
  251. };
  252. var get = function (obj, key) {
  253. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  254. };
  255. var has = function (obj, key) {
  256. return hasOwnProperty.call(obj, key);
  257. };
  258. var hasNonNullableKey = function (obj, key) {
  259. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  260. };
  261. var Cell = function (initial) {
  262. var value = initial;
  263. var get = function () {
  264. return value;
  265. };
  266. var set = function (v) {
  267. value = v;
  268. };
  269. var clone = function () {
  270. return Cell(get());
  271. };
  272. return {
  273. get: get,
  274. set: set,
  275. clone: clone
  276. };
  277. };
  278. var firstMatch = function (regexes, s) {
  279. for (var i = 0; i < regexes.length; i++) {
  280. var x = regexes[i];
  281. if (x.test(s)) {
  282. return x;
  283. }
  284. }
  285. return undefined;
  286. };
  287. var find$1 = function (regexes, agent) {
  288. var r = firstMatch(regexes, agent);
  289. if (!r) {
  290. return {
  291. major: 0,
  292. minor: 0
  293. };
  294. }
  295. var group = function (i) {
  296. return Number(agent.replace(r, '$' + i));
  297. };
  298. return nu(group(1), group(2));
  299. };
  300. var detect = function (versionRegexes, agent) {
  301. var cleanedAgent = String(agent).toLowerCase();
  302. if (versionRegexes.length === 0) {
  303. return unknown();
  304. }
  305. return find$1(versionRegexes, cleanedAgent);
  306. };
  307. var unknown = function () {
  308. return nu(0, 0);
  309. };
  310. var nu = function (major, minor) {
  311. return {
  312. major: major,
  313. minor: minor
  314. };
  315. };
  316. var Version = {
  317. nu: nu,
  318. detect: detect,
  319. unknown: unknown
  320. };
  321. var edge = 'Edge';
  322. var chrome = 'Chrome';
  323. var ie = 'IE';
  324. var opera = 'Opera';
  325. var firefox = 'Firefox';
  326. var safari = 'Safari';
  327. var isBrowser = function (name, current) {
  328. return function () {
  329. return current === name;
  330. };
  331. };
  332. var unknown$1 = function () {
  333. return nu$1({
  334. current: undefined,
  335. version: Version.unknown()
  336. });
  337. };
  338. var nu$1 = function (info) {
  339. var current = info.current;
  340. var version = info.version;
  341. return {
  342. current: current,
  343. version: version,
  344. isEdge: isBrowser(edge, current),
  345. isChrome: isBrowser(chrome, current),
  346. isIE: isBrowser(ie, current),
  347. isOpera: isBrowser(opera, current),
  348. isFirefox: isBrowser(firefox, current),
  349. isSafari: isBrowser(safari, current)
  350. };
  351. };
  352. var Browser = {
  353. unknown: unknown$1,
  354. nu: nu$1,
  355. edge: constant(edge),
  356. chrome: constant(chrome),
  357. ie: constant(ie),
  358. opera: constant(opera),
  359. firefox: constant(firefox),
  360. safari: constant(safari)
  361. };
  362. var windows = 'Windows';
  363. var ios = 'iOS';
  364. var android = 'Android';
  365. var linux = 'Linux';
  366. var osx = 'OSX';
  367. var solaris = 'Solaris';
  368. var freebsd = 'FreeBSD';
  369. var chromeos = 'ChromeOS';
  370. var isOS = function (name, current) {
  371. return function () {
  372. return current === name;
  373. };
  374. };
  375. var unknown$2 = function () {
  376. return nu$2({
  377. current: undefined,
  378. version: Version.unknown()
  379. });
  380. };
  381. var nu$2 = function (info) {
  382. var current = info.current;
  383. var version = info.version;
  384. return {
  385. current: current,
  386. version: version,
  387. isWindows: isOS(windows, current),
  388. isiOS: isOS(ios, current),
  389. isAndroid: isOS(android, current),
  390. isOSX: isOS(osx, current),
  391. isLinux: isOS(linux, current),
  392. isSolaris: isOS(solaris, current),
  393. isFreeBSD: isOS(freebsd, current),
  394. isChromeOS: isOS(chromeos, current)
  395. };
  396. };
  397. var OperatingSystem = {
  398. unknown: unknown$2,
  399. nu: nu$2,
  400. windows: constant(windows),
  401. ios: constant(ios),
  402. android: constant(android),
  403. linux: constant(linux),
  404. osx: constant(osx),
  405. solaris: constant(solaris),
  406. freebsd: constant(freebsd),
  407. chromeos: constant(chromeos)
  408. };
  409. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  410. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  411. var isiPhone = os.isiOS() && !isiPad;
  412. var isMobile = os.isiOS() || os.isAndroid();
  413. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  414. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  415. var isPhone = isiPhone || isMobile && !isTablet;
  416. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  417. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  418. return {
  419. isiPad: constant(isiPad),
  420. isiPhone: constant(isiPhone),
  421. isTablet: constant(isTablet),
  422. isPhone: constant(isPhone),
  423. isTouch: constant(isTouch),
  424. isAndroid: os.isAndroid,
  425. isiOS: os.isiOS,
  426. isWebView: constant(iOSwebview),
  427. isDesktop: constant(isDesktop)
  428. };
  429. };
  430. var typeOf = function (x) {
  431. if (x === null) {
  432. return 'null';
  433. }
  434. var t = typeof x;
  435. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  436. return 'array';
  437. }
  438. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  439. return 'string';
  440. }
  441. return t;
  442. };
  443. var isType = function (type) {
  444. return function (value) {
  445. return typeOf(value) === type;
  446. };
  447. };
  448. var isString = isType('string');
  449. var isObject = isType('object');
  450. var isArray = isType('array');
  451. var isBoolean = isType('boolean');
  452. var isFunction = isType('function');
  453. var isNumber = isType('number');
  454. var nativeSlice = Array.prototype.slice;
  455. var nativeIndexOf = Array.prototype.indexOf;
  456. var nativePush = Array.prototype.push;
  457. var rawIndexOf = function (ts, t) {
  458. return nativeIndexOf.call(ts, t);
  459. };
  460. var contains = function (xs, x) {
  461. return rawIndexOf(xs, x) > -1;
  462. };
  463. var exists = function (xs, pred) {
  464. for (var i = 0, len = xs.length; i < len; i++) {
  465. var x = xs[i];
  466. if (pred(x, i)) {
  467. return true;
  468. }
  469. }
  470. return false;
  471. };
  472. var map$1 = function (xs, f) {
  473. var len = xs.length;
  474. var r = new Array(len);
  475. for (var i = 0; i < len; i++) {
  476. var x = xs[i];
  477. r[i] = f(x, i);
  478. }
  479. return r;
  480. };
  481. var each$1 = function (xs, f) {
  482. for (var i = 0, len = xs.length; i < len; i++) {
  483. var x = xs[i];
  484. f(x, i);
  485. }
  486. };
  487. var eachr = function (xs, f) {
  488. for (var i = xs.length - 1; i >= 0; i--) {
  489. var x = xs[i];
  490. f(x, i);
  491. }
  492. };
  493. var filter = function (xs, pred) {
  494. var r = [];
  495. for (var i = 0, len = xs.length; i < len; i++) {
  496. var x = xs[i];
  497. if (pred(x, i)) {
  498. r.push(x);
  499. }
  500. }
  501. return r;
  502. };
  503. var foldr = function (xs, f, acc) {
  504. eachr(xs, function (x) {
  505. acc = f(acc, x);
  506. });
  507. return acc;
  508. };
  509. var foldl = function (xs, f, acc) {
  510. each$1(xs, function (x) {
  511. acc = f(acc, x);
  512. });
  513. return acc;
  514. };
  515. var find$2 = function (xs, pred) {
  516. for (var i = 0, len = xs.length; i < len; i++) {
  517. var x = xs[i];
  518. if (pred(x, i)) {
  519. return Option.some(x);
  520. }
  521. }
  522. return Option.none();
  523. };
  524. var findIndex = function (xs, pred) {
  525. for (var i = 0, len = xs.length; i < len; i++) {
  526. var x = xs[i];
  527. if (pred(x, i)) {
  528. return Option.some(i);
  529. }
  530. }
  531. return Option.none();
  532. };
  533. var flatten = function (xs) {
  534. var r = [];
  535. for (var i = 0, len = xs.length; i < len; ++i) {
  536. if (!isArray(xs[i])) {
  537. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  538. }
  539. nativePush.apply(r, xs[i]);
  540. }
  541. return r;
  542. };
  543. var bind = function (xs, f) {
  544. return flatten(map$1(xs, f));
  545. };
  546. var forall = function (xs, pred) {
  547. for (var i = 0, len = xs.length; i < len; ++i) {
  548. var x = xs[i];
  549. if (pred(x, i) !== true) {
  550. return false;
  551. }
  552. }
  553. return true;
  554. };
  555. var reverse = function (xs) {
  556. var r = nativeSlice.call(xs, 0);
  557. r.reverse();
  558. return r;
  559. };
  560. var difference = function (a1, a2) {
  561. return filter(a1, function (x) {
  562. return !contains(a2, x);
  563. });
  564. };
  565. var pure = function (x) {
  566. return [x];
  567. };
  568. var sort = function (xs, comparator) {
  569. var copy = nativeSlice.call(xs, 0);
  570. copy.sort(comparator);
  571. return copy;
  572. };
  573. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  574. return nativeSlice.call(x);
  575. };
  576. var findMap = function (arr, f) {
  577. for (var i = 0; i < arr.length; i++) {
  578. var r = f(arr[i], i);
  579. if (r.isSome()) {
  580. return r;
  581. }
  582. }
  583. return Option.none();
  584. };
  585. var detect$1 = function (candidates, userAgent) {
  586. var agent = String(userAgent).toLowerCase();
  587. return find$2(candidates, function (candidate) {
  588. return candidate.search(agent);
  589. });
  590. };
  591. var detectBrowser = function (browsers, userAgent) {
  592. return detect$1(browsers, userAgent).map(function (browser) {
  593. var version = Version.detect(browser.versionRegexes, userAgent);
  594. return {
  595. current: browser.name,
  596. version: version
  597. };
  598. });
  599. };
  600. var detectOs = function (oses, userAgent) {
  601. return detect$1(oses, userAgent).map(function (os) {
  602. var version = Version.detect(os.versionRegexes, userAgent);
  603. return {
  604. current: os.name,
  605. version: version
  606. };
  607. });
  608. };
  609. var UaString = {
  610. detectBrowser: detectBrowser,
  611. detectOs: detectOs
  612. };
  613. var checkRange = function (str, substr, start) {
  614. if (substr === '') {
  615. return true;
  616. }
  617. if (str.length < substr.length) {
  618. return false;
  619. }
  620. var x = str.substr(start, start + substr.length);
  621. return x === substr;
  622. };
  623. var supplant = function (str, obj) {
  624. var isStringOrNumber = function (a) {
  625. var t = typeof a;
  626. return t === 'string' || t === 'number';
  627. };
  628. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  629. var value = obj[key];
  630. return isStringOrNumber(value) ? value.toString() : fullMatch;
  631. });
  632. };
  633. var contains$1 = function (str, substr) {
  634. return str.indexOf(substr) !== -1;
  635. };
  636. var endsWith = function (str, suffix) {
  637. return checkRange(str, suffix, str.length - suffix.length);
  638. };
  639. var trim = function (str) {
  640. return str.replace(/^\s+|\s+$/g, '');
  641. };
  642. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  643. var checkContains = function (target) {
  644. return function (uastring) {
  645. return contains$1(uastring, target);
  646. };
  647. };
  648. var browsers = [
  649. {
  650. name: 'Edge',
  651. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  652. search: function (uastring) {
  653. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  654. }
  655. },
  656. {
  657. name: 'Chrome',
  658. versionRegexes: [
  659. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  660. normalVersionRegex
  661. ],
  662. search: function (uastring) {
  663. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  664. }
  665. },
  666. {
  667. name: 'IE',
  668. versionRegexes: [
  669. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  670. /.*?rv:([0-9]+)\.([0-9]+).*/
  671. ],
  672. search: function (uastring) {
  673. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  674. }
  675. },
  676. {
  677. name: 'Opera',
  678. versionRegexes: [
  679. normalVersionRegex,
  680. /.*?opera\/([0-9]+)\.([0-9]+).*/
  681. ],
  682. search: checkContains('opera')
  683. },
  684. {
  685. name: 'Firefox',
  686. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  687. search: checkContains('firefox')
  688. },
  689. {
  690. name: 'Safari',
  691. versionRegexes: [
  692. normalVersionRegex,
  693. /.*?cpu os ([0-9]+)_([0-9]+).*/
  694. ],
  695. search: function (uastring) {
  696. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  697. }
  698. }
  699. ];
  700. var oses = [
  701. {
  702. name: 'Windows',
  703. search: checkContains('win'),
  704. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  705. },
  706. {
  707. name: 'iOS',
  708. search: function (uastring) {
  709. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  710. },
  711. versionRegexes: [
  712. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  713. /.*cpu os ([0-9]+)_([0-9]+).*/,
  714. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  715. ]
  716. },
  717. {
  718. name: 'Android',
  719. search: checkContains('android'),
  720. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  721. },
  722. {
  723. name: 'OSX',
  724. search: checkContains('mac os x'),
  725. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  726. },
  727. {
  728. name: 'Linux',
  729. search: checkContains('linux'),
  730. versionRegexes: []
  731. },
  732. {
  733. name: 'Solaris',
  734. search: checkContains('sunos'),
  735. versionRegexes: []
  736. },
  737. {
  738. name: 'FreeBSD',
  739. search: checkContains('freebsd'),
  740. versionRegexes: []
  741. },
  742. {
  743. name: 'ChromeOS',
  744. search: checkContains('cros'),
  745. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  746. }
  747. ];
  748. var PlatformInfo = {
  749. browsers: constant(browsers),
  750. oses: constant(oses)
  751. };
  752. var detect$2 = function (userAgent, mediaMatch) {
  753. var browsers = PlatformInfo.browsers();
  754. var oses = PlatformInfo.oses();
  755. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  756. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  757. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  758. return {
  759. browser: browser,
  760. os: os,
  761. deviceType: deviceType
  762. };
  763. };
  764. var PlatformDetection = { detect: detect$2 };
  765. var mediaMatch = function (query) {
  766. return domGlobals.window.matchMedia(query).matches;
  767. };
  768. var platform = Cell(PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch));
  769. var detect$3 = function () {
  770. return platform.get();
  771. };
  772. var touchstart = constant('touchstart');
  773. var touchmove = constant('touchmove');
  774. var touchend = constant('touchend');
  775. var mousedown = constant('mousedown');
  776. var mousemove = constant('mousemove');
  777. var mouseup = constant('mouseup');
  778. var mouseover = constant('mouseover');
  779. var keydown = constant('keydown');
  780. var keyup = constant('keyup');
  781. var input = constant('input');
  782. var change = constant('change');
  783. var click = constant('click');
  784. var transitionend = constant('transitionend');
  785. var selectstart = constant('selectstart');
  786. var alloy = { tap: constant('alloy.tap') };
  787. var focus = constant('alloy.focus');
  788. var postBlur = constant('alloy.blur.post');
  789. var postPaste = constant('alloy.paste.post');
  790. var receive = constant('alloy.receive');
  791. var execute = constant('alloy.execute');
  792. var focusItem = constant('alloy.focus.item');
  793. var tap = alloy.tap;
  794. var longpress = constant('alloy.longpress');
  795. var systemInit = constant('alloy.system.init');
  796. var attachedToDom = constant('alloy.system.attached');
  797. var detachedFromDom = constant('alloy.system.detached');
  798. var focusShifted = constant('alloy.focusmanager.shifted');
  799. var highlight = constant('alloy.highlight');
  800. var dehighlight = constant('alloy.dehighlight');
  801. var emit = function (component, event) {
  802. dispatchWith(component, component.element(), event, {});
  803. };
  804. var emitWith = function (component, event, properties) {
  805. dispatchWith(component, component.element(), event, properties);
  806. };
  807. var emitExecute = function (component) {
  808. emit(component, execute());
  809. };
  810. var dispatch = function (component, target, event) {
  811. dispatchWith(component, target, event, {});
  812. };
  813. var dispatchWith = function (component, target, event, properties) {
  814. var data = __assign({ target: target }, properties);
  815. component.getSystem().triggerEvent(event, target, map(data, constant));
  816. };
  817. var dispatchEvent = function (component, target, event, simulatedEvent) {
  818. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  819. };
  820. var dispatchFocus = function (component, target) {
  821. component.getSystem().triggerFocus(target, component.element());
  822. };
  823. var cached = function (f) {
  824. var called = false;
  825. var r;
  826. return function () {
  827. var args = [];
  828. for (var _i = 0; _i < arguments.length; _i++) {
  829. args[_i] = arguments[_i];
  830. }
  831. if (!called) {
  832. called = true;
  833. r = f.apply(null, args);
  834. }
  835. return r;
  836. };
  837. };
  838. var fromHtml = function (html, scope) {
  839. var doc = scope || domGlobals.document;
  840. var div = doc.createElement('div');
  841. div.innerHTML = html;
  842. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  843. domGlobals.console.error('HTML does not have a single root node', html);
  844. throw new Error('HTML must have a single root node');
  845. }
  846. return fromDom(div.childNodes[0]);
  847. };
  848. var fromTag = function (tag, scope) {
  849. var doc = scope || domGlobals.document;
  850. var node = doc.createElement(tag);
  851. return fromDom(node);
  852. };
  853. var fromText = function (text, scope) {
  854. var doc = scope || domGlobals.document;
  855. var node = doc.createTextNode(text);
  856. return fromDom(node);
  857. };
  858. var fromDom = function (node) {
  859. if (node === null || node === undefined) {
  860. throw new Error('Node cannot be null or undefined');
  861. }
  862. return { dom: constant(node) };
  863. };
  864. var fromPoint = function (docElm, x, y) {
  865. var doc = docElm.dom();
  866. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  867. };
  868. var Element = {
  869. fromHtml: fromHtml,
  870. fromTag: fromTag,
  871. fromText: fromText,
  872. fromDom: fromDom,
  873. fromPoint: fromPoint
  874. };
  875. var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE;
  876. var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE;
  877. var COMMENT = domGlobals.Node.COMMENT_NODE;
  878. var DOCUMENT = domGlobals.Node.DOCUMENT_NODE;
  879. var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE;
  880. var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE;
  881. var ELEMENT = domGlobals.Node.ELEMENT_NODE;
  882. var TEXT = domGlobals.Node.TEXT_NODE;
  883. var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE;
  884. var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE;
  885. var ENTITY = domGlobals.Node.ENTITY_NODE;
  886. var NOTATION = domGlobals.Node.NOTATION_NODE;
  887. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  888. var name = function (element) {
  889. var r = element.dom().nodeName;
  890. return r.toLowerCase();
  891. };
  892. var type = function (element) {
  893. return element.dom().nodeType;
  894. };
  895. var isType$1 = function (t) {
  896. return function (element) {
  897. return type(element) === t;
  898. };
  899. };
  900. var isElement = isType$1(ELEMENT);
  901. var isText = isType$1(TEXT);
  902. var inBody = function (element) {
  903. var dom = isText(element) ? element.dom().parentNode : element.dom();
  904. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  905. };
  906. var body = cached(function () {
  907. return getBody(Element.fromDom(domGlobals.document));
  908. });
  909. var getBody = function (doc) {
  910. var b = doc.dom().body;
  911. if (b === null || b === undefined) {
  912. throw new Error('Body is not available yet');
  913. }
  914. return Element.fromDom(b);
  915. };
  916. var Immutable = function () {
  917. var fields = [];
  918. for (var _i = 0; _i < arguments.length; _i++) {
  919. fields[_i] = arguments[_i];
  920. }
  921. return function () {
  922. var values = [];
  923. for (var _i = 0; _i < arguments.length; _i++) {
  924. values[_i] = arguments[_i];
  925. }
  926. if (fields.length !== values.length) {
  927. throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
  928. }
  929. var struct = {};
  930. each$1(fields, function (name, i) {
  931. struct[name] = constant(values[i]);
  932. });
  933. return struct;
  934. };
  935. };
  936. var sort$1 = function (arr) {
  937. return arr.slice(0).sort();
  938. };
  939. var reqMessage = function (required, keys) {
  940. throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  941. };
  942. var unsuppMessage = function (unsupported) {
  943. throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  944. };
  945. var validateStrArr = function (label, array) {
  946. if (!isArray(array)) {
  947. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  948. }
  949. each$1(array, function (a) {
  950. if (!isString(a)) {
  951. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  952. }
  953. });
  954. };
  955. var checkDupes = function (everything) {
  956. var sorted = sort$1(everything);
  957. var dupe = find$2(sorted, function (s, i) {
  958. return i < sorted.length - 1 && s === sorted[i + 1];
  959. });
  960. dupe.each(function (d) {
  961. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  962. });
  963. };
  964. var MixedBag = function (required, optional) {
  965. var everything = required.concat(optional);
  966. if (everything.length === 0) {
  967. throw new Error('You must specify at least one required or optional field.');
  968. }
  969. validateStrArr('required', required);
  970. validateStrArr('optional', optional);
  971. checkDupes(everything);
  972. return function (obj) {
  973. var keys$1 = keys(obj);
  974. var allReqd = forall(required, function (req) {
  975. return contains(keys$1, req);
  976. });
  977. if (!allReqd) {
  978. reqMessage(required, keys$1);
  979. }
  980. var unsupported = filter(keys$1, function (key) {
  981. return !contains(everything, key);
  982. });
  983. if (unsupported.length > 0) {
  984. unsuppMessage(unsupported);
  985. }
  986. var r = {};
  987. each$1(required, function (req) {
  988. r[req] = constant(obj[req]);
  989. });
  990. each$1(optional, function (opt) {
  991. r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
  992. });
  993. return r;
  994. };
  995. };
  996. var compareDocumentPosition = function (a, b, match) {
  997. return (a.compareDocumentPosition(b) & match) !== 0;
  998. };
  999. var documentPositionPreceding = function (a, b) {
  1000. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_PRECEDING);
  1001. };
  1002. var documentPositionContainedBy = function (a, b) {
  1003. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY);
  1004. };
  1005. var Node = {
  1006. documentPositionPreceding: documentPositionPreceding,
  1007. documentPositionContainedBy: documentPositionContainedBy
  1008. };
  1009. var ELEMENT$1 = ELEMENT;
  1010. var DOCUMENT$1 = DOCUMENT;
  1011. var is = function (element, selector) {
  1012. var dom = element.dom();
  1013. if (dom.nodeType !== ELEMENT$1) {
  1014. return false;
  1015. } else {
  1016. var elem = dom;
  1017. if (elem.matches !== undefined) {
  1018. return elem.matches(selector);
  1019. } else if (elem.msMatchesSelector !== undefined) {
  1020. return elem.msMatchesSelector(selector);
  1021. } else if (elem.webkitMatchesSelector !== undefined) {
  1022. return elem.webkitMatchesSelector(selector);
  1023. } else if (elem.mozMatchesSelector !== undefined) {
  1024. return elem.mozMatchesSelector(selector);
  1025. } else {
  1026. throw new Error('Browser lacks native selectors');
  1027. }
  1028. }
  1029. };
  1030. var bypassSelector = function (dom) {
  1031. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  1032. };
  1033. var all = function (selector, scope) {
  1034. var base = scope === undefined ? domGlobals.document : scope.dom();
  1035. return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), Element.fromDom);
  1036. };
  1037. var one = function (selector, scope) {
  1038. var base = scope === undefined ? domGlobals.document : scope.dom();
  1039. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1040. };
  1041. var eq = function (e1, e2) {
  1042. return e1.dom() === e2.dom();
  1043. };
  1044. var regularContains = function (e1, e2) {
  1045. var d1 = e1.dom();
  1046. var d2 = e2.dom();
  1047. return d1 === d2 ? false : d1.contains(d2);
  1048. };
  1049. var ieContains = function (e1, e2) {
  1050. return Node.documentPositionContainedBy(e1.dom(), e2.dom());
  1051. };
  1052. var browser = detect$3().browser;
  1053. var contains$2 = browser.isIE() ? ieContains : regularContains;
  1054. var owner = function (element) {
  1055. return Element.fromDom(element.dom().ownerDocument);
  1056. };
  1057. var defaultView = function (element) {
  1058. return Element.fromDom(element.dom().ownerDocument.defaultView);
  1059. };
  1060. var parent = function (element) {
  1061. return Option.from(element.dom().parentNode).map(Element.fromDom);
  1062. };
  1063. var parents = function (element, isRoot) {
  1064. var stop = isFunction(isRoot) ? isRoot : never;
  1065. var dom = element.dom();
  1066. var ret = [];
  1067. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1068. var rawParent = dom.parentNode;
  1069. var p = Element.fromDom(rawParent);
  1070. ret.push(p);
  1071. if (stop(p) === true) {
  1072. break;
  1073. } else {
  1074. dom = rawParent;
  1075. }
  1076. }
  1077. return ret;
  1078. };
  1079. var siblings = function (element) {
  1080. var filterSelf = function (elements) {
  1081. return filter(elements, function (x) {
  1082. return !eq(element, x);
  1083. });
  1084. };
  1085. return parent(element).map(children).map(filterSelf).getOr([]);
  1086. };
  1087. var nextSibling = function (element) {
  1088. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  1089. };
  1090. var children = function (element) {
  1091. return map$1(element.dom().childNodes, Element.fromDom);
  1092. };
  1093. var child = function (element, index) {
  1094. var cs = element.dom().childNodes;
  1095. return Option.from(cs[index]).map(Element.fromDom);
  1096. };
  1097. var firstChild = function (element) {
  1098. return child(element, 0);
  1099. };
  1100. var spot = Immutable('element', 'offset');
  1101. var before = function (marker, element) {
  1102. var parent$1 = parent(marker);
  1103. parent$1.each(function (v) {
  1104. v.dom().insertBefore(element.dom(), marker.dom());
  1105. });
  1106. };
  1107. var after = function (marker, element) {
  1108. var sibling = nextSibling(marker);
  1109. sibling.fold(function () {
  1110. var parent$1 = parent(marker);
  1111. parent$1.each(function (v) {
  1112. append(v, element);
  1113. });
  1114. }, function (v) {
  1115. before(v, element);
  1116. });
  1117. };
  1118. var prepend = function (parent, element) {
  1119. var firstChild$1 = firstChild(parent);
  1120. firstChild$1.fold(function () {
  1121. append(parent, element);
  1122. }, function (v) {
  1123. parent.dom().insertBefore(element.dom(), v.dom());
  1124. });
  1125. };
  1126. var append = function (parent, element) {
  1127. parent.dom().appendChild(element.dom());
  1128. };
  1129. var appendAt = function (parent, element, index) {
  1130. child(parent, index).fold(function () {
  1131. append(parent, element);
  1132. }, function (v) {
  1133. before(v, element);
  1134. });
  1135. };
  1136. var append$1 = function (parent, elements) {
  1137. each$1(elements, function (x) {
  1138. append(parent, x);
  1139. });
  1140. };
  1141. var empty = function (element) {
  1142. element.dom().textContent = '';
  1143. each$1(children(element), function (rogue) {
  1144. remove(rogue);
  1145. });
  1146. };
  1147. var remove = function (element) {
  1148. var dom = element.dom();
  1149. if (dom.parentNode !== null) {
  1150. dom.parentNode.removeChild(dom);
  1151. }
  1152. };
  1153. var fireDetaching = function (component) {
  1154. emit(component, detachedFromDom());
  1155. var children = component.components();
  1156. each$1(children, fireDetaching);
  1157. };
  1158. var fireAttaching = function (component) {
  1159. var children = component.components();
  1160. each$1(children, fireAttaching);
  1161. emit(component, attachedToDom());
  1162. };
  1163. var attach = function (parent, child) {
  1164. append(parent.element(), child.element());
  1165. };
  1166. var detachChildren = function (component) {
  1167. each$1(component.components(), function (childComp) {
  1168. return remove(childComp.element());
  1169. });
  1170. empty(component.element());
  1171. component.syncComponents();
  1172. };
  1173. var replaceChildren = function (component, newChildren) {
  1174. var subs = component.components();
  1175. detachChildren(component);
  1176. var deleted = difference(subs, newChildren);
  1177. each$1(deleted, function (comp) {
  1178. fireDetaching(comp);
  1179. component.getSystem().removeFromWorld(comp);
  1180. });
  1181. each$1(newChildren, function (childComp) {
  1182. if (!childComp.getSystem().isConnected()) {
  1183. component.getSystem().addToWorld(childComp);
  1184. attach(component, childComp);
  1185. if (inBody(component.element())) {
  1186. fireAttaching(childComp);
  1187. }
  1188. } else {
  1189. attach(component, childComp);
  1190. }
  1191. component.syncComponents();
  1192. });
  1193. };
  1194. var attach$1 = function (parent, child) {
  1195. attachWith(parent, child, append);
  1196. };
  1197. var attachWith = function (parent, child, insertion) {
  1198. parent.getSystem().addToWorld(child);
  1199. insertion(parent.element(), child.element());
  1200. if (inBody(parent.element())) {
  1201. fireAttaching(child);
  1202. }
  1203. parent.syncComponents();
  1204. };
  1205. var doDetach = function (component) {
  1206. fireDetaching(component);
  1207. remove(component.element());
  1208. component.getSystem().removeFromWorld(component);
  1209. };
  1210. var detach = function (component) {
  1211. var parent$1 = parent(component.element()).bind(function (p) {
  1212. return component.getSystem().getByDom(p).toOption();
  1213. });
  1214. doDetach(component);
  1215. parent$1.each(function (p) {
  1216. p.syncComponents();
  1217. });
  1218. };
  1219. var attachSystemAfter = function (element, guiSystem) {
  1220. attachSystemWith(element, guiSystem, after);
  1221. };
  1222. var attachSystemWith = function (element, guiSystem, inserter) {
  1223. inserter(element, guiSystem.element());
  1224. var children$1 = children(guiSystem.element());
  1225. each$1(children$1, function (child) {
  1226. guiSystem.getByDom(child).each(fireAttaching);
  1227. });
  1228. };
  1229. var detachSystem = function (guiSystem) {
  1230. var children$1 = children(guiSystem.element());
  1231. each$1(children$1, function (child) {
  1232. guiSystem.getByDom(child).each(fireDetaching);
  1233. });
  1234. remove(guiSystem.element());
  1235. };
  1236. var value = function (o) {
  1237. var is = function (v) {
  1238. return o === v;
  1239. };
  1240. var or = function (opt) {
  1241. return value(o);
  1242. };
  1243. var orThunk = function (f) {
  1244. return value(o);
  1245. };
  1246. var map = function (f) {
  1247. return value(f(o));
  1248. };
  1249. var mapError = function (f) {
  1250. return value(o);
  1251. };
  1252. var each = function (f) {
  1253. f(o);
  1254. };
  1255. var bind = function (f) {
  1256. return f(o);
  1257. };
  1258. var fold = function (_, onValue) {
  1259. return onValue(o);
  1260. };
  1261. var exists = function (f) {
  1262. return f(o);
  1263. };
  1264. var forall = function (f) {
  1265. return f(o);
  1266. };
  1267. var toOption = function () {
  1268. return Option.some(o);
  1269. };
  1270. return {
  1271. is: is,
  1272. isValue: always,
  1273. isError: never,
  1274. getOr: constant(o),
  1275. getOrThunk: constant(o),
  1276. getOrDie: constant(o),
  1277. or: or,
  1278. orThunk: orThunk,
  1279. fold: fold,
  1280. map: map,
  1281. mapError: mapError,
  1282. each: each,
  1283. bind: bind,
  1284. exists: exists,
  1285. forall: forall,
  1286. toOption: toOption
  1287. };
  1288. };
  1289. var error = function (message) {
  1290. var getOrThunk = function (f) {
  1291. return f();
  1292. };
  1293. var getOrDie = function () {
  1294. return die(String(message))();
  1295. };
  1296. var or = function (opt) {
  1297. return opt;
  1298. };
  1299. var orThunk = function (f) {
  1300. return f();
  1301. };
  1302. var map = function (f) {
  1303. return error(message);
  1304. };
  1305. var mapError = function (f) {
  1306. return error(f(message));
  1307. };
  1308. var bind = function (f) {
  1309. return error(message);
  1310. };
  1311. var fold = function (onError, _) {
  1312. return onError(message);
  1313. };
  1314. return {
  1315. is: never,
  1316. isValue: never,
  1317. isError: always,
  1318. getOr: identity,
  1319. getOrThunk: getOrThunk,
  1320. getOrDie: getOrDie,
  1321. or: or,
  1322. orThunk: orThunk,
  1323. fold: fold,
  1324. map: map,
  1325. mapError: mapError,
  1326. each: noop,
  1327. bind: bind,
  1328. exists: never,
  1329. forall: always,
  1330. toOption: Option.none
  1331. };
  1332. };
  1333. var fromOption = function (opt, err) {
  1334. return opt.fold(function () {
  1335. return error(err);
  1336. }, value);
  1337. };
  1338. var Result = {
  1339. value: value,
  1340. error: error,
  1341. fromOption: fromOption
  1342. };
  1343. var generate = function (cases) {
  1344. if (!isArray(cases)) {
  1345. throw new Error('cases must be an array');
  1346. }
  1347. if (cases.length === 0) {
  1348. throw new Error('there must be at least one case');
  1349. }
  1350. var constructors = [];
  1351. var adt = {};
  1352. each$1(cases, function (acase, count) {
  1353. var keys$1 = keys(acase);
  1354. if (keys$1.length !== 1) {
  1355. throw new Error('one and only one name per case');
  1356. }
  1357. var key = keys$1[0];
  1358. var value = acase[key];
  1359. if (adt[key] !== undefined) {
  1360. throw new Error('duplicate key detected:' + key);
  1361. } else if (key === 'cata') {
  1362. throw new Error('cannot have a case named cata (sorry)');
  1363. } else if (!isArray(value)) {
  1364. throw new Error('case arguments must be an array');
  1365. }
  1366. constructors.push(key);
  1367. adt[key] = function () {
  1368. var argLength = arguments.length;
  1369. if (argLength !== value.length) {
  1370. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1371. }
  1372. var args = new Array(argLength);
  1373. for (var i = 0; i < args.length; i++) {
  1374. args[i] = arguments[i];
  1375. }
  1376. var match = function (branches) {
  1377. var branchKeys = keys(branches);
  1378. if (constructors.length !== branchKeys.length) {
  1379. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1380. }
  1381. var allReqd = forall(constructors, function (reqKey) {
  1382. return contains(branchKeys, reqKey);
  1383. });
  1384. if (!allReqd) {
  1385. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1386. }
  1387. return branches[key].apply(null, args);
  1388. };
  1389. return {
  1390. fold: function () {
  1391. if (arguments.length !== cases.length) {
  1392. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  1393. }
  1394. var target = arguments[count];
  1395. return target.apply(null, args);
  1396. },
  1397. match: match,
  1398. log: function (label) {
  1399. domGlobals.console.log(label, {
  1400. constructors: constructors,
  1401. constructor: key,
  1402. params: args
  1403. });
  1404. }
  1405. };
  1406. };
  1407. });
  1408. return adt;
  1409. };
  1410. var Adt = { generate: generate };
  1411. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  1412. var shallow = function (old, nu) {
  1413. return nu;
  1414. };
  1415. var deep = function (old, nu) {
  1416. var bothObjects = isObject(old) && isObject(nu);
  1417. return bothObjects ? deepMerge(old, nu) : nu;
  1418. };
  1419. var baseMerge = function (merger) {
  1420. return function () {
  1421. var objects = new Array(arguments.length);
  1422. for (var i = 0; i < objects.length; i++) {
  1423. objects[i] = arguments[i];
  1424. }
  1425. if (objects.length === 0) {
  1426. throw new Error('Can\'t merge zero objects');
  1427. }
  1428. var ret = {};
  1429. for (var j = 0; j < objects.length; j++) {
  1430. var curObject = objects[j];
  1431. for (var key in curObject) {
  1432. if (hasOwnProperty$1.call(curObject, key)) {
  1433. ret[key] = merger(ret[key], curObject[key]);
  1434. }
  1435. }
  1436. }
  1437. return ret;
  1438. };
  1439. };
  1440. var deepMerge = baseMerge(deep);
  1441. var merge = baseMerge(shallow);
  1442. var SimpleResultType;
  1443. (function (SimpleResultType) {
  1444. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1445. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1446. }(SimpleResultType || (SimpleResultType = {})));
  1447. var fold = function (res, onError, onValue) {
  1448. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1449. };
  1450. var partition = function (results) {
  1451. var values = [];
  1452. var errors = [];
  1453. each$1(results, function (obj) {
  1454. fold(obj, function (err) {
  1455. return errors.push(err);
  1456. }, function (val) {
  1457. return values.push(val);
  1458. });
  1459. });
  1460. return {
  1461. values: values,
  1462. errors: errors
  1463. };
  1464. };
  1465. var mapError = function (res, f) {
  1466. if (res.stype === SimpleResultType.Error) {
  1467. return {
  1468. stype: SimpleResultType.Error,
  1469. serror: f(res.serror)
  1470. };
  1471. } else {
  1472. return res;
  1473. }
  1474. };
  1475. var map$2 = function (res, f) {
  1476. if (res.stype === SimpleResultType.Value) {
  1477. return {
  1478. stype: SimpleResultType.Value,
  1479. svalue: f(res.svalue)
  1480. };
  1481. } else {
  1482. return res;
  1483. }
  1484. };
  1485. var bind$1 = function (res, f) {
  1486. if (res.stype === SimpleResultType.Value) {
  1487. return f(res.svalue);
  1488. } else {
  1489. return res;
  1490. }
  1491. };
  1492. var bindError = function (res, f) {
  1493. if (res.stype === SimpleResultType.Error) {
  1494. return f(res.serror);
  1495. } else {
  1496. return res;
  1497. }
  1498. };
  1499. var svalue = function (v) {
  1500. return {
  1501. stype: SimpleResultType.Value,
  1502. svalue: v
  1503. };
  1504. };
  1505. var serror = function (e) {
  1506. return {
  1507. stype: SimpleResultType.Error,
  1508. serror: e
  1509. };
  1510. };
  1511. var toResult = function (res) {
  1512. return fold(res, Result.error, Result.value);
  1513. };
  1514. var fromResult = function (res) {
  1515. return res.fold(serror, svalue);
  1516. };
  1517. var SimpleResult = {
  1518. fromResult: fromResult,
  1519. toResult: toResult,
  1520. svalue: svalue,
  1521. partition: partition,
  1522. serror: serror,
  1523. bind: bind$1,
  1524. bindError: bindError,
  1525. map: map$2,
  1526. mapError: mapError,
  1527. fold: fold
  1528. };
  1529. var adt = Adt.generate([
  1530. { strict: [] },
  1531. { defaultedThunk: ['fallbackThunk'] },
  1532. { asOption: [] },
  1533. { asDefaultedOptionThunk: ['fallbackThunk'] },
  1534. { mergeWithThunk: ['baseThunk'] }
  1535. ]);
  1536. var defaulted = function (fallback) {
  1537. return adt.defaultedThunk(constant(fallback));
  1538. };
  1539. var mergeWith = function (base) {
  1540. return adt.mergeWithThunk(constant(base));
  1541. };
  1542. var strict = adt.strict;
  1543. var asOption = adt.asOption;
  1544. var defaultedThunk = adt.defaultedThunk;
  1545. var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
  1546. var mergeWithThunk = adt.mergeWithThunk;
  1547. var exclude = function (obj, fields) {
  1548. var r = {};
  1549. each(obj, function (v, k) {
  1550. if (!contains(fields, k)) {
  1551. r[k] = v;
  1552. }
  1553. });
  1554. return r;
  1555. };
  1556. var wrap = function (key, value) {
  1557. var _a;
  1558. return _a = {}, _a[key] = value, _a;
  1559. };
  1560. var wrapAll = function (keyvalues) {
  1561. var r = {};
  1562. each$1(keyvalues, function (kv) {
  1563. r[kv.key] = kv.value;
  1564. });
  1565. return r;
  1566. };
  1567. var comparison = Adt.generate([
  1568. {
  1569. bothErrors: [
  1570. 'error1',
  1571. 'error2'
  1572. ]
  1573. },
  1574. {
  1575. firstError: [
  1576. 'error1',
  1577. 'value2'
  1578. ]
  1579. },
  1580. {
  1581. secondError: [
  1582. 'value1',
  1583. 'error2'
  1584. ]
  1585. },
  1586. {
  1587. bothValues: [
  1588. 'value1',
  1589. 'value2'
  1590. ]
  1591. }
  1592. ]);
  1593. var partition$1 = function (results) {
  1594. var errors = [];
  1595. var values = [];
  1596. each$1(results, function (result) {
  1597. result.fold(function (err) {
  1598. errors.push(err);
  1599. }, function (value) {
  1600. values.push(value);
  1601. });
  1602. });
  1603. return {
  1604. errors: errors,
  1605. values: values
  1606. };
  1607. };
  1608. var exclude$1 = function (obj, fields) {
  1609. return exclude(obj, fields);
  1610. };
  1611. var wrap$1 = function (key, value) {
  1612. return wrap(key, value);
  1613. };
  1614. var wrapAll$1 = function (keyvalues) {
  1615. return wrapAll(keyvalues);
  1616. };
  1617. var mergeValues = function (values, base) {
  1618. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  1619. };
  1620. var mergeErrors = function (errors) {
  1621. return Result.error(flatten(errors));
  1622. };
  1623. var consolidate = function (objs, base) {
  1624. var partitions = partition$1(objs);
  1625. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  1626. };
  1627. var mergeValues$1 = function (values, base) {
  1628. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  1629. };
  1630. var mergeErrors$1 = function (errors) {
  1631. return compose(SimpleResult.serror, flatten)(errors);
  1632. };
  1633. var consolidateObj = function (objects, base) {
  1634. var partition = SimpleResult.partition(objects);
  1635. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1636. };
  1637. var consolidateArr = function (objects) {
  1638. var partitions = SimpleResult.partition(objects);
  1639. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1640. };
  1641. var ResultCombine = {
  1642. consolidateObj: consolidateObj,
  1643. consolidateArr: consolidateArr
  1644. };
  1645. var formatObj = function (input) {
  1646. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1647. };
  1648. var formatErrors = function (errors) {
  1649. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1650. path: [],
  1651. getErrorInfo: function () {
  1652. return '... (only showing first ten failures)';
  1653. }
  1654. }]) : errors;
  1655. return map$1(es, function (e) {
  1656. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1657. });
  1658. };
  1659. var nu$3 = function (path, getErrorInfo) {
  1660. return SimpleResult.serror([{
  1661. path: path,
  1662. getErrorInfo: getErrorInfo
  1663. }]);
  1664. };
  1665. var missingStrict = function (path, key, obj) {
  1666. return nu$3(path, function () {
  1667. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  1668. });
  1669. };
  1670. var missingKey = function (path, key) {
  1671. return nu$3(path, function () {
  1672. return 'Choice schema did not contain choice key: "' + key + '"';
  1673. });
  1674. };
  1675. var missingBranch = function (path, branches, branch) {
  1676. return nu$3(path, function () {
  1677. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1678. });
  1679. };
  1680. var unsupportedFields = function (path, unsupported) {
  1681. return nu$3(path, function () {
  1682. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1683. });
  1684. };
  1685. var custom = function (path, err) {
  1686. return nu$3(path, function () {
  1687. return err;
  1688. });
  1689. };
  1690. var adt$1 = Adt.generate([
  1691. {
  1692. field: [
  1693. 'key',
  1694. 'okey',
  1695. 'presence',
  1696. 'prop'
  1697. ]
  1698. },
  1699. {
  1700. state: [
  1701. 'okey',
  1702. 'instantiator'
  1703. ]
  1704. }
  1705. ]);
  1706. var strictAccess = function (path, obj, key) {
  1707. return get(obj, key).fold(function () {
  1708. return missingStrict(path, key, obj);
  1709. }, SimpleResult.svalue);
  1710. };
  1711. var fallbackAccess = function (obj, key, fallbackThunk) {
  1712. var v = get(obj, key).fold(function () {
  1713. return fallbackThunk(obj);
  1714. }, identity);
  1715. return SimpleResult.svalue(v);
  1716. };
  1717. var optionAccess = function (obj, key) {
  1718. return SimpleResult.svalue(get(obj, key));
  1719. };
  1720. var optionDefaultedAccess = function (obj, key, fallback) {
  1721. var opt = get(obj, key).map(function (val) {
  1722. return val === true ? fallback(obj) : val;
  1723. });
  1724. return SimpleResult.svalue(opt);
  1725. };
  1726. var cExtractOne = function (path, obj, field, strength) {
  1727. return field.fold(function (key, okey, presence, prop) {
  1728. var bundle = function (av) {
  1729. var result = prop.extract(path.concat([key]), strength, av);
  1730. return SimpleResult.map(result, function (res) {
  1731. return wrap(okey, strength(res));
  1732. });
  1733. };
  1734. var bundleAsOption = function (optValue) {
  1735. return optValue.fold(function () {
  1736. var outcome = wrap(okey, strength(Option.none()));
  1737. return SimpleResult.svalue(outcome);
  1738. }, function (ov) {
  1739. var result = prop.extract(path.concat([key]), strength, ov);
  1740. return SimpleResult.map(result, function (res) {
  1741. return wrap(okey, strength(Option.some(res)));
  1742. });
  1743. });
  1744. };
  1745. return function () {
  1746. return presence.fold(function () {
  1747. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1748. }, function (fallbackThunk) {
  1749. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1750. }, function () {
  1751. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1752. }, function (fallbackThunk) {
  1753. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1754. }, function (baseThunk) {
  1755. var base = baseThunk(obj);
  1756. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1757. return deepMerge(base, v);
  1758. });
  1759. return SimpleResult.bind(result, bundle);
  1760. });
  1761. }();
  1762. }, function (okey, instantiator) {
  1763. var state = instantiator(obj);
  1764. return SimpleResult.svalue(wrap(okey, strength(state)));
  1765. });
  1766. };
  1767. var cExtract = function (path, obj, fields, strength) {
  1768. var results = map$1(fields, function (field) {
  1769. return cExtractOne(path, obj, field, strength);
  1770. });
  1771. return ResultCombine.consolidateObj(results, {});
  1772. };
  1773. var value$1 = function (validator) {
  1774. var extract = function (path, strength, val) {
  1775. return SimpleResult.bindError(validator(val, strength), function (err) {
  1776. return custom(path, err);
  1777. });
  1778. };
  1779. var toString = function () {
  1780. return 'val';
  1781. };
  1782. return {
  1783. extract: extract,
  1784. toString: toString
  1785. };
  1786. };
  1787. var getSetKeys = function (obj) {
  1788. var keys$1 = keys(obj);
  1789. return filter(keys$1, function (k) {
  1790. return hasNonNullableKey(obj, k);
  1791. });
  1792. };
  1793. var objOfOnly = function (fields) {
  1794. var delegate = objOf(fields);
  1795. var fieldNames = foldr(fields, function (acc, f) {
  1796. return f.fold(function (key) {
  1797. return deepMerge(acc, wrap$1(key, true));
  1798. }, constant(acc));
  1799. }, {});
  1800. var extract = function (path, strength, o) {
  1801. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1802. var extra = filter(keys, function (k) {
  1803. return !hasNonNullableKey(fieldNames, k);
  1804. });
  1805. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1806. };
  1807. return {
  1808. extract: extract,
  1809. toString: delegate.toString
  1810. };
  1811. };
  1812. var objOf = function (fields) {
  1813. var extract = function (path, strength, o) {
  1814. return cExtract(path, o, fields, strength);
  1815. };
  1816. var toString = function () {
  1817. var fieldStrings = map$1(fields, function (field) {
  1818. return field.fold(function (key, okey, presence, prop) {
  1819. return key + ' -> ' + prop.toString();
  1820. }, function (okey, instantiator) {
  1821. return 'state(' + okey + ')';
  1822. });
  1823. });
  1824. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1825. };
  1826. return {
  1827. extract: extract,
  1828. toString: toString
  1829. };
  1830. };
  1831. var arrOf = function (prop) {
  1832. var extract = function (path, strength, array) {
  1833. var results = map$1(array, function (a, i) {
  1834. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1835. });
  1836. return ResultCombine.consolidateArr(results);
  1837. };
  1838. var toString = function () {
  1839. return 'array(' + prop.toString() + ')';
  1840. };
  1841. return {
  1842. extract: extract,
  1843. toString: toString
  1844. };
  1845. };
  1846. var setOf = function (validator, prop) {
  1847. var validateKeys = function (path, keys) {
  1848. return arrOf(value$1(validator)).extract(path, identity, keys);
  1849. };
  1850. var extract = function (path, strength, o) {
  1851. var keys$1 = keys(o);
  1852. var validatedKeys = validateKeys(path, keys$1);
  1853. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1854. var schema = map$1(validKeys, function (vk) {
  1855. return adt$1.field(vk, vk, strict(), prop);
  1856. });
  1857. return objOf(schema).extract(path, strength, o);
  1858. });
  1859. };
  1860. var toString = function () {
  1861. return 'setOf(' + prop.toString() + ')';
  1862. };
  1863. return {
  1864. extract: extract,
  1865. toString: toString
  1866. };
  1867. };
  1868. var anyValue = constant(value$1(SimpleResult.svalue));
  1869. var state = adt$1.state;
  1870. var field = adt$1.field;
  1871. var chooseFrom = function (path, strength, input, branches, ch) {
  1872. var fields = get(branches, ch);
  1873. return fields.fold(function () {
  1874. return missingBranch(path, branches, ch);
  1875. }, function (vp) {
  1876. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1877. });
  1878. };
  1879. var choose = function (key, branches) {
  1880. var extract = function (path, strength, input) {
  1881. var choice = get(input, key);
  1882. return choice.fold(function () {
  1883. return missingKey(path, key);
  1884. }, function (chosen) {
  1885. return chooseFrom(path, strength, input, branches, chosen);
  1886. });
  1887. };
  1888. var toString = function () {
  1889. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1890. };
  1891. return {
  1892. extract: extract,
  1893. toString: toString
  1894. };
  1895. };
  1896. var _anyValue = value$1(SimpleResult.svalue);
  1897. var valueOf = function (validator) {
  1898. return value$1(function (v) {
  1899. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1900. });
  1901. };
  1902. var setOf$1 = function (validator, prop) {
  1903. return setOf(function (v) {
  1904. return SimpleResult.fromResult(validator(v));
  1905. }, prop);
  1906. };
  1907. var extract = function (label, prop, strength, obj) {
  1908. var res = prop.extract([label], strength, obj);
  1909. return SimpleResult.mapError(res, function (errs) {
  1910. return {
  1911. input: obj,
  1912. errors: errs
  1913. };
  1914. });
  1915. };
  1916. var asRaw = function (label, prop, obj) {
  1917. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1918. };
  1919. var getOrDie = function (extraction) {
  1920. return extraction.fold(function (errInfo) {
  1921. throw new Error(formatError(errInfo));
  1922. }, identity);
  1923. };
  1924. var asRawOrDie = function (label, prop, obj) {
  1925. return getOrDie(asRaw(label, prop, obj));
  1926. };
  1927. var formatError = function (errInfo) {
  1928. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1929. };
  1930. var choose$1 = function (key, branches) {
  1931. return choose(key, map(branches, objOf));
  1932. };
  1933. var anyValue$1 = constant(_anyValue);
  1934. var typedValue = function (validator, expectedType) {
  1935. return value$1(function (a) {
  1936. var actualType = typeof a;
  1937. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1938. });
  1939. };
  1940. var functionProcessor = typedValue(isFunction, 'function');
  1941. var strict$1 = function (key) {
  1942. return field(key, key, strict(), anyValue());
  1943. };
  1944. var strictOf = function (key, schema) {
  1945. return field(key, key, strict(), schema);
  1946. };
  1947. var strictFunction = function (key) {
  1948. return strictOf(key, functionProcessor);
  1949. };
  1950. var forbid = function (key, message) {
  1951. return field(key, key, asOption(), value$1(function (v) {
  1952. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1953. }));
  1954. };
  1955. var strictObjOf = function (key, objSchema) {
  1956. return field(key, key, strict(), objOf(objSchema));
  1957. };
  1958. var option = function (key) {
  1959. return field(key, key, asOption(), anyValue());
  1960. };
  1961. var optionOf = function (key, schema) {
  1962. return field(key, key, asOption(), schema);
  1963. };
  1964. var optionObjOf = function (key, objSchema) {
  1965. return optionOf(key, objOf(objSchema));
  1966. };
  1967. var optionObjOfOnly = function (key, objSchema) {
  1968. return optionOf(key, objOfOnly(objSchema));
  1969. };
  1970. var defaulted$1 = function (key, fallback) {
  1971. return field(key, key, defaulted(fallback), anyValue());
  1972. };
  1973. var defaultedOf = function (key, fallback, schema) {
  1974. return field(key, key, defaulted(fallback), schema);
  1975. };
  1976. var defaultedObjOf = function (key, fallback, objSchema) {
  1977. return defaultedOf(key, fallback, objOf(objSchema));
  1978. };
  1979. var state$1 = function (okey, instantiator) {
  1980. return state(okey, instantiator);
  1981. };
  1982. var ancestor = function (scope, transform, isRoot) {
  1983. var element = scope.dom();
  1984. var stop = isFunction(isRoot) ? isRoot : constant(false);
  1985. while (element.parentNode) {
  1986. element = element.parentNode;
  1987. var el = Element.fromDom(element);
  1988. var transformed = transform(el);
  1989. if (transformed.isSome()) {
  1990. return transformed;
  1991. } else if (stop(el)) {
  1992. break;
  1993. }
  1994. }
  1995. return Option.none();
  1996. };
  1997. var closest = function (scope, transform, isRoot) {
  1998. var current = transform(scope);
  1999. return current.orThunk(function () {
  2000. return isRoot(scope) ? Option.none() : ancestor(scope, transform, isRoot);
  2001. });
  2002. };
  2003. var isSource = function (component, simulatedEvent) {
  2004. return eq(component.element(), simulatedEvent.event().target());
  2005. };
  2006. var nu$4 = function (parts) {
  2007. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2008. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2009. }
  2010. return asRawOrDie('Extracting event.handler', objOfOnly([
  2011. defaulted$1('can', constant(true)),
  2012. defaulted$1('abort', constant(false)),
  2013. defaulted$1('run', noop)
  2014. ]), parts);
  2015. };
  2016. var all$1 = function (handlers, f) {
  2017. return function () {
  2018. var args = [];
  2019. for (var _i = 0; _i < arguments.length; _i++) {
  2020. args[_i] = arguments[_i];
  2021. }
  2022. return foldl(handlers, function (acc, handler) {
  2023. return acc && f(handler).apply(undefined, args);
  2024. }, true);
  2025. };
  2026. };
  2027. var any = function (handlers, f) {
  2028. return function () {
  2029. var args = [];
  2030. for (var _i = 0; _i < arguments.length; _i++) {
  2031. args[_i] = arguments[_i];
  2032. }
  2033. return foldl(handlers, function (acc, handler) {
  2034. return acc || f(handler).apply(undefined, args);
  2035. }, false);
  2036. };
  2037. };
  2038. var read = function (handler) {
  2039. return isFunction(handler) ? {
  2040. can: constant(true),
  2041. abort: constant(false),
  2042. run: handler
  2043. } : handler;
  2044. };
  2045. var fuse = function (handlers) {
  2046. var can = all$1(handlers, function (handler) {
  2047. return handler.can;
  2048. });
  2049. var abort = any(handlers, function (handler) {
  2050. return handler.abort;
  2051. });
  2052. var run = function () {
  2053. var args = [];
  2054. for (var _i = 0; _i < arguments.length; _i++) {
  2055. args[_i] = arguments[_i];
  2056. }
  2057. each$1(handlers, function (handler) {
  2058. handler.run.apply(undefined, args);
  2059. });
  2060. };
  2061. return nu$4({
  2062. can: can,
  2063. abort: abort,
  2064. run: run
  2065. });
  2066. };
  2067. var derive = function (configs) {
  2068. return wrapAll$1(configs);
  2069. };
  2070. var abort = function (name, predicate) {
  2071. return {
  2072. key: name,
  2073. value: nu$4({ abort: predicate })
  2074. };
  2075. };
  2076. var can = function (name, predicate) {
  2077. return {
  2078. key: name,
  2079. value: nu$4({ can: predicate })
  2080. };
  2081. };
  2082. var run = function (name, handler) {
  2083. return {
  2084. key: name,
  2085. value: nu$4({ run: handler })
  2086. };
  2087. };
  2088. var runActionExtra = function (name, action, extra) {
  2089. return {
  2090. key: name,
  2091. value: nu$4({
  2092. run: function (component, simulatedEvent) {
  2093. action.apply(undefined, [
  2094. component,
  2095. simulatedEvent
  2096. ].concat(extra));
  2097. }
  2098. })
  2099. };
  2100. };
  2101. var runOnName = function (name) {
  2102. return function (handler) {
  2103. return run(name, handler);
  2104. };
  2105. };
  2106. var runOnSourceName = function (name) {
  2107. return function (handler) {
  2108. return {
  2109. key: name,
  2110. value: nu$4({
  2111. run: function (component, simulatedEvent) {
  2112. if (isSource(component, simulatedEvent)) {
  2113. handler(component, simulatedEvent);
  2114. }
  2115. }
  2116. })
  2117. };
  2118. };
  2119. };
  2120. var redirectToUid = function (name, uid) {
  2121. return run(name, function (component, simulatedEvent) {
  2122. component.getSystem().getByUid(uid).each(function (redirectee) {
  2123. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2124. });
  2125. });
  2126. };
  2127. var redirectToPart = function (name, detail, partName) {
  2128. var uid = detail.partUids[partName];
  2129. return redirectToUid(name, uid);
  2130. };
  2131. var cutter = function (name) {
  2132. return run(name, function (component, simulatedEvent) {
  2133. simulatedEvent.cut();
  2134. });
  2135. };
  2136. var stopper = function (name) {
  2137. return run(name, function (component, simulatedEvent) {
  2138. simulatedEvent.stop();
  2139. });
  2140. };
  2141. var runOnSource = function (name, f) {
  2142. return runOnSourceName(name)(f);
  2143. };
  2144. var runOnAttached = runOnSourceName(attachedToDom());
  2145. var runOnDetached = runOnSourceName(detachedFromDom());
  2146. var runOnInit = runOnSourceName(systemInit());
  2147. var runOnExecute = runOnName(execute());
  2148. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2149. var delegate = apiFunction.toString();
  2150. var endIndex = delegate.indexOf(')') + 1;
  2151. var openBracketIndex = delegate.indexOf('(');
  2152. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2153. f.toFunctionAnnotation = function () {
  2154. return {
  2155. name: apiName,
  2156. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2157. };
  2158. };
  2159. return f;
  2160. };
  2161. var cleanParameters = function (parameters) {
  2162. return map$1(parameters, function (p) {
  2163. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2164. });
  2165. };
  2166. var markAsExtraApi = function (f, extraName) {
  2167. var delegate = f.toString();
  2168. var endIndex = delegate.indexOf(')') + 1;
  2169. var openBracketIndex = delegate.indexOf('(');
  2170. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2171. f.toFunctionAnnotation = function () {
  2172. return {
  2173. name: extraName,
  2174. parameters: cleanParameters(parameters)
  2175. };
  2176. };
  2177. return f;
  2178. };
  2179. var markAsSketchApi = function (f, apiFunction) {
  2180. var delegate = apiFunction.toString();
  2181. var endIndex = delegate.indexOf(')') + 1;
  2182. var openBracketIndex = delegate.indexOf('(');
  2183. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2184. f.toFunctionAnnotation = function () {
  2185. return {
  2186. name: 'OVERRIDE',
  2187. parameters: cleanParameters(parameters.slice(1))
  2188. };
  2189. };
  2190. return f;
  2191. };
  2192. var nu$5 = function (s) {
  2193. return {
  2194. classes: s.classes !== undefined ? s.classes : [],
  2195. attributes: s.attributes !== undefined ? s.attributes : {},
  2196. styles: s.styles !== undefined ? s.styles : {}
  2197. };
  2198. };
  2199. var merge$1 = function (defnA, mod) {
  2200. return __assign(__assign({}, defnA), {
  2201. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2202. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2203. classes: defnA.classes.concat(mod.classes)
  2204. });
  2205. };
  2206. var executeEvent = function (bConfig, bState, executor) {
  2207. return runOnExecute(function (component) {
  2208. executor(component, bConfig, bState);
  2209. });
  2210. };
  2211. var loadEvent = function (bConfig, bState, f) {
  2212. return runOnInit(function (component, simulatedEvent) {
  2213. f(component, bConfig, bState);
  2214. });
  2215. };
  2216. var create = function (schema, name, active, apis, extra, state) {
  2217. var configSchema = objOfOnly(schema);
  2218. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2219. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2220. };
  2221. var createModes = function (modes, name, active, apis, extra, state) {
  2222. var configSchema = modes;
  2223. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2224. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2225. };
  2226. var wrapApi = function (bName, apiFunction, apiName) {
  2227. var f = function (component) {
  2228. var rest = [];
  2229. for (var _i = 1; _i < arguments.length; _i++) {
  2230. rest[_i - 1] = arguments[_i];
  2231. }
  2232. var args = [component].concat(rest);
  2233. return component.config({ name: constant(bName) }).fold(function () {
  2234. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2235. }, function (info) {
  2236. var rest = Array.prototype.slice.call(args, 1);
  2237. return apiFunction.apply(undefined, [
  2238. component,
  2239. info.config,
  2240. info.state
  2241. ].concat(rest));
  2242. });
  2243. };
  2244. return markAsBehaviourApi(f, apiName, apiFunction);
  2245. };
  2246. var revokeBehaviour = function (name) {
  2247. return {
  2248. key: name,
  2249. value: undefined
  2250. };
  2251. };
  2252. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2253. var getConfig = function (info) {
  2254. return hasNonNullableKey(info, name) ? info[name]() : Option.none();
  2255. };
  2256. var wrappedApis = map(apis, function (apiF, apiName) {
  2257. return wrapApi(name, apiF, apiName);
  2258. });
  2259. var wrappedExtra = map(extra, function (extraF, extraName) {
  2260. return markAsExtraApi(extraF, extraName);
  2261. });
  2262. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2263. revoke: curry(revokeBehaviour, name),
  2264. config: function (spec) {
  2265. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  2266. return {
  2267. key: name,
  2268. value: {
  2269. config: prepared,
  2270. me: me,
  2271. configAsRaw: cached(function () {
  2272. return asRawOrDie(name + '-config', configSchema, spec);
  2273. }),
  2274. initialConfig: spec,
  2275. state: state
  2276. }
  2277. };
  2278. },
  2279. schema: function () {
  2280. return schemaSchema;
  2281. },
  2282. exhibit: function (info, base) {
  2283. return getConfig(info).bind(function (behaviourInfo) {
  2284. return get(active, 'exhibit').map(function (exhibitor) {
  2285. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2286. });
  2287. }).getOr(nu$5({}));
  2288. },
  2289. name: function () {
  2290. return name;
  2291. },
  2292. handlers: function (info) {
  2293. return getConfig(info).map(function (behaviourInfo) {
  2294. var getEvents = get(active, 'events').getOr(function () {
  2295. return {};
  2296. });
  2297. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2298. }).getOr({});
  2299. }
  2300. });
  2301. return me;
  2302. };
  2303. var NoState = {
  2304. init: function () {
  2305. return nu$6({
  2306. readState: function () {
  2307. return 'No State required';
  2308. }
  2309. });
  2310. }
  2311. };
  2312. var nu$6 = function (spec) {
  2313. return spec;
  2314. };
  2315. var derive$1 = function (capabilities) {
  2316. return wrapAll$1(capabilities);
  2317. };
  2318. var simpleSchema = objOfOnly([
  2319. strict$1('fields'),
  2320. strict$1('name'),
  2321. defaulted$1('active', {}),
  2322. defaulted$1('apis', {}),
  2323. defaulted$1('state', NoState),
  2324. defaulted$1('extra', {})
  2325. ]);
  2326. var create$1 = function (data) {
  2327. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  2328. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2329. };
  2330. var modeSchema = objOfOnly([
  2331. strict$1('branchKey'),
  2332. strict$1('branches'),
  2333. strict$1('name'),
  2334. defaulted$1('active', {}),
  2335. defaulted$1('apis', {}),
  2336. defaulted$1('state', NoState),
  2337. defaulted$1('extra', {})
  2338. ]);
  2339. var createModes$1 = function (data) {
  2340. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  2341. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2342. };
  2343. var revoke = constant(undefined);
  2344. var rawSet = function (dom, key, value) {
  2345. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2346. dom.setAttribute(key, value + '');
  2347. } else {
  2348. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2349. throw new Error('Attribute value was not simple');
  2350. }
  2351. };
  2352. var set = function (element, key, value) {
  2353. rawSet(element.dom(), key, value);
  2354. };
  2355. var setAll = function (element, attrs) {
  2356. var dom = element.dom();
  2357. each(attrs, function (v, k) {
  2358. rawSet(dom, k, v);
  2359. });
  2360. };
  2361. var get$1 = function (element, key) {
  2362. var v = element.dom().getAttribute(key);
  2363. return v === null ? undefined : v;
  2364. };
  2365. var has$1 = function (element, key) {
  2366. var dom = element.dom();
  2367. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2368. };
  2369. var remove$1 = function (element, key) {
  2370. element.dom().removeAttribute(key);
  2371. };
  2372. var read$1 = function (element, attr) {
  2373. var value = get$1(element, attr);
  2374. return value === undefined || value === '' ? [] : value.split(' ');
  2375. };
  2376. var add = function (element, attr, id) {
  2377. var old = read$1(element, attr);
  2378. var nu = old.concat([id]);
  2379. set(element, attr, nu.join(' '));
  2380. return true;
  2381. };
  2382. var remove$2 = function (element, attr, id) {
  2383. var nu = filter(read$1(element, attr), function (v) {
  2384. return v !== id;
  2385. });
  2386. if (nu.length > 0) {
  2387. set(element, attr, nu.join(' '));
  2388. } else {
  2389. remove$1(element, attr);
  2390. }
  2391. return false;
  2392. };
  2393. var supports = function (element) {
  2394. return element.dom().classList !== undefined;
  2395. };
  2396. var get$2 = function (element) {
  2397. return read$1(element, 'class');
  2398. };
  2399. var add$1 = function (element, clazz) {
  2400. return add(element, 'class', clazz);
  2401. };
  2402. var remove$3 = function (element, clazz) {
  2403. return remove$2(element, 'class', clazz);
  2404. };
  2405. var add$2 = function (element, clazz) {
  2406. if (supports(element)) {
  2407. element.dom().classList.add(clazz);
  2408. } else {
  2409. add$1(element, clazz);
  2410. }
  2411. };
  2412. var cleanClass = function (element) {
  2413. var classList = supports(element) ? element.dom().classList : get$2(element);
  2414. if (classList.length === 0) {
  2415. remove$1(element, 'class');
  2416. }
  2417. };
  2418. var remove$4 = function (element, clazz) {
  2419. if (supports(element)) {
  2420. var classList = element.dom().classList;
  2421. classList.remove(clazz);
  2422. } else {
  2423. remove$3(element, clazz);
  2424. }
  2425. cleanClass(element);
  2426. };
  2427. var has$2 = function (element, clazz) {
  2428. return supports(element) && element.dom().classList.contains(clazz);
  2429. };
  2430. var swap = function (element, addCls, removeCls) {
  2431. remove$4(element, removeCls);
  2432. add$2(element, addCls);
  2433. };
  2434. var toAlpha = function (component, swapConfig, swapState) {
  2435. swap(component.element(), swapConfig.alpha, swapConfig.omega);
  2436. };
  2437. var toOmega = function (component, swapConfig, swapState) {
  2438. swap(component.element(), swapConfig.omega, swapConfig.alpha);
  2439. };
  2440. var clear = function (component, swapConfig, swapState) {
  2441. remove$4(component.element(), swapConfig.alpha);
  2442. remove$4(component.element(), swapConfig.omega);
  2443. };
  2444. var isAlpha = function (component, swapConfig, swapState) {
  2445. return has$2(component.element(), swapConfig.alpha);
  2446. };
  2447. var isOmega = function (component, swapConfig, swapState) {
  2448. return has$2(component.element(), swapConfig.omega);
  2449. };
  2450. var SwapApis = /*#__PURE__*/Object.freeze({
  2451. __proto__: null,
  2452. toAlpha: toAlpha,
  2453. toOmega: toOmega,
  2454. isAlpha: isAlpha,
  2455. isOmega: isOmega,
  2456. clear: clear
  2457. });
  2458. var SwapSchema = [
  2459. strict$1('alpha'),
  2460. strict$1('omega')
  2461. ];
  2462. var Swapping = create$1({
  2463. fields: SwapSchema,
  2464. name: 'swapping',
  2465. apis: SwapApis
  2466. });
  2467. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2468. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  2469. }
  2470. var ancestor$1 = function (scope, predicate, isRoot) {
  2471. var element = scope.dom();
  2472. var stop = isFunction(isRoot) ? isRoot : constant(false);
  2473. while (element.parentNode) {
  2474. element = element.parentNode;
  2475. var el = Element.fromDom(element);
  2476. if (predicate(el)) {
  2477. return Option.some(el);
  2478. } else if (stop(el)) {
  2479. break;
  2480. }
  2481. }
  2482. return Option.none();
  2483. };
  2484. var closest$1 = function (scope, predicate, isRoot) {
  2485. var is = function (s, test) {
  2486. return test(s);
  2487. };
  2488. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  2489. };
  2490. var descendant = function (scope, predicate) {
  2491. var descend = function (node) {
  2492. for (var i = 0; i < node.childNodes.length; i++) {
  2493. var child_1 = Element.fromDom(node.childNodes[i]);
  2494. if (predicate(child_1)) {
  2495. return Option.some(child_1);
  2496. }
  2497. var res = descend(node.childNodes[i]);
  2498. if (res.isSome()) {
  2499. return res;
  2500. }
  2501. }
  2502. return Option.none();
  2503. };
  2504. return descend(scope.dom());
  2505. };
  2506. var focus$1 = function (element) {
  2507. element.dom().focus();
  2508. };
  2509. var blur = function (element) {
  2510. element.dom().blur();
  2511. };
  2512. var hasFocus = function (element) {
  2513. var doc = owner(element).dom();
  2514. return element.dom() === doc.activeElement;
  2515. };
  2516. var active = function (_doc) {
  2517. var doc = _doc !== undefined ? _doc.dom() : domGlobals.document;
  2518. return Option.from(doc.activeElement).map(Element.fromDom);
  2519. };
  2520. var search = function (element) {
  2521. return active(owner(element)).filter(function (e) {
  2522. return element.dom().contains(e.dom());
  2523. });
  2524. };
  2525. var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2526. var global$2 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2527. var openLink = function (target) {
  2528. var link = domGlobals.document.createElement('a');
  2529. link.target = '_blank';
  2530. link.href = target.href;
  2531. link.rel = 'noreferrer noopener';
  2532. var nuEvt = domGlobals.document.createEvent('MouseEvents');
  2533. nuEvt.initMouseEvent('click', true, true, domGlobals.window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2534. domGlobals.document.body.appendChild(link);
  2535. link.dispatchEvent(nuEvt);
  2536. domGlobals.document.body.removeChild(link);
  2537. };
  2538. var TinyCodeDupe = { openLink: openLink };
  2539. var isSkinDisabled = function (editor) {
  2540. return editor.settings.skin === false;
  2541. };
  2542. var readOnlyOnInit = function (editor) {
  2543. return false;
  2544. };
  2545. var formatChanged = 'formatChanged';
  2546. var orientationChanged = 'orientationChanged';
  2547. var dropupDismissed = 'dropupDismissed';
  2548. var TinyChannels = {
  2549. formatChanged: constant(formatChanged),
  2550. orientationChanged: constant(orientationChanged),
  2551. dropupDismissed: constant(dropupDismissed)
  2552. };
  2553. var fromHtml$1 = function (html, scope) {
  2554. var doc = scope || domGlobals.document;
  2555. var div = doc.createElement('div');
  2556. div.innerHTML = html;
  2557. return children(Element.fromDom(div));
  2558. };
  2559. var get$3 = function (element) {
  2560. return element.dom().innerHTML;
  2561. };
  2562. var set$1 = function (element, content) {
  2563. var owner$1 = owner(element);
  2564. var docDom = owner$1.dom();
  2565. var fragment = Element.fromDom(docDom.createDocumentFragment());
  2566. var contentElements = fromHtml$1(content, docDom);
  2567. append$1(fragment, contentElements);
  2568. empty(element);
  2569. append(element, fragment);
  2570. };
  2571. var getOuter = function (element) {
  2572. var container = Element.fromTag('div');
  2573. var clone = Element.fromDom(element.dom().cloneNode(true));
  2574. append(container, clone);
  2575. return get$3(container);
  2576. };
  2577. var clone = function (original, isDeep) {
  2578. return Element.fromDom(original.dom().cloneNode(isDeep));
  2579. };
  2580. var shallow$1 = function (original) {
  2581. return clone(original, false);
  2582. };
  2583. var getHtml = function (element) {
  2584. var clone = shallow$1(element);
  2585. return getOuter(clone);
  2586. };
  2587. var element = function (elem) {
  2588. return getHtml(elem);
  2589. };
  2590. var chooseChannels = function (channels, message) {
  2591. return message.universal() ? channels : filter(channels, function (ch) {
  2592. return contains(message.channels(), ch);
  2593. });
  2594. };
  2595. var events = function (receiveConfig) {
  2596. return derive([run(receive(), function (component, message) {
  2597. var channelMap = receiveConfig.channels;
  2598. var channels = keys(channelMap);
  2599. var receivingData = message;
  2600. var targetChannels = chooseChannels(channels, receivingData);
  2601. each$1(targetChannels, function (ch) {
  2602. var channelInfo = channelMap[ch];
  2603. var channelSchema = channelInfo.schema;
  2604. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, receivingData.data());
  2605. channelInfo.onReceive(component, data);
  2606. });
  2607. })]);
  2608. };
  2609. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2610. __proto__: null,
  2611. events: events
  2612. });
  2613. var unknown$3 = 'unknown';
  2614. var EventConfiguration;
  2615. (function (EventConfiguration) {
  2616. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2617. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2618. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2619. }(EventConfiguration || (EventConfiguration = {})));
  2620. var eventConfig = Cell({});
  2621. var makeEventLogger = function (eventName, initialTarget) {
  2622. var sequence = [];
  2623. var startTime = new Date().getTime();
  2624. return {
  2625. logEventCut: function (name, target, purpose) {
  2626. sequence.push({
  2627. outcome: 'cut',
  2628. target: target,
  2629. purpose: purpose
  2630. });
  2631. },
  2632. logEventStopped: function (name, target, purpose) {
  2633. sequence.push({
  2634. outcome: 'stopped',
  2635. target: target,
  2636. purpose: purpose
  2637. });
  2638. },
  2639. logNoParent: function (name, target, purpose) {
  2640. sequence.push({
  2641. outcome: 'no-parent',
  2642. target: target,
  2643. purpose: purpose
  2644. });
  2645. },
  2646. logEventNoHandlers: function (name, target) {
  2647. sequence.push({
  2648. outcome: 'no-handlers-left',
  2649. target: target
  2650. });
  2651. },
  2652. logEventResponse: function (name, target, purpose) {
  2653. sequence.push({
  2654. outcome: 'response',
  2655. purpose: purpose,
  2656. target: target
  2657. });
  2658. },
  2659. write: function () {
  2660. var finishTime = new Date().getTime();
  2661. if (contains([
  2662. 'mousemove',
  2663. 'mouseover',
  2664. 'mouseout',
  2665. systemInit()
  2666. ], eventName)) {
  2667. return;
  2668. }
  2669. domGlobals.console.log(eventName, {
  2670. event: eventName,
  2671. time: finishTime - startTime,
  2672. target: initialTarget.dom(),
  2673. sequence: map$1(sequence, function (s) {
  2674. if (!contains([
  2675. 'cut',
  2676. 'stopped',
  2677. 'response'
  2678. ], s.outcome)) {
  2679. return s.outcome;
  2680. } else {
  2681. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2682. }
  2683. })
  2684. });
  2685. }
  2686. };
  2687. };
  2688. var processEvent = function (eventName, initialTarget, f) {
  2689. var status = get(eventConfig.get(), eventName).orThunk(function () {
  2690. var patterns = keys(eventConfig.get());
  2691. return findMap(patterns, function (p) {
  2692. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  2693. });
  2694. }).getOr(EventConfiguration.NORMAL);
  2695. switch (status) {
  2696. case EventConfiguration.NORMAL:
  2697. return f(noLogger());
  2698. case EventConfiguration.LOGGING: {
  2699. var logger = makeEventLogger(eventName, initialTarget);
  2700. var output = f(logger);
  2701. logger.write();
  2702. return output;
  2703. }
  2704. case EventConfiguration.STOP:
  2705. return true;
  2706. }
  2707. };
  2708. var path = [
  2709. 'alloy/data/Fields',
  2710. 'alloy/debugging/Debugging'
  2711. ];
  2712. var getTrace = function () {
  2713. var err = new Error();
  2714. if (err.stack !== undefined) {
  2715. var lines = err.stack.split('\n');
  2716. return find$2(lines, function (line) {
  2717. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2718. return line.indexOf(p) > -1;
  2719. });
  2720. }).getOr(unknown$3);
  2721. } else {
  2722. return unknown$3;
  2723. }
  2724. };
  2725. var ignoreEvent = {
  2726. logEventCut: noop,
  2727. logEventStopped: noop,
  2728. logNoParent: noop,
  2729. logEventNoHandlers: noop,
  2730. logEventResponse: noop,
  2731. write: noop
  2732. };
  2733. var monitorEvent = function (eventName, initialTarget, f) {
  2734. return processEvent(eventName, initialTarget, f);
  2735. };
  2736. var noLogger = constant(ignoreEvent);
  2737. var menuFields = constant([
  2738. strict$1('menu'),
  2739. strict$1('selectedMenu')
  2740. ]);
  2741. var itemFields = constant([
  2742. strict$1('item'),
  2743. strict$1('selectedItem')
  2744. ]);
  2745. var schema = constant(objOf(itemFields().concat(menuFields())));
  2746. var itemSchema = constant(objOf(itemFields()));
  2747. var _initSize = strictObjOf('initSize', [
  2748. strict$1('numColumns'),
  2749. strict$1('numRows')
  2750. ]);
  2751. var itemMarkers = function () {
  2752. return strictOf('markers', itemSchema());
  2753. };
  2754. var tieredMenuMarkers = function () {
  2755. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2756. };
  2757. var markers = function (required) {
  2758. return strictObjOf('markers', map$1(required, strict$1));
  2759. };
  2760. var onPresenceHandler = function (label, fieldName, presence) {
  2761. var trace = getTrace();
  2762. return field(fieldName, fieldName, presence, valueOf(function (f) {
  2763. return Result.value(function () {
  2764. var args = [];
  2765. for (var _i = 0; _i < arguments.length; _i++) {
  2766. args[_i] = arguments[_i];
  2767. }
  2768. return f.apply(undefined, args);
  2769. });
  2770. }));
  2771. };
  2772. var onHandler = function (fieldName) {
  2773. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  2774. };
  2775. var onKeyboardHandler = function (fieldName) {
  2776. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  2777. };
  2778. var onStrictHandler = function (fieldName) {
  2779. return onPresenceHandler('onHandler', fieldName, strict());
  2780. };
  2781. var onStrictKeyboardHandler = function (fieldName) {
  2782. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  2783. };
  2784. var output = function (name, value) {
  2785. return state$1(name, constant(value));
  2786. };
  2787. var snapshot = function (name) {
  2788. return state$1(name, identity);
  2789. };
  2790. var initSize = constant(_initSize);
  2791. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  2792. onStrictHandler('onReceive'),
  2793. defaulted$1('schema', anyValue$1())
  2794. ])))];
  2795. var Receiving = create$1({
  2796. fields: ReceivingSchema,
  2797. name: 'receiving',
  2798. active: ActiveReceiving
  2799. });
  2800. var updateAriaState = function (component, toggleConfig, toggleState) {
  2801. var ariaInfo = toggleConfig.aria;
  2802. ariaInfo.update(component, ariaInfo, toggleState.get());
  2803. };
  2804. var updateClass = function (component, toggleConfig, toggleState) {
  2805. toggleConfig.toggleClass.each(function (toggleClass) {
  2806. if (toggleState.get()) {
  2807. add$2(component.element(), toggleClass);
  2808. } else {
  2809. remove$4(component.element(), toggleClass);
  2810. }
  2811. });
  2812. };
  2813. var toggle = function (component, toggleConfig, toggleState) {
  2814. set$2(component, toggleConfig, toggleState, !toggleState.get());
  2815. };
  2816. var on = function (component, toggleConfig, toggleState) {
  2817. toggleState.set(true);
  2818. updateClass(component, toggleConfig, toggleState);
  2819. updateAriaState(component, toggleConfig, toggleState);
  2820. };
  2821. var off = function (component, toggleConfig, toggleState) {
  2822. toggleState.set(false);
  2823. updateClass(component, toggleConfig, toggleState);
  2824. updateAriaState(component, toggleConfig, toggleState);
  2825. };
  2826. var set$2 = function (component, toggleConfig, toggleState, state) {
  2827. var action = state ? on : off;
  2828. action(component, toggleConfig, toggleState);
  2829. };
  2830. var isOn = function (component, toggleConfig, toggleState) {
  2831. return toggleState.get();
  2832. };
  2833. var onLoad = function (component, toggleConfig, toggleState) {
  2834. set$2(component, toggleConfig, toggleState, toggleConfig.selected);
  2835. };
  2836. var ToggleApis = /*#__PURE__*/Object.freeze({
  2837. __proto__: null,
  2838. onLoad: onLoad,
  2839. toggle: toggle,
  2840. isOn: isOn,
  2841. on: on,
  2842. off: off,
  2843. set: set$2
  2844. });
  2845. var exhibit = function () {
  2846. return nu$5({});
  2847. };
  2848. var events$1 = function (toggleConfig, toggleState) {
  2849. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2850. var load = loadEvent(toggleConfig, toggleState, onLoad);
  2851. return derive(flatten([
  2852. toggleConfig.toggleOnExecute ? [execute] : [],
  2853. [load]
  2854. ]));
  2855. };
  2856. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2857. __proto__: null,
  2858. exhibit: exhibit,
  2859. events: events$1
  2860. });
  2861. var SetupBehaviourCellState = function (initialState) {
  2862. var init = function () {
  2863. var cell = Cell(initialState);
  2864. var get = function () {
  2865. return cell.get();
  2866. };
  2867. var set = function (newState) {
  2868. return cell.set(newState);
  2869. };
  2870. var clear = function () {
  2871. return cell.set(initialState);
  2872. };
  2873. var readState = function () {
  2874. return cell.get();
  2875. };
  2876. return {
  2877. get: get,
  2878. set: set,
  2879. clear: clear,
  2880. readState: readState
  2881. };
  2882. };
  2883. return { init: init };
  2884. };
  2885. var updatePressed = function (component, ariaInfo, status) {
  2886. set(component.element(), 'aria-pressed', status);
  2887. if (ariaInfo.syncWithExpanded) {
  2888. updateExpanded(component, ariaInfo, status);
  2889. }
  2890. };
  2891. var updateSelected = function (component, ariaInfo, status) {
  2892. set(component.element(), 'aria-selected', status);
  2893. };
  2894. var updateChecked = function (component, ariaInfo, status) {
  2895. set(component.element(), 'aria-checked', status);
  2896. };
  2897. var updateExpanded = function (component, ariaInfo, status) {
  2898. set(component.element(), 'aria-expanded', status);
  2899. };
  2900. var ToggleSchema = [
  2901. defaulted$1('selected', false),
  2902. option('toggleClass'),
  2903. defaulted$1('toggleOnExecute', true),
  2904. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  2905. pressed: [
  2906. defaulted$1('syncWithExpanded', false),
  2907. output('update', updatePressed)
  2908. ],
  2909. checked: [output('update', updateChecked)],
  2910. expanded: [output('update', updateExpanded)],
  2911. selected: [output('update', updateSelected)],
  2912. none: [output('update', noop)]
  2913. }))
  2914. ];
  2915. var Toggling = create$1({
  2916. fields: ToggleSchema,
  2917. name: 'toggling',
  2918. active: ActiveToggle,
  2919. apis: ToggleApis,
  2920. state: SetupBehaviourCellState(false)
  2921. });
  2922. var format = function (command, update) {
  2923. return Receiving.config({
  2924. channels: wrap$1(TinyChannels.formatChanged(), {
  2925. onReceive: function (button, data) {
  2926. if (data.command === command) {
  2927. update(button, data.state);
  2928. }
  2929. }
  2930. })
  2931. });
  2932. };
  2933. var orientation = function (onReceive) {
  2934. return Receiving.config({ channels: wrap$1(TinyChannels.orientationChanged(), { onReceive: onReceive }) });
  2935. };
  2936. var receive$1 = function (channel, onReceive) {
  2937. return {
  2938. key: channel,
  2939. value: { onReceive: onReceive }
  2940. };
  2941. };
  2942. var Receivers = {
  2943. format: format,
  2944. orientation: orientation,
  2945. receive: receive$1
  2946. };
  2947. var prefix = 'tinymce-mobile';
  2948. var resolve = function (p) {
  2949. return prefix + '-' + p;
  2950. };
  2951. var Styles = {
  2952. resolve: resolve,
  2953. prefix: constant(prefix)
  2954. };
  2955. var pointerEvents = function () {
  2956. var onClick = function (component, simulatedEvent) {
  2957. simulatedEvent.stop();
  2958. emitExecute(component);
  2959. };
  2960. return [
  2961. run(click(), onClick),
  2962. run(tap(), onClick),
  2963. cutter(touchstart()),
  2964. cutter(mousedown())
  2965. ];
  2966. };
  2967. var events$2 = function (optAction) {
  2968. var executeHandler = function (action) {
  2969. return runOnExecute(function (component, simulatedEvent) {
  2970. action(component);
  2971. simulatedEvent.stop();
  2972. });
  2973. };
  2974. return derive(flatten([
  2975. optAction.map(executeHandler).toArray(),
  2976. pointerEvents()
  2977. ]));
  2978. };
  2979. var focus$2 = function (component, focusConfig) {
  2980. if (!focusConfig.ignore) {
  2981. focus$1(component.element());
  2982. focusConfig.onFocus(component);
  2983. }
  2984. };
  2985. var blur$1 = function (component, focusConfig) {
  2986. if (!focusConfig.ignore) {
  2987. blur(component.element());
  2988. }
  2989. };
  2990. var isFocused = function (component) {
  2991. return hasFocus(component.element());
  2992. };
  2993. var FocusApis = /*#__PURE__*/Object.freeze({
  2994. __proto__: null,
  2995. focus: focus$2,
  2996. blur: blur$1,
  2997. isFocused: isFocused
  2998. });
  2999. var exhibit$1 = function (base, focusConfig) {
  3000. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3001. return nu$5(mod);
  3002. };
  3003. var events$3 = function (focusConfig) {
  3004. return derive([run(focus(), function (component, simulatedEvent) {
  3005. focus$2(component, focusConfig);
  3006. simulatedEvent.stop();
  3007. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3008. simulatedEvent.event().prevent();
  3009. })] : []));
  3010. };
  3011. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3012. __proto__: null,
  3013. exhibit: exhibit$1,
  3014. events: events$3
  3015. });
  3016. var FocusSchema = [
  3017. onHandler('onFocus'),
  3018. defaulted$1('stopMousedown', false),
  3019. defaulted$1('ignore', false)
  3020. ];
  3021. var Focusing = create$1({
  3022. fields: FocusSchema,
  3023. name: 'focusing',
  3024. active: ActiveFocus,
  3025. apis: FocusApis
  3026. });
  3027. var isSupported = function (dom) {
  3028. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  3029. };
  3030. var internalSet = function (dom, property, value) {
  3031. if (!isString(value)) {
  3032. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3033. throw new Error('CSS value must be a string: ' + value);
  3034. }
  3035. if (isSupported(dom)) {
  3036. dom.style.setProperty(property, value);
  3037. }
  3038. };
  3039. var internalRemove = function (dom, property) {
  3040. if (isSupported(dom)) {
  3041. dom.style.removeProperty(property);
  3042. }
  3043. };
  3044. var set$3 = function (element, property, value) {
  3045. var dom = element.dom();
  3046. internalSet(dom, property, value);
  3047. };
  3048. var setAll$1 = function (element, css) {
  3049. var dom = element.dom();
  3050. each(css, function (v, k) {
  3051. internalSet(dom, k, v);
  3052. });
  3053. };
  3054. var get$4 = function (element, property) {
  3055. var dom = element.dom();
  3056. var styles = domGlobals.window.getComputedStyle(dom);
  3057. var r = styles.getPropertyValue(property);
  3058. var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3059. return v === null ? undefined : v;
  3060. };
  3061. var getUnsafeProperty = function (dom, property) {
  3062. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  3063. };
  3064. var getRaw = function (element, property) {
  3065. var dom = element.dom();
  3066. var raw = getUnsafeProperty(dom, property);
  3067. return Option.from(raw).filter(function (r) {
  3068. return r.length > 0;
  3069. });
  3070. };
  3071. var remove$5 = function (element, property) {
  3072. var dom = element.dom();
  3073. internalRemove(dom, property);
  3074. if (has$1(element, 'style') && trim(get$1(element, 'style')) === '') {
  3075. remove$1(element, 'style');
  3076. }
  3077. };
  3078. var reflow = function (e) {
  3079. return e.dom().offsetWidth;
  3080. };
  3081. function Dimension (name, getOffset) {
  3082. var set = function (element, h) {
  3083. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3084. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3085. }
  3086. var dom = element.dom();
  3087. if (isSupported(dom)) {
  3088. dom.style[name] = h + 'px';
  3089. }
  3090. };
  3091. var get = function (element) {
  3092. var r = getOffset(element);
  3093. if (r <= 0 || r === null) {
  3094. var css = get$4(element, name);
  3095. return parseFloat(css) || 0;
  3096. }
  3097. return r;
  3098. };
  3099. var getOuter = get;
  3100. var aggregate = function (element, properties) {
  3101. return foldl(properties, function (acc, property) {
  3102. var val = get$4(element, property);
  3103. var value = val === undefined ? 0 : parseInt(val, 10);
  3104. return isNaN(value) ? acc : acc + value;
  3105. }, 0);
  3106. };
  3107. var max = function (element, value, properties) {
  3108. var cumulativeInclusions = aggregate(element, properties);
  3109. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3110. return absoluteMax;
  3111. };
  3112. return {
  3113. set: set,
  3114. get: get,
  3115. getOuter: getOuter,
  3116. aggregate: aggregate,
  3117. max: max
  3118. };
  3119. }
  3120. var api = Dimension('height', function (element) {
  3121. var dom = element.dom();
  3122. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3123. });
  3124. var get$5 = function (element) {
  3125. return api.get(element);
  3126. };
  3127. var ancestors = function (scope, predicate, isRoot) {
  3128. return filter(parents(scope, isRoot), predicate);
  3129. };
  3130. var siblings$1 = function (scope, predicate) {
  3131. return filter(siblings(scope), predicate);
  3132. };
  3133. var all$2 = function (selector) {
  3134. return all(selector);
  3135. };
  3136. var ancestors$1 = function (scope, selector, isRoot) {
  3137. return ancestors(scope, function (e) {
  3138. return is(e, selector);
  3139. }, isRoot);
  3140. };
  3141. var siblings$2 = function (scope, selector) {
  3142. return siblings$1(scope, function (e) {
  3143. return is(e, selector);
  3144. });
  3145. };
  3146. var descendants = function (scope, selector) {
  3147. return all(selector, scope);
  3148. };
  3149. var first = function (selector) {
  3150. return one(selector);
  3151. };
  3152. var ancestor$2 = function (scope, selector, isRoot) {
  3153. return ancestor$1(scope, function (e) {
  3154. return is(e, selector);
  3155. }, isRoot);
  3156. };
  3157. var descendant$1 = function (scope, selector) {
  3158. return one(selector, scope);
  3159. };
  3160. var closest$2 = function (scope, selector, isRoot) {
  3161. return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  3162. };
  3163. var BACKSPACE = function () {
  3164. return [8];
  3165. };
  3166. var TAB = function () {
  3167. return [9];
  3168. };
  3169. var ENTER = function () {
  3170. return [13];
  3171. };
  3172. var ESCAPE = function () {
  3173. return [27];
  3174. };
  3175. var SPACE = function () {
  3176. return [32];
  3177. };
  3178. var LEFT = function () {
  3179. return [37];
  3180. };
  3181. var UP = function () {
  3182. return [38];
  3183. };
  3184. var RIGHT = function () {
  3185. return [39];
  3186. };
  3187. var DOWN = function () {
  3188. return [40];
  3189. };
  3190. var cyclePrev = function (values, index, predicate) {
  3191. var before = reverse(values.slice(0, index));
  3192. var after = reverse(values.slice(index + 1));
  3193. return find$2(before.concat(after), predicate);
  3194. };
  3195. var tryPrev = function (values, index, predicate) {
  3196. var before = reverse(values.slice(0, index));
  3197. return find$2(before, predicate);
  3198. };
  3199. var cycleNext = function (values, index, predicate) {
  3200. var before = values.slice(0, index);
  3201. var after = values.slice(index + 1);
  3202. return find$2(after.concat(before), predicate);
  3203. };
  3204. var tryNext = function (values, index, predicate) {
  3205. var after = values.slice(index + 1);
  3206. return find$2(after, predicate);
  3207. };
  3208. var inSet = function (keys) {
  3209. return function (event) {
  3210. var raw = event.raw();
  3211. return contains(keys, raw.which);
  3212. };
  3213. };
  3214. var and = function (preds) {
  3215. return function (event) {
  3216. return forall(preds, function (pred) {
  3217. return pred(event);
  3218. });
  3219. };
  3220. };
  3221. var isShift = function (event) {
  3222. var raw = event.raw();
  3223. return raw.shiftKey === true;
  3224. };
  3225. var isControl = function (event) {
  3226. var raw = event.raw();
  3227. return raw.ctrlKey === true;
  3228. };
  3229. var isNotShift = not(isShift);
  3230. var rule = function (matches, action) {
  3231. return {
  3232. matches: matches,
  3233. classification: action
  3234. };
  3235. };
  3236. var choose$2 = function (transitions, event) {
  3237. var transition = find$2(transitions, function (t) {
  3238. return t.matches(event);
  3239. });
  3240. return transition.map(function (t) {
  3241. return t.classification;
  3242. });
  3243. };
  3244. var cat = function (arr) {
  3245. var r = [];
  3246. var push = function (x) {
  3247. r.push(x);
  3248. };
  3249. for (var i = 0; i < arr.length; i++) {
  3250. arr[i].each(push);
  3251. }
  3252. return r;
  3253. };
  3254. var sequence = function (arr) {
  3255. var r = [];
  3256. for (var i = 0; i < arr.length; i++) {
  3257. var x = arr[i];
  3258. if (x.isSome()) {
  3259. r.push(x.getOrDie());
  3260. } else {
  3261. return Option.none();
  3262. }
  3263. }
  3264. return Option.some(r);
  3265. };
  3266. var someIf = function (b, a) {
  3267. return b ? Option.some(a) : Option.none();
  3268. };
  3269. var cycleBy = function (value, delta, min, max) {
  3270. var r = value + delta;
  3271. return r > max ? min : r < min ? max : r;
  3272. };
  3273. var clamp = function (value, min, max) {
  3274. return Math.min(Math.max(value, min), max);
  3275. };
  3276. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3277. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  3278. each$1(highlighted, function (h) {
  3279. if (!exists(skip, function (skipComp) {
  3280. return skipComp.element() === h;
  3281. })) {
  3282. remove$4(h, hConfig.highlightClass);
  3283. component.getSystem().getByDom(h).each(function (target) {
  3284. hConfig.onDehighlight(component, target);
  3285. emit(target, dehighlight());
  3286. });
  3287. }
  3288. });
  3289. };
  3290. var dehighlightAll = function (component, hConfig, hState) {
  3291. return dehighlightAllExcept(component, hConfig, hState, []);
  3292. };
  3293. var dehighlight$1 = function (component, hConfig, hState, target) {
  3294. if (isHighlighted(component, hConfig, hState, target)) {
  3295. remove$4(target.element(), hConfig.highlightClass);
  3296. hConfig.onDehighlight(component, target);
  3297. emit(target, dehighlight());
  3298. }
  3299. };
  3300. var highlight$1 = function (component, hConfig, hState, target) {
  3301. dehighlightAllExcept(component, hConfig, hState, [target]);
  3302. if (!isHighlighted(component, hConfig, hState, target)) {
  3303. add$2(target.element(), hConfig.highlightClass);
  3304. hConfig.onHighlight(component, target);
  3305. emit(target, highlight());
  3306. }
  3307. };
  3308. var highlightFirst = function (component, hConfig, hState) {
  3309. getFirst(component, hConfig).each(function (firstComp) {
  3310. highlight$1(component, hConfig, hState, firstComp);
  3311. });
  3312. };
  3313. var highlightLast = function (component, hConfig, hState) {
  3314. getLast(component, hConfig).each(function (lastComp) {
  3315. highlight$1(component, hConfig, hState, lastComp);
  3316. });
  3317. };
  3318. var highlightAt = function (component, hConfig, hState, index) {
  3319. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3320. throw new Error(err);
  3321. }, function (firstComp) {
  3322. highlight$1(component, hConfig, hState, firstComp);
  3323. });
  3324. };
  3325. var highlightBy = function (component, hConfig, hState, predicate) {
  3326. var candidates = getCandidates(component, hConfig);
  3327. var targetComp = find$2(candidates, predicate);
  3328. targetComp.each(function (c) {
  3329. highlight$1(component, hConfig, hState, c);
  3330. });
  3331. };
  3332. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3333. return has$2(queryTarget.element(), hConfig.highlightClass);
  3334. };
  3335. var getHighlighted = function (component, hConfig, hState) {
  3336. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  3337. return component.getSystem().getByDom(e).toOption();
  3338. });
  3339. };
  3340. var getByIndex = function (component, hConfig, hState, index) {
  3341. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3342. return Option.from(items[index]).fold(function () {
  3343. return Result.error('No element found with index ' + index);
  3344. }, component.getSystem().getByDom);
  3345. };
  3346. var getFirst = function (component, hConfig, hState) {
  3347. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  3348. return component.getSystem().getByDom(e).toOption();
  3349. });
  3350. };
  3351. var getLast = function (component, hConfig, hState) {
  3352. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3353. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  3354. return last.bind(function (c) {
  3355. return component.getSystem().getByDom(c).toOption();
  3356. });
  3357. };
  3358. var getDelta = function (component, hConfig, hState, delta) {
  3359. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3360. var current = findIndex(items, function (item) {
  3361. return has$2(item, hConfig.highlightClass);
  3362. });
  3363. return current.bind(function (selected) {
  3364. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3365. return component.getSystem().getByDom(items[dest]).toOption();
  3366. });
  3367. };
  3368. var getPrevious = function (component, hConfig, hState) {
  3369. return getDelta(component, hConfig, hState, -1);
  3370. };
  3371. var getNext = function (component, hConfig, hState) {
  3372. return getDelta(component, hConfig, hState, +1);
  3373. };
  3374. var getCandidates = function (component, hConfig, hState) {
  3375. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3376. return cat(map$1(items, function (i) {
  3377. return component.getSystem().getByDom(i).toOption();
  3378. }));
  3379. };
  3380. var HighlightApis = /*#__PURE__*/Object.freeze({
  3381. __proto__: null,
  3382. dehighlightAll: dehighlightAll,
  3383. dehighlight: dehighlight$1,
  3384. highlight: highlight$1,
  3385. highlightFirst: highlightFirst,
  3386. highlightLast: highlightLast,
  3387. highlightAt: highlightAt,
  3388. highlightBy: highlightBy,
  3389. isHighlighted: isHighlighted,
  3390. getHighlighted: getHighlighted,
  3391. getFirst: getFirst,
  3392. getLast: getLast,
  3393. getPrevious: getPrevious,
  3394. getNext: getNext,
  3395. getCandidates: getCandidates
  3396. });
  3397. var HighlightSchema = [
  3398. strict$1('highlightClass'),
  3399. strict$1('itemClass'),
  3400. onHandler('onHighlight'),
  3401. onHandler('onDehighlight')
  3402. ];
  3403. var Highlighting = create$1({
  3404. fields: HighlightSchema,
  3405. name: 'highlighting',
  3406. apis: HighlightApis
  3407. });
  3408. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3409. var noChange = prevFocus.exists(function (p) {
  3410. return newFocus.exists(function (n) {
  3411. return eq(n, p);
  3412. });
  3413. });
  3414. if (!noChange) {
  3415. emitWith(component, focusShifted(), {
  3416. prevFocus: prevFocus,
  3417. newFocus: newFocus
  3418. });
  3419. }
  3420. };
  3421. var dom = function () {
  3422. var get = function (component) {
  3423. return search(component.element());
  3424. };
  3425. var set = function (component, focusee) {
  3426. var prevFocus = get(component);
  3427. component.getSystem().triggerFocus(focusee, component.element());
  3428. var newFocus = get(component);
  3429. reportFocusShifting(component, prevFocus, newFocus);
  3430. };
  3431. return {
  3432. get: get,
  3433. set: set
  3434. };
  3435. };
  3436. var highlights = function () {
  3437. var get = function (component) {
  3438. return Highlighting.getHighlighted(component).map(function (item) {
  3439. return item.element();
  3440. });
  3441. };
  3442. var set = function (component, element) {
  3443. var prevFocus = get(component);
  3444. component.getSystem().getByDom(element).fold(noop, function (item) {
  3445. Highlighting.highlight(component, item);
  3446. });
  3447. var newFocus = get(component);
  3448. reportFocusShifting(component, prevFocus, newFocus);
  3449. };
  3450. return {
  3451. get: get,
  3452. set: set
  3453. };
  3454. };
  3455. var FocusInsideModes;
  3456. (function (FocusInsideModes) {
  3457. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3458. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3459. FocusInsideModes['OnApiMode'] = 'onApi';
  3460. }(FocusInsideModes || (FocusInsideModes = {})));
  3461. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3462. var schema = function () {
  3463. return infoSchema.concat([
  3464. defaulted$1('focusManager', dom()),
  3465. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3466. return contains([
  3467. 'onFocus',
  3468. 'onEnterOrSpace',
  3469. 'onApi'
  3470. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3471. })),
  3472. output('handler', me),
  3473. output('state', stateInit),
  3474. output('sendFocusIn', optFocusIn)
  3475. ]);
  3476. };
  3477. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3478. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3479. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  3480. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3481. });
  3482. };
  3483. var toEvents = function (keyingConfig, keyingState) {
  3484. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3485. return run(focus(), function (component, simulatedEvent) {
  3486. focusIn(component, keyingConfig, keyingState);
  3487. simulatedEvent.stop();
  3488. });
  3489. });
  3490. var tryGoInsideComponent = function (component, simulatedEvent) {
  3491. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  3492. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3493. optFocusIn(keyingConfig).each(function (focusIn) {
  3494. focusIn(component, keyingConfig, keyingState);
  3495. simulatedEvent.stop();
  3496. });
  3497. }
  3498. };
  3499. return derive(onFocusHandler.toArray().concat([
  3500. run(keydown(), function (component, simulatedEvent) {
  3501. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3502. tryGoInsideComponent(component, simulatedEvent);
  3503. }, function (_) {
  3504. simulatedEvent.stop();
  3505. });
  3506. }),
  3507. run(keyup(), function (component, simulatedEvent) {
  3508. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3509. simulatedEvent.stop();
  3510. });
  3511. })
  3512. ]));
  3513. };
  3514. var me = {
  3515. schema: schema,
  3516. processKey: processKey,
  3517. toEvents: toEvents
  3518. };
  3519. return me;
  3520. };
  3521. var create$2 = function (cyclicField) {
  3522. var schema = [
  3523. option('onEscape'),
  3524. option('onEnter'),
  3525. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3526. defaulted$1('firstTabstop', 0),
  3527. defaulted$1('useTabstopAt', constant(true)),
  3528. option('visibilitySelector')
  3529. ].concat([cyclicField]);
  3530. var isVisible = function (tabbingConfig, element) {
  3531. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3532. return closest$2(element, sel);
  3533. }).getOr(element);
  3534. return get$5(target) > 0;
  3535. };
  3536. var findInitial = function (component, tabbingConfig) {
  3537. var tabstops = descendants(component.element(), tabbingConfig.selector);
  3538. var visibles = filter(tabstops, function (elem) {
  3539. return isVisible(tabbingConfig, elem);
  3540. });
  3541. return Option.from(visibles[tabbingConfig.firstTabstop]);
  3542. };
  3543. var findCurrent = function (component, tabbingConfig) {
  3544. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3545. return closest$2(elem, tabbingConfig.selector);
  3546. });
  3547. };
  3548. var isTabstop = function (tabbingConfig, element) {
  3549. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3550. };
  3551. var focusIn = function (component, tabbingConfig, tabbingState) {
  3552. findInitial(component, tabbingConfig).each(function (target) {
  3553. tabbingConfig.focusManager.set(component, target);
  3554. });
  3555. };
  3556. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3557. return cycle(tabstops, stopIndex, function (elem) {
  3558. return isTabstop(tabbingConfig, elem);
  3559. }).fold(function () {
  3560. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  3561. }, function (target) {
  3562. tabbingConfig.focusManager.set(component, target);
  3563. return Option.some(true);
  3564. });
  3565. };
  3566. var go = function (component, simulatedEvent, tabbingConfig, cycle) {
  3567. var tabstops = descendants(component.element(), tabbingConfig.selector);
  3568. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3569. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  3570. return optStopIndex.bind(function (stopIndex) {
  3571. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3572. });
  3573. });
  3574. };
  3575. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  3576. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3577. return go(component, simulatedEvent, tabbingConfig, navigate);
  3578. };
  3579. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  3580. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3581. return go(component, simulatedEvent, tabbingConfig, navigate);
  3582. };
  3583. var execute = function (component, simulatedEvent, tabbingConfig) {
  3584. return tabbingConfig.onEnter.bind(function (f) {
  3585. return f(component, simulatedEvent);
  3586. });
  3587. };
  3588. var exit = function (component, simulatedEvent, tabbingConfig) {
  3589. return tabbingConfig.onEscape.bind(function (f) {
  3590. return f(component, simulatedEvent);
  3591. });
  3592. };
  3593. var getKeydownRules = constant([
  3594. rule(and([
  3595. isShift,
  3596. inSet(TAB())
  3597. ]), goBackwards),
  3598. rule(inSet(TAB()), goForwards),
  3599. rule(inSet(ESCAPE()), exit),
  3600. rule(and([
  3601. isNotShift,
  3602. inSet(ENTER())
  3603. ]), execute)
  3604. ]);
  3605. var getKeyupRules = constant([]);
  3606. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3607. return Option.some(focusIn);
  3608. });
  3609. };
  3610. var AcyclicType = create$2(state$1('cyclic', constant(false)));
  3611. var CyclicType = create$2(state$1('cyclic', constant(true)));
  3612. var inside = function (target) {
  3613. return name(target) === 'input' && get$1(target, 'type') !== 'radio' || name(target) === 'textarea';
  3614. };
  3615. var doDefaultExecute = function (component, simulatedEvent, focused) {
  3616. dispatch(component, focused, execute());
  3617. return Option.some(true);
  3618. };
  3619. var defaultExecute = function (component, simulatedEvent, focused) {
  3620. return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  3621. };
  3622. var stopEventForFirefox = function (component, simulatedEvent) {
  3623. return Option.some(true);
  3624. };
  3625. var schema$1 = [
  3626. defaulted$1('execute', defaultExecute),
  3627. defaulted$1('useSpace', false),
  3628. defaulted$1('useEnter', true),
  3629. defaulted$1('useControlEnter', false),
  3630. defaulted$1('useDown', false)
  3631. ];
  3632. var execute$1 = function (component, simulatedEvent, executeConfig) {
  3633. return executeConfig.execute(component, simulatedEvent, component.element());
  3634. };
  3635. var getKeydownRules = function (component, simulatedEvent, executeConfig, executeState) {
  3636. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  3637. var enterExec = executeConfig.useEnter ? ENTER() : [];
  3638. var downExec = executeConfig.useDown ? DOWN() : [];
  3639. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3640. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  3641. isControl,
  3642. inSet(ENTER())
  3643. ]), execute$1)] : []);
  3644. };
  3645. var getKeyupRules = function (component, simulatedEvent, executeConfig, executeState) {
  3646. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  3647. };
  3648. var ExecutionType = typical(schema$1, NoState.init, getKeydownRules, getKeyupRules, function () {
  3649. return Option.none();
  3650. });
  3651. var flatgrid = function () {
  3652. var dimensions = Cell(Option.none());
  3653. var setGridSize = function (numRows, numColumns) {
  3654. dimensions.set(Option.some({
  3655. numRows: constant(numRows),
  3656. numColumns: constant(numColumns)
  3657. }));
  3658. };
  3659. var getNumRows = function () {
  3660. return dimensions.get().map(function (d) {
  3661. return d.numRows();
  3662. });
  3663. };
  3664. var getNumColumns = function () {
  3665. return dimensions.get().map(function (d) {
  3666. return d.numColumns();
  3667. });
  3668. };
  3669. return nu$6({
  3670. readState: function () {
  3671. return dimensions.get().map(function (d) {
  3672. return {
  3673. numRows: String(d.numRows()),
  3674. numColumns: String(d.numColumns())
  3675. };
  3676. }).getOr({
  3677. numRows: '?',
  3678. numColumns: '?'
  3679. });
  3680. },
  3681. setGridSize: setGridSize,
  3682. getNumRows: getNumRows,
  3683. getNumColumns: getNumColumns
  3684. });
  3685. };
  3686. var init = function (spec) {
  3687. return spec.state(spec);
  3688. };
  3689. var KeyingState = /*#__PURE__*/Object.freeze({
  3690. __proto__: null,
  3691. flatgrid: flatgrid,
  3692. init: init
  3693. });
  3694. var onDirection = function (isLtr, isRtl) {
  3695. return function (element) {
  3696. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3697. };
  3698. };
  3699. var getDirection = function (element) {
  3700. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3701. };
  3702. var useH = function (movement) {
  3703. return function (component, simulatedEvent, config, state) {
  3704. var move = movement(component.element());
  3705. return use(move, component, simulatedEvent, config, state);
  3706. };
  3707. };
  3708. var west = function (moveLeft, moveRight) {
  3709. var movement = onDirection(moveLeft, moveRight);
  3710. return useH(movement);
  3711. };
  3712. var east = function (moveLeft, moveRight) {
  3713. var movement = onDirection(moveRight, moveLeft);
  3714. return useH(movement);
  3715. };
  3716. var useV = function (move) {
  3717. return function (component, simulatedEvent, config, state) {
  3718. return use(move, component, simulatedEvent, config, state);
  3719. };
  3720. };
  3721. var use = function (move, component, simulatedEvent, config, state) {
  3722. var outcome = config.focusManager.get(component).bind(function (focused) {
  3723. return move(component.element(), focused, config, state);
  3724. });
  3725. return outcome.map(function (newFocus) {
  3726. config.focusManager.set(component, newFocus);
  3727. return true;
  3728. });
  3729. };
  3730. var north = useV;
  3731. var south = useV;
  3732. var move = useV;
  3733. var isHidden = function (dom) {
  3734. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3735. };
  3736. var isVisible = function (element) {
  3737. var dom = element.dom();
  3738. return !isHidden(dom);
  3739. };
  3740. var locate = function (candidates, predicate) {
  3741. return findIndex(candidates, predicate).map(function (index) {
  3742. return {
  3743. index: constant(index),
  3744. candidates: constant(candidates)
  3745. };
  3746. });
  3747. };
  3748. var locateVisible = function (container, current, selector) {
  3749. var predicate = function (x) {
  3750. return eq(x, current);
  3751. };
  3752. var candidates = descendants(container, selector);
  3753. var visible = filter(candidates, isVisible);
  3754. return locate(visible, predicate);
  3755. };
  3756. var findIndex$1 = function (elements, target) {
  3757. return findIndex(elements, function (elem) {
  3758. return eq(target, elem);
  3759. });
  3760. };
  3761. var withGrid = function (values, index, numCols, f) {
  3762. var oldRow = Math.floor(index / numCols);
  3763. var oldColumn = index % numCols;
  3764. return f(oldRow, oldColumn).bind(function (address) {
  3765. var newIndex = address.row() * numCols + address.column();
  3766. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  3767. });
  3768. };
  3769. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  3770. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3771. var onLastRow = oldRow === numRows - 1;
  3772. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3773. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3774. return Option.some({
  3775. row: constant(oldRow),
  3776. column: constant(newColumn)
  3777. });
  3778. });
  3779. };
  3780. var cycleVertical = function (values, index, numRows, numCols, delta) {
  3781. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3782. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3783. var onLastRow = newRow === numRows - 1;
  3784. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3785. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  3786. return Option.some({
  3787. row: constant(newRow),
  3788. column: constant(newCol)
  3789. });
  3790. });
  3791. };
  3792. var cycleRight = function (values, index, numRows, numCols) {
  3793. return cycleHorizontal(values, index, numRows, numCols, +1);
  3794. };
  3795. var cycleLeft = function (values, index, numRows, numCols) {
  3796. return cycleHorizontal(values, index, numRows, numCols, -1);
  3797. };
  3798. var cycleUp = function (values, index, numRows, numCols) {
  3799. return cycleVertical(values, index, numRows, numCols, -1);
  3800. };
  3801. var cycleDown = function (values, index, numRows, numCols) {
  3802. return cycleVertical(values, index, numRows, numCols, +1);
  3803. };
  3804. var schema$2 = [
  3805. strict$1('selector'),
  3806. defaulted$1('execute', defaultExecute),
  3807. onKeyboardHandler('onEscape'),
  3808. defaulted$1('captureTab', false),
  3809. initSize()
  3810. ];
  3811. var focusIn = function (component, gridConfig, gridState) {
  3812. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  3813. gridConfig.focusManager.set(component, first);
  3814. });
  3815. };
  3816. var findCurrent = function (component, gridConfig) {
  3817. return gridConfig.focusManager.get(component).bind(function (elem) {
  3818. return closest$2(elem, gridConfig.selector);
  3819. });
  3820. };
  3821. var execute$2 = function (component, simulatedEvent, gridConfig, gridState) {
  3822. return findCurrent(component, gridConfig).bind(function (focused) {
  3823. return gridConfig.execute(component, simulatedEvent, focused);
  3824. });
  3825. };
  3826. var doMove = function (cycle) {
  3827. return function (element, focused, gridConfig, gridState) {
  3828. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3829. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3830. });
  3831. };
  3832. };
  3833. var handleTab = function (component, simulatedEvent, gridConfig) {
  3834. return gridConfig.captureTab ? Option.some(true) : Option.none();
  3835. };
  3836. var doEscape = function (component, simulatedEvent, gridConfig) {
  3837. return gridConfig.onEscape(component, simulatedEvent);
  3838. };
  3839. var moveLeft = doMove(cycleLeft);
  3840. var moveRight = doMove(cycleRight);
  3841. var moveNorth = doMove(cycleUp);
  3842. var moveSouth = doMove(cycleDown);
  3843. var getKeydownRules$1 = constant([
  3844. rule(inSet(LEFT()), west(moveLeft, moveRight)),
  3845. rule(inSet(RIGHT()), east(moveLeft, moveRight)),
  3846. rule(inSet(UP()), north(moveNorth)),
  3847. rule(inSet(DOWN()), south(moveSouth)),
  3848. rule(and([
  3849. isShift,
  3850. inSet(TAB())
  3851. ]), handleTab),
  3852. rule(and([
  3853. isNotShift,
  3854. inSet(TAB())
  3855. ]), handleTab),
  3856. rule(inSet(ESCAPE()), doEscape),
  3857. rule(inSet(SPACE().concat(ENTER())), execute$2)
  3858. ]);
  3859. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3860. var FlatgridType = typical(schema$2, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  3861. return Option.some(focusIn);
  3862. });
  3863. var horizontal = function (container, selector, current, delta) {
  3864. var isDisabledButton = function (candidate) {
  3865. return name(candidate) === 'button' && get$1(candidate, 'disabled') === 'disabled';
  3866. };
  3867. var tryCycle = function (initial, index, candidates) {
  3868. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  3869. if (newIndex === initial) {
  3870. return Option.none();
  3871. } else {
  3872. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  3873. }
  3874. };
  3875. return locateVisible(container, current, selector).bind(function (identified) {
  3876. var index = identified.index();
  3877. var candidates = identified.candidates();
  3878. return tryCycle(index, index, candidates);
  3879. });
  3880. };
  3881. var schema$3 = [
  3882. strict$1('selector'),
  3883. defaulted$1('getInitial', Option.none),
  3884. defaulted$1('execute', defaultExecute),
  3885. onKeyboardHandler('onEscape'),
  3886. defaulted$1('executeOnMove', false),
  3887. defaulted$1('allowVertical', true)
  3888. ];
  3889. var findCurrent$1 = function (component, flowConfig) {
  3890. return flowConfig.focusManager.get(component).bind(function (elem) {
  3891. return closest$2(elem, flowConfig.selector);
  3892. });
  3893. };
  3894. var execute$3 = function (component, simulatedEvent, flowConfig) {
  3895. return findCurrent$1(component, flowConfig).bind(function (focused) {
  3896. return flowConfig.execute(component, simulatedEvent, focused);
  3897. });
  3898. };
  3899. var focusIn$1 = function (component, flowConfig, state) {
  3900. flowConfig.getInitial(component).orThunk(function () {
  3901. return descendant$1(component.element(), flowConfig.selector);
  3902. }).each(function (first) {
  3903. flowConfig.focusManager.set(component, first);
  3904. });
  3905. };
  3906. var moveLeft$1 = function (element, focused, info) {
  3907. return horizontal(element, info.selector, focused, -1);
  3908. };
  3909. var moveRight$1 = function (element, focused, info) {
  3910. return horizontal(element, info.selector, focused, +1);
  3911. };
  3912. var doMove$1 = function (movement) {
  3913. return function (component, simulatedEvent, flowConfig, flowState) {
  3914. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  3915. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  3916. });
  3917. };
  3918. };
  3919. var doEscape$1 = function (component, simulatedEvent, flowConfig) {
  3920. return flowConfig.onEscape(component, simulatedEvent);
  3921. };
  3922. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  3923. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  3924. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  3925. return [
  3926. rule(inSet(westMovers), doMove$1(west(moveLeft$1, moveRight$1))),
  3927. rule(inSet(eastMovers), doMove$1(east(moveLeft$1, moveRight$1))),
  3928. rule(inSet(ENTER()), execute$3),
  3929. rule(inSet(SPACE()), execute$3),
  3930. rule(inSet(ESCAPE()), doEscape$1)
  3931. ];
  3932. };
  3933. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3934. var FlowType = typical(schema$3, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  3935. return Option.some(focusIn$1);
  3936. });
  3937. var outcome = MixedBag([
  3938. 'rowIndex',
  3939. 'columnIndex',
  3940. 'cell'
  3941. ], []);
  3942. var toCell = function (matrix, rowIndex, columnIndex) {
  3943. return Option.from(matrix[rowIndex]).bind(function (row) {
  3944. return Option.from(row[columnIndex]).map(function (cell) {
  3945. return outcome({
  3946. rowIndex: rowIndex,
  3947. columnIndex: columnIndex,
  3948. cell: cell
  3949. });
  3950. });
  3951. });
  3952. };
  3953. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  3954. var row = matrix[rowIndex];
  3955. var colsInRow = row.length;
  3956. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  3957. return toCell(matrix, rowIndex, newColIndex);
  3958. };
  3959. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  3960. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  3961. var colsInNextRow = matrix[nextRowIndex].length;
  3962. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  3963. return toCell(matrix, nextRowIndex, nextColIndex);
  3964. };
  3965. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  3966. var row = matrix[rowIndex];
  3967. var colsInRow = row.length;
  3968. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  3969. return toCell(matrix, rowIndex, newColIndex);
  3970. };
  3971. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  3972. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  3973. var colsInNextRow = matrix[nextRowIndex].length;
  3974. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  3975. return toCell(matrix, nextRowIndex, nextColIndex);
  3976. };
  3977. var cycleRight$1 = function (matrix, startRow, startCol) {
  3978. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  3979. };
  3980. var cycleLeft$1 = function (matrix, startRow, startCol) {
  3981. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  3982. };
  3983. var cycleUp$1 = function (matrix, startRow, startCol) {
  3984. return cycleVertical$1(matrix, startCol, startRow, -1);
  3985. };
  3986. var cycleDown$1 = function (matrix, startRow, startCol) {
  3987. return cycleVertical$1(matrix, startCol, startRow, +1);
  3988. };
  3989. var moveLeft$2 = function (matrix, startRow, startCol) {
  3990. return moveHorizontal(matrix, startRow, startCol, -1);
  3991. };
  3992. var moveRight$2 = function (matrix, startRow, startCol) {
  3993. return moveHorizontal(matrix, startRow, startCol, +1);
  3994. };
  3995. var moveUp = function (matrix, startRow, startCol) {
  3996. return moveVertical(matrix, startCol, startRow, -1);
  3997. };
  3998. var moveDown = function (matrix, startRow, startCol) {
  3999. return moveVertical(matrix, startCol, startRow, +1);
  4000. };
  4001. var schema$4 = [
  4002. strictObjOf('selectors', [
  4003. strict$1('row'),
  4004. strict$1('cell')
  4005. ]),
  4006. defaulted$1('cycles', true),
  4007. defaulted$1('previousSelector', Option.none),
  4008. defaulted$1('execute', defaultExecute)
  4009. ];
  4010. var focusIn$2 = function (component, matrixConfig, state) {
  4011. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4012. var selectors = matrixConfig.selectors;
  4013. return descendant$1(component.element(), selectors.cell);
  4014. });
  4015. focused.each(function (cell) {
  4016. matrixConfig.focusManager.set(component, cell);
  4017. });
  4018. };
  4019. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  4020. return search(component.element()).bind(function (focused) {
  4021. return matrixConfig.execute(component, simulatedEvent, focused);
  4022. });
  4023. };
  4024. var toMatrix = function (rows, matrixConfig) {
  4025. return map$1(rows, function (row) {
  4026. return descendants(row, matrixConfig.selectors.cell);
  4027. });
  4028. };
  4029. var doMove$2 = function (ifCycle, ifMove) {
  4030. return function (element, focused, matrixConfig) {
  4031. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4032. return closest$2(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4033. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4034. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  4035. var allRows = descendants(element, matrixConfig.selectors.row);
  4036. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  4037. var matrix = toMatrix(allRows, matrixConfig);
  4038. return move(matrix, rowIndex, colIndex).map(function (next) {
  4039. return next.cell();
  4040. });
  4041. });
  4042. });
  4043. });
  4044. };
  4045. };
  4046. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  4047. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  4048. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  4049. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  4050. var getKeydownRules$3 = constant([
  4051. rule(inSet(LEFT()), west(moveLeft$3, moveRight$3)),
  4052. rule(inSet(RIGHT()), east(moveLeft$3, moveRight$3)),
  4053. rule(inSet(UP()), north(moveNorth$1)),
  4054. rule(inSet(DOWN()), south(moveSouth$1)),
  4055. rule(inSet(SPACE().concat(ENTER())), execute$4)
  4056. ]);
  4057. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4058. var MatrixType = typical(schema$4, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4059. return Option.some(focusIn$2);
  4060. });
  4061. var schema$5 = [
  4062. strict$1('selector'),
  4063. defaulted$1('execute', defaultExecute),
  4064. defaulted$1('moveOnTab', false)
  4065. ];
  4066. var execute$5 = function (component, simulatedEvent, menuConfig) {
  4067. return menuConfig.focusManager.get(component).bind(function (focused) {
  4068. return menuConfig.execute(component, simulatedEvent, focused);
  4069. });
  4070. };
  4071. var focusIn$3 = function (component, menuConfig, state) {
  4072. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  4073. menuConfig.focusManager.set(component, first);
  4074. });
  4075. };
  4076. var moveUp$1 = function (element, focused, info) {
  4077. return horizontal(element, info.selector, focused, -1);
  4078. };
  4079. var moveDown$1 = function (element, focused, info) {
  4080. return horizontal(element, info.selector, focused, +1);
  4081. };
  4082. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  4083. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  4084. };
  4085. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  4086. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  4087. };
  4088. var getKeydownRules$4 = constant([
  4089. rule(inSet(UP()), move(moveUp$1)),
  4090. rule(inSet(DOWN()), move(moveDown$1)),
  4091. rule(and([
  4092. isShift,
  4093. inSet(TAB())
  4094. ]), fireShiftTab),
  4095. rule(and([
  4096. isNotShift,
  4097. inSet(TAB())
  4098. ]), fireTab),
  4099. rule(inSet(ENTER()), execute$5),
  4100. rule(inSet(SPACE()), execute$5)
  4101. ]);
  4102. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4103. var MenuType = typical(schema$5, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  4104. return Option.some(focusIn$3);
  4105. });
  4106. var schema$6 = [
  4107. onKeyboardHandler('onSpace'),
  4108. onKeyboardHandler('onEnter'),
  4109. onKeyboardHandler('onShiftEnter'),
  4110. onKeyboardHandler('onLeft'),
  4111. onKeyboardHandler('onRight'),
  4112. onKeyboardHandler('onTab'),
  4113. onKeyboardHandler('onShiftTab'),
  4114. onKeyboardHandler('onUp'),
  4115. onKeyboardHandler('onDown'),
  4116. onKeyboardHandler('onEscape'),
  4117. defaulted$1('stopSpaceKeyup', false),
  4118. option('focusIn')
  4119. ];
  4120. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  4121. return [
  4122. rule(inSet(SPACE()), specialInfo.onSpace),
  4123. rule(and([
  4124. isNotShift,
  4125. inSet(ENTER())
  4126. ]), specialInfo.onEnter),
  4127. rule(and([
  4128. isShift,
  4129. inSet(ENTER())
  4130. ]), specialInfo.onShiftEnter),
  4131. rule(and([
  4132. isShift,
  4133. inSet(TAB())
  4134. ]), specialInfo.onShiftTab),
  4135. rule(and([
  4136. isNotShift,
  4137. inSet(TAB())
  4138. ]), specialInfo.onTab),
  4139. rule(inSet(UP()), specialInfo.onUp),
  4140. rule(inSet(DOWN()), specialInfo.onDown),
  4141. rule(inSet(LEFT()), specialInfo.onLeft),
  4142. rule(inSet(RIGHT()), specialInfo.onRight),
  4143. rule(inSet(SPACE()), specialInfo.onSpace),
  4144. rule(inSet(ESCAPE()), specialInfo.onEscape)
  4145. ];
  4146. };
  4147. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  4148. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  4149. };
  4150. var SpecialType = typical(schema$6, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  4151. return specialInfo.focusIn;
  4152. });
  4153. var acyclic = AcyclicType.schema();
  4154. var cyclic = CyclicType.schema();
  4155. var flow = FlowType.schema();
  4156. var flatgrid$1 = FlatgridType.schema();
  4157. var matrix = MatrixType.schema();
  4158. var execution = ExecutionType.schema();
  4159. var menu = MenuType.schema();
  4160. var special = SpecialType.schema();
  4161. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4162. __proto__: null,
  4163. acyclic: acyclic,
  4164. cyclic: cyclic,
  4165. flow: flow,
  4166. flatgrid: flatgrid$1,
  4167. matrix: matrix,
  4168. execution: execution,
  4169. menu: menu,
  4170. special: special
  4171. });
  4172. var isFlatgridState = function (keyState) {
  4173. return hasNonNullableKey(keyState, 'setGridSize');
  4174. };
  4175. var Keying = createModes$1({
  4176. branchKey: 'mode',
  4177. branches: KeyboardBranches,
  4178. name: 'keying',
  4179. active: {
  4180. events: function (keyingConfig, keyingState) {
  4181. var handler = keyingConfig.handler;
  4182. return handler.toEvents(keyingConfig, keyingState);
  4183. }
  4184. },
  4185. apis: {
  4186. focusIn: function (component, keyConfig, keyState) {
  4187. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4188. component.getSystem().triggerFocus(component.element(), component.element());
  4189. }, function (sendFocusIn) {
  4190. sendFocusIn(component, keyConfig, keyState);
  4191. });
  4192. },
  4193. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4194. if (!isFlatgridState(keyState)) {
  4195. domGlobals.console.error('Layout does not support setGridSize');
  4196. } else {
  4197. keyState.setGridSize(numRows, numColumns);
  4198. }
  4199. }
  4200. },
  4201. state: KeyingState
  4202. });
  4203. var field$1 = function (name, forbidden) {
  4204. return defaultedObjOf(name, {}, map$1(forbidden, function (f) {
  4205. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4206. }).concat([state$1('dump', identity)]));
  4207. };
  4208. var get$6 = function (data) {
  4209. return data.dump;
  4210. };
  4211. var augment = function (data, original) {
  4212. return __assign(__assign({}, data.dump), derive$1(original));
  4213. };
  4214. var SketchBehaviours = {
  4215. field: field$1,
  4216. augment: augment,
  4217. get: get$6
  4218. };
  4219. var _placeholder = 'placeholder';
  4220. var adt$2 = Adt.generate([
  4221. {
  4222. single: [
  4223. 'required',
  4224. 'valueThunk'
  4225. ]
  4226. },
  4227. {
  4228. multiple: [
  4229. 'required',
  4230. 'valueThunks'
  4231. ]
  4232. }
  4233. ]);
  4234. var isSubstituted = function (spec) {
  4235. return has(spec, 'uiType');
  4236. };
  4237. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4238. if (owner.exists(function (o) {
  4239. return o !== compSpec.owner;
  4240. })) {
  4241. return adt$2.single(true, constant(compSpec));
  4242. }
  4243. return get(placeholders, compSpec.name).fold(function () {
  4244. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4245. }, function (newSpec) {
  4246. return newSpec.replace();
  4247. });
  4248. };
  4249. var scan = function (owner, detail, compSpec, placeholders) {
  4250. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  4251. return subPlaceholder(owner, detail, compSpec, placeholders);
  4252. } else {
  4253. return adt$2.single(false, constant(compSpec));
  4254. }
  4255. };
  4256. var substitute = function (owner, detail, compSpec, placeholders) {
  4257. var base = scan(owner, detail, compSpec, placeholders);
  4258. return base.fold(function (req, valueThunk) {
  4259. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  4260. var childSpecs = get(value, 'components').getOr([]);
  4261. var substituted = bind(childSpecs, function (c) {
  4262. return substitute(owner, detail, c, placeholders);
  4263. });
  4264. return [__assign(__assign({}, value), { components: substituted })];
  4265. }, function (req, valuesThunk) {
  4266. if (isSubstituted(compSpec)) {
  4267. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4268. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4269. return preprocessor(values);
  4270. } else {
  4271. return valuesThunk(detail);
  4272. }
  4273. });
  4274. };
  4275. var substituteAll = function (owner, detail, components, placeholders) {
  4276. return bind(components, function (c) {
  4277. return substitute(owner, detail, c, placeholders);
  4278. });
  4279. };
  4280. var oneReplace = function (label, replacements) {
  4281. var called = false;
  4282. var used = function () {
  4283. return called;
  4284. };
  4285. var replace = function () {
  4286. if (called) {
  4287. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4288. }
  4289. called = true;
  4290. return replacements;
  4291. };
  4292. var required = function () {
  4293. return replacements.fold(function (req, _) {
  4294. return req;
  4295. }, function (req, _) {
  4296. return req;
  4297. });
  4298. };
  4299. return {
  4300. name: constant(label),
  4301. required: required,
  4302. used: used,
  4303. replace: replace
  4304. };
  4305. };
  4306. var substitutePlaces = function (owner, detail, components, placeholders) {
  4307. var ps = map(placeholders, function (ph, name) {
  4308. return oneReplace(name, ph);
  4309. });
  4310. var outcome = substituteAll(owner, detail, components, ps);
  4311. each(ps, function (p) {
  4312. if (p.used() === false && p.required()) {
  4313. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4314. }
  4315. });
  4316. return outcome;
  4317. };
  4318. var single = adt$2.single;
  4319. var multiple = adt$2.multiple;
  4320. var placeholder = constant(_placeholder);
  4321. var unique = 0;
  4322. var generate$1 = function (prefix) {
  4323. var date = new Date();
  4324. var time = date.getTime();
  4325. var random = Math.floor(Math.random() * 1000000000);
  4326. unique++;
  4327. return prefix + '_' + random + unique + String(time);
  4328. };
  4329. var adt$3 = Adt.generate([
  4330. { required: ['data'] },
  4331. { external: ['data'] },
  4332. { optional: ['data'] },
  4333. { group: ['data'] }
  4334. ]);
  4335. var fFactory = defaulted$1('factory', { sketch: identity });
  4336. var fSchema = defaulted$1('schema', []);
  4337. var fName = strict$1('name');
  4338. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  4339. return '<alloy.' + generate$1(typeSpec.name) + '>';
  4340. }), anyValue$1());
  4341. var fGroupSchema = state$1('schema', function () {
  4342. return [option('preprocess')];
  4343. });
  4344. var fDefaults = defaulted$1('defaults', constant({}));
  4345. var fOverrides = defaulted$1('overrides', constant({}));
  4346. var requiredSpec = objOf([
  4347. fFactory,
  4348. fSchema,
  4349. fName,
  4350. fPname,
  4351. fDefaults,
  4352. fOverrides
  4353. ]);
  4354. var externalSpec = objOf([
  4355. fFactory,
  4356. fSchema,
  4357. fName,
  4358. fDefaults,
  4359. fOverrides
  4360. ]);
  4361. var optionalSpec = objOf([
  4362. fFactory,
  4363. fSchema,
  4364. fName,
  4365. fPname,
  4366. fDefaults,
  4367. fOverrides
  4368. ]);
  4369. var groupSpec = objOf([
  4370. fFactory,
  4371. fGroupSchema,
  4372. fName,
  4373. strict$1('unit'),
  4374. fPname,
  4375. fDefaults,
  4376. fOverrides
  4377. ]);
  4378. var asNamedPart = function (part) {
  4379. return part.fold(Option.some, Option.none, Option.some, Option.some);
  4380. };
  4381. var name$1 = function (part) {
  4382. var get = function (data) {
  4383. return data.name;
  4384. };
  4385. return part.fold(get, get, get, get);
  4386. };
  4387. var convert = function (adtConstructor, partSchema) {
  4388. return function (spec) {
  4389. var data = asRawOrDie('Converting part type', partSchema, spec);
  4390. return adtConstructor(data);
  4391. };
  4392. };
  4393. var required = convert(adt$3.required, requiredSpec);
  4394. var external = convert(adt$3.external, externalSpec);
  4395. var optional = convert(adt$3.optional, optionalSpec);
  4396. var group = convert(adt$3.group, groupSpec);
  4397. var original = constant('entirety');
  4398. var combine = function (detail, data, partSpec, partValidated) {
  4399. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4400. };
  4401. var subs = function (owner, detail, parts) {
  4402. var internals = {};
  4403. var externals = {};
  4404. each$1(parts, function (part) {
  4405. part.fold(function (data) {
  4406. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  4407. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4408. });
  4409. }, function (data) {
  4410. var partSpec = detail.parts[data.name];
  4411. externals[data.name] = constant(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  4412. }, function (data) {
  4413. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  4414. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4415. });
  4416. }, function (data) {
  4417. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4418. var units = detail[data.name];
  4419. return map$1(units, function (u) {
  4420. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4421. });
  4422. });
  4423. });
  4424. });
  4425. return {
  4426. internals: constant(internals),
  4427. externals: constant(externals)
  4428. };
  4429. };
  4430. var generate$2 = function (owner, parts) {
  4431. var r = {};
  4432. each$1(parts, function (part) {
  4433. asNamedPart(part).each(function (np) {
  4434. var g = doGenerateOne(owner, np.pname);
  4435. r[np.name] = function (config) {
  4436. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4437. return __assign(__assign({}, g), {
  4438. config: config,
  4439. validated: validated
  4440. });
  4441. };
  4442. });
  4443. });
  4444. return r;
  4445. };
  4446. var doGenerateOne = function (owner, pname) {
  4447. return {
  4448. uiType: placeholder(),
  4449. owner: owner,
  4450. name: pname
  4451. };
  4452. };
  4453. var generateOne = function (owner, pname, config) {
  4454. return {
  4455. uiType: placeholder(),
  4456. owner: owner,
  4457. name: pname,
  4458. config: config,
  4459. validated: {}
  4460. };
  4461. };
  4462. var schemas = function (parts) {
  4463. return bind(parts, function (part) {
  4464. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  4465. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  4466. }).toArray();
  4467. });
  4468. };
  4469. var names = function (parts) {
  4470. return map$1(parts, name$1);
  4471. };
  4472. var substitutes = function (owner, detail, parts) {
  4473. return subs(owner, detail, parts);
  4474. };
  4475. var components = function (owner, detail, internals) {
  4476. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  4477. };
  4478. var getPart = function (component, detail, partKey) {
  4479. var uid = detail.partUids[partKey];
  4480. return component.getSystem().getByUid(uid).toOption();
  4481. };
  4482. var getPartOrDie = function (component, detail, partKey) {
  4483. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4484. };
  4485. var getAllParts = function (component, detail) {
  4486. var system = component.getSystem();
  4487. return map(detail.partUids, function (pUid, k) {
  4488. return constant(system.getByUid(pUid));
  4489. });
  4490. };
  4491. var defaultUids = function (baseUid, partTypes) {
  4492. var partNames = names(partTypes);
  4493. return wrapAll$1(map$1(partNames, function (pn) {
  4494. return {
  4495. key: pn,
  4496. value: baseUid + '-' + pn
  4497. };
  4498. }));
  4499. };
  4500. var defaultUidsSchema = function (partTypes) {
  4501. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  4502. return defaultUids(spec.uid, partTypes);
  4503. }), anyValue$1());
  4504. };
  4505. var premadeTag = generate$1('alloy-premade');
  4506. var premade = function (comp) {
  4507. return wrap$1(premadeTag, comp);
  4508. };
  4509. var getPremade = function (spec) {
  4510. return get(spec, premadeTag);
  4511. };
  4512. var makeApi = function (f) {
  4513. return markAsSketchApi(function (component) {
  4514. var rest = [];
  4515. for (var _i = 1; _i < arguments.length; _i++) {
  4516. rest[_i - 1] = arguments[_i];
  4517. }
  4518. return f.apply(undefined, [component.getApis()].concat([component].concat(rest)));
  4519. }, f);
  4520. };
  4521. var prefix$1 = constant('alloy-id-');
  4522. var idAttr = constant('data-alloy-id');
  4523. var prefix$2 = prefix$1();
  4524. var idAttr$1 = idAttr();
  4525. var write = function (label, elem) {
  4526. var id = generate$1(prefix$2 + label);
  4527. writeOnly(elem, id);
  4528. return id;
  4529. };
  4530. var writeOnly = function (elem, uid) {
  4531. Object.defineProperty(elem.dom(), idAttr$1, {
  4532. value: uid,
  4533. writable: true
  4534. });
  4535. };
  4536. var read$2 = function (elem) {
  4537. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  4538. return Option.from(id);
  4539. };
  4540. var generate$3 = function (prefix) {
  4541. return generate$1(prefix);
  4542. };
  4543. var base = function (partSchemas, partUidsSchemas) {
  4544. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  4545. return ps.concat([
  4546. strict$1('uid'),
  4547. defaulted$1('dom', {}),
  4548. defaulted$1('components', []),
  4549. snapshot('originalSpec'),
  4550. defaulted$1('debug.sketcher', {})
  4551. ]).concat(partUidsSchemas);
  4552. };
  4553. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4554. var baseS = base(partSchemas, partUidsSchemas);
  4555. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4556. };
  4557. var single$1 = function (owner, schema, factory, spec) {
  4558. var specWithUid = supplyUid(spec);
  4559. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  4560. return factory(detail, specWithUid);
  4561. };
  4562. var composite = function (owner, schema, partTypes, factory, spec) {
  4563. var specWithUid = supplyUid(spec);
  4564. var partSchemas = schemas(partTypes);
  4565. var partUidsSchema = defaultUidsSchema(partTypes);
  4566. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4567. var subs = substitutes(owner, detail, partTypes);
  4568. var components$1 = components(owner, detail, subs.internals());
  4569. return factory(detail, components$1, specWithUid, subs.externals());
  4570. };
  4571. var hasUid = function (spec) {
  4572. return has(spec, 'uid');
  4573. };
  4574. var supplyUid = function (spec) {
  4575. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$3('uid') });
  4576. };
  4577. function isSketchSpec(spec) {
  4578. return spec.uid !== undefined;
  4579. }
  4580. var singleSchema = objOfOnly([
  4581. strict$1('name'),
  4582. strict$1('factory'),
  4583. strict$1('configFields'),
  4584. defaulted$1('apis', {}),
  4585. defaulted$1('extraApis', {})
  4586. ]);
  4587. var compositeSchema = objOfOnly([
  4588. strict$1('name'),
  4589. strict$1('factory'),
  4590. strict$1('configFields'),
  4591. strict$1('partFields'),
  4592. defaulted$1('apis', {}),
  4593. defaulted$1('extraApis', {})
  4594. ]);
  4595. var single$2 = function (rawConfig) {
  4596. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4597. var sketch = function (spec) {
  4598. return single$1(config.name, config.configFields, config.factory, spec);
  4599. };
  4600. var apis = map(config.apis, makeApi);
  4601. var extraApis = map(config.extraApis, function (f, k) {
  4602. return markAsExtraApi(f, k);
  4603. });
  4604. return __assign(__assign({
  4605. name: constant(config.name),
  4606. configFields: constant(config.configFields),
  4607. sketch: sketch
  4608. }, apis), extraApis);
  4609. };
  4610. var composite$1 = function (rawConfig) {
  4611. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4612. var sketch = function (spec) {
  4613. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  4614. };
  4615. var parts = generate$2(config.name, config.partFields);
  4616. var apis = map(config.apis, makeApi);
  4617. var extraApis = map(config.extraApis, function (f, k) {
  4618. return markAsExtraApi(f, k);
  4619. });
  4620. return __assign(__assign({
  4621. name: constant(config.name),
  4622. partFields: constant(config.partFields),
  4623. configFields: constant(config.configFields),
  4624. sketch: sketch,
  4625. parts: constant(parts)
  4626. }, apis), extraApis);
  4627. };
  4628. var factory = function (detail) {
  4629. var events = events$2(detail.action);
  4630. var tag = detail.dom.tag;
  4631. var lookupAttr = function (attr) {
  4632. return get(detail.dom, 'attributes').bind(function (attrs) {
  4633. return get(attrs, attr);
  4634. });
  4635. };
  4636. var getModAttributes = function () {
  4637. if (tag === 'button') {
  4638. var type = lookupAttr('type').getOr('button');
  4639. var roleAttrs = lookupAttr('role').map(function (role) {
  4640. return { role: role };
  4641. }).getOr({});
  4642. return __assign({ type: type }, roleAttrs);
  4643. } else {
  4644. var role = lookupAttr('role').getOr('button');
  4645. return { role: role };
  4646. }
  4647. };
  4648. return {
  4649. uid: detail.uid,
  4650. dom: detail.dom,
  4651. components: detail.components,
  4652. events: events,
  4653. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4654. Focusing.config({}),
  4655. Keying.config({
  4656. mode: 'execution',
  4657. useSpace: true,
  4658. useEnter: true
  4659. })
  4660. ]),
  4661. domModification: { attributes: getModAttributes() },
  4662. eventOrder: detail.eventOrder
  4663. };
  4664. };
  4665. var Button = single$2({
  4666. name: 'Button',
  4667. factory: factory,
  4668. configFields: [
  4669. defaulted$1('uid', undefined),
  4670. strict$1('dom'),
  4671. defaulted$1('components', []),
  4672. SketchBehaviours.field('buttonBehaviours', [
  4673. Focusing,
  4674. Keying
  4675. ]),
  4676. option('action'),
  4677. option('role'),
  4678. defaulted$1('eventOrder', {})
  4679. ]
  4680. });
  4681. var exhibit$2 = function () {
  4682. return nu$5({
  4683. styles: {
  4684. '-webkit-user-select': 'none',
  4685. 'user-select': 'none',
  4686. '-ms-user-select': 'none',
  4687. '-moz-user-select': '-moz-none'
  4688. },
  4689. attributes: { unselectable: 'on' }
  4690. });
  4691. };
  4692. var events$4 = function () {
  4693. return derive([abort(selectstart(), constant(true))]);
  4694. };
  4695. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4696. __proto__: null,
  4697. events: events$4,
  4698. exhibit: exhibit$2
  4699. });
  4700. var Unselecting = create$1({
  4701. fields: [],
  4702. name: 'unselecting',
  4703. active: ActiveUnselecting
  4704. });
  4705. var getAttrs = function (elem) {
  4706. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  4707. return foldl(attributes, function (b, attr) {
  4708. var _a;
  4709. if (attr.name === 'class') {
  4710. return b;
  4711. } else {
  4712. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4713. }
  4714. }, {});
  4715. };
  4716. var getClasses = function (elem) {
  4717. return Array.prototype.slice.call(elem.dom().classList, 0);
  4718. };
  4719. var fromHtml$2 = function (html) {
  4720. var elem = Element.fromHtml(html);
  4721. var children$1 = children(elem);
  4722. var attrs = getAttrs(elem);
  4723. var classes = getClasses(elem);
  4724. var contents = children$1.length === 0 ? {} : { innerHtml: get$3(elem) };
  4725. return __assign({
  4726. tag: name(elem),
  4727. classes: classes,
  4728. attributes: attrs
  4729. }, contents);
  4730. };
  4731. var dom$1 = function (rawHtml) {
  4732. var html = supplant(rawHtml, { prefix: Styles.prefix() });
  4733. return fromHtml$2(html);
  4734. };
  4735. var spec = function (rawHtml) {
  4736. var sDom = dom$1(rawHtml);
  4737. return { dom: sDom };
  4738. };
  4739. var forToolbarCommand = function (editor, command) {
  4740. return forToolbar(command, function () {
  4741. editor.execCommand(command);
  4742. }, {}, editor);
  4743. };
  4744. var getToggleBehaviours = function (command) {
  4745. return derive$1([
  4746. Toggling.config({
  4747. toggleClass: Styles.resolve('toolbar-button-selected'),
  4748. toggleOnExecute: false,
  4749. aria: { mode: 'pressed' }
  4750. }),
  4751. Receivers.format(command, function (button, status) {
  4752. var toggle = status ? Toggling.on : Toggling.off;
  4753. toggle(button);
  4754. })
  4755. ]);
  4756. };
  4757. var forToolbarStateCommand = function (editor, command) {
  4758. var extraBehaviours = getToggleBehaviours(command);
  4759. return forToolbar(command, function () {
  4760. editor.execCommand(command);
  4761. }, extraBehaviours, editor);
  4762. };
  4763. var forToolbarStateAction = function (editor, clazz, command, action) {
  4764. var extraBehaviours = getToggleBehaviours(command);
  4765. return forToolbar(clazz, action, extraBehaviours, editor);
  4766. };
  4767. var getToolbarIconButton = function (clazz, editor) {
  4768. var icons = editor.ui.registry.getAll().icons;
  4769. var optOxideIcon = Option.from(icons[clazz]);
  4770. return optOxideIcon.fold(function () {
  4771. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4772. }, function (icon) {
  4773. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4774. });
  4775. };
  4776. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4777. return Button.sketch({
  4778. dom: getToolbarIconButton(clazz, editor),
  4779. action: action,
  4780. buttonBehaviours: deepMerge(derive$1([Unselecting.config({})]), extraBehaviours)
  4781. });
  4782. };
  4783. var Buttons = {
  4784. forToolbar: forToolbar,
  4785. forToolbarCommand: forToolbarCommand,
  4786. forToolbarStateAction: forToolbarStateAction,
  4787. forToolbarStateCommand: forToolbarStateCommand,
  4788. getToolbarIconButton: getToolbarIconButton
  4789. };
  4790. var labelPart = optional({
  4791. schema: [strict$1('dom')],
  4792. name: 'label'
  4793. });
  4794. var edgePart = function (name) {
  4795. return optional({
  4796. name: '' + name + '-edge',
  4797. overrides: function (detail) {
  4798. var action = detail.model.manager.edgeActions[name];
  4799. return action.fold(function () {
  4800. return {};
  4801. }, function (a) {
  4802. return {
  4803. events: derive([
  4804. runActionExtra(touchstart(), function (comp, se, d) {
  4805. return a(comp, d);
  4806. }, [detail]),
  4807. runActionExtra(mousedown(), function (comp, se, d) {
  4808. return a(comp, d);
  4809. }, [detail]),
  4810. runActionExtra(mousemove(), function (comp, se, det) {
  4811. if (det.mouseIsDown.get()) {
  4812. a(comp, det);
  4813. }
  4814. }, [detail])
  4815. ])
  4816. };
  4817. });
  4818. }
  4819. });
  4820. };
  4821. var tlEdgePart = edgePart('top-left');
  4822. var tedgePart = edgePart('top');
  4823. var trEdgePart = edgePart('top-right');
  4824. var redgePart = edgePart('right');
  4825. var brEdgePart = edgePart('bottom-right');
  4826. var bedgePart = edgePart('bottom');
  4827. var blEdgePart = edgePart('bottom-left');
  4828. var ledgePart = edgePart('left');
  4829. var thumbPart = required({
  4830. name: 'thumb',
  4831. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  4832. overrides: function (detail) {
  4833. return {
  4834. events: derive([
  4835. redirectToPart(touchstart(), detail, 'spectrum'),
  4836. redirectToPart(touchmove(), detail, 'spectrum'),
  4837. redirectToPart(touchend(), detail, 'spectrum'),
  4838. redirectToPart(mousedown(), detail, 'spectrum'),
  4839. redirectToPart(mousemove(), detail, 'spectrum'),
  4840. redirectToPart(mouseup(), detail, 'spectrum')
  4841. ])
  4842. };
  4843. }
  4844. });
  4845. var spectrumPart = required({
  4846. schema: [state$1('mouseIsDown', function () {
  4847. return Cell(false);
  4848. })],
  4849. name: 'spectrum',
  4850. overrides: function (detail) {
  4851. var modelDetail = detail.model;
  4852. var model = modelDetail.manager;
  4853. var setValueFrom = function (component, simulatedEvent) {
  4854. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  4855. return model.setValueFrom(component, detail, value);
  4856. });
  4857. };
  4858. return {
  4859. behaviours: derive$1([
  4860. Keying.config({
  4861. mode: 'special',
  4862. onLeft: function (spectrum) {
  4863. return model.onLeft(spectrum, detail);
  4864. },
  4865. onRight: function (spectrum) {
  4866. return model.onRight(spectrum, detail);
  4867. },
  4868. onUp: function (spectrum) {
  4869. return model.onUp(spectrum, detail);
  4870. },
  4871. onDown: function (spectrum) {
  4872. return model.onDown(spectrum, detail);
  4873. }
  4874. }),
  4875. Focusing.config({})
  4876. ]),
  4877. events: derive([
  4878. run(touchstart(), setValueFrom),
  4879. run(touchmove(), setValueFrom),
  4880. run(mousedown(), setValueFrom),
  4881. run(mousemove(), function (spectrum, se) {
  4882. if (detail.mouseIsDown.get()) {
  4883. setValueFrom(spectrum, se);
  4884. }
  4885. })
  4886. ])
  4887. };
  4888. }
  4889. });
  4890. var SliderParts = [
  4891. labelPart,
  4892. ledgePart,
  4893. redgePart,
  4894. tedgePart,
  4895. bedgePart,
  4896. tlEdgePart,
  4897. trEdgePart,
  4898. blEdgePart,
  4899. brEdgePart,
  4900. thumbPart,
  4901. spectrumPart
  4902. ];
  4903. var onLoad$1 = function (component, repConfig, repState) {
  4904. repConfig.store.manager.onLoad(component, repConfig, repState);
  4905. };
  4906. var onUnload = function (component, repConfig, repState) {
  4907. repConfig.store.manager.onUnload(component, repConfig, repState);
  4908. };
  4909. var setValue = function (component, repConfig, repState, data) {
  4910. repConfig.store.manager.setValue(component, repConfig, repState, data);
  4911. };
  4912. var getValue = function (component, repConfig, repState) {
  4913. return repConfig.store.manager.getValue(component, repConfig, repState);
  4914. };
  4915. var getState = function (component, repConfig, repState) {
  4916. return repState;
  4917. };
  4918. var RepresentApis = /*#__PURE__*/Object.freeze({
  4919. __proto__: null,
  4920. onLoad: onLoad$1,
  4921. onUnload: onUnload,
  4922. setValue: setValue,
  4923. getValue: getValue,
  4924. getState: getState
  4925. });
  4926. var events$5 = function (repConfig, repState) {
  4927. var es = repConfig.resetOnDom ? [
  4928. runOnAttached(function (comp, se) {
  4929. onLoad$1(comp, repConfig, repState);
  4930. }),
  4931. runOnDetached(function (comp, se) {
  4932. onUnload(comp, repConfig, repState);
  4933. })
  4934. ] : [loadEvent(repConfig, repState, onLoad$1)];
  4935. return derive(es);
  4936. };
  4937. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  4938. __proto__: null,
  4939. events: events$5
  4940. });
  4941. var memory = function () {
  4942. var data = Cell(null);
  4943. var readState = function () {
  4944. return {
  4945. mode: 'memory',
  4946. value: data.get()
  4947. };
  4948. };
  4949. var isNotSet = function () {
  4950. return data.get() === null;
  4951. };
  4952. var clear = function () {
  4953. data.set(null);
  4954. };
  4955. return nu$6({
  4956. set: data.set,
  4957. get: data.get,
  4958. isNotSet: isNotSet,
  4959. clear: clear,
  4960. readState: readState
  4961. });
  4962. };
  4963. var manual = function () {
  4964. var readState = function () {
  4965. };
  4966. return nu$6({ readState: readState });
  4967. };
  4968. var dataset = function () {
  4969. var dataByValue = Cell({});
  4970. var dataByText = Cell({});
  4971. var readState = function () {
  4972. return {
  4973. mode: 'dataset',
  4974. dataByValue: dataByValue.get(),
  4975. dataByText: dataByText.get()
  4976. };
  4977. };
  4978. var clear = function () {
  4979. dataByValue.set({});
  4980. dataByText.set({});
  4981. };
  4982. var lookup = function (itemString) {
  4983. return get(dataByValue.get(), itemString).orThunk(function () {
  4984. return get(dataByText.get(), itemString);
  4985. });
  4986. };
  4987. var update = function (items) {
  4988. var currentDataByValue = dataByValue.get();
  4989. var currentDataByText = dataByText.get();
  4990. var newDataByValue = {};
  4991. var newDataByText = {};
  4992. each$1(items, function (item) {
  4993. newDataByValue[item.value] = item;
  4994. get(item, 'meta').each(function (meta) {
  4995. get(meta, 'text').each(function (text) {
  4996. newDataByText[text] = item;
  4997. });
  4998. });
  4999. });
  5000. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5001. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5002. };
  5003. return nu$6({
  5004. readState: readState,
  5005. lookup: lookup,
  5006. update: update,
  5007. clear: clear
  5008. });
  5009. };
  5010. var init$1 = function (spec) {
  5011. return spec.store.manager.state(spec);
  5012. };
  5013. var RepresentState = /*#__PURE__*/Object.freeze({
  5014. __proto__: null,
  5015. memory: memory,
  5016. dataset: dataset,
  5017. manual: manual,
  5018. init: init$1
  5019. });
  5020. var setValue$1 = function (component, repConfig, repState, data) {
  5021. var store = repConfig.store;
  5022. repState.update([data]);
  5023. store.setValue(component, data);
  5024. repConfig.onSetValue(component, data);
  5025. };
  5026. var getValue$1 = function (component, repConfig, repState) {
  5027. var store = repConfig.store;
  5028. var key = store.getDataKey(component);
  5029. return repState.lookup(key).fold(function () {
  5030. return store.getFallbackEntry(key);
  5031. }, function (data) {
  5032. return data;
  5033. });
  5034. };
  5035. var onLoad$2 = function (component, repConfig, repState) {
  5036. var store = repConfig.store;
  5037. store.initialValue.each(function (data) {
  5038. setValue$1(component, repConfig, repState, data);
  5039. });
  5040. };
  5041. var onUnload$1 = function (component, repConfig, repState) {
  5042. repState.clear();
  5043. };
  5044. var DatasetStore = [
  5045. option('initialValue'),
  5046. strict$1('getFallbackEntry'),
  5047. strict$1('getDataKey'),
  5048. strict$1('setValue'),
  5049. output('manager', {
  5050. setValue: setValue$1,
  5051. getValue: getValue$1,
  5052. onLoad: onLoad$2,
  5053. onUnload: onUnload$1,
  5054. state: dataset
  5055. })
  5056. ];
  5057. var getValue$2 = function (component, repConfig, repState) {
  5058. return repConfig.store.getValue(component);
  5059. };
  5060. var setValue$2 = function (component, repConfig, repState, data) {
  5061. repConfig.store.setValue(component, data);
  5062. repConfig.onSetValue(component, data);
  5063. };
  5064. var onLoad$3 = function (component, repConfig, repState) {
  5065. repConfig.store.initialValue.each(function (data) {
  5066. repConfig.store.setValue(component, data);
  5067. });
  5068. };
  5069. var ManualStore = [
  5070. strict$1('getValue'),
  5071. defaulted$1('setValue', noop),
  5072. option('initialValue'),
  5073. output('manager', {
  5074. setValue: setValue$2,
  5075. getValue: getValue$2,
  5076. onLoad: onLoad$3,
  5077. onUnload: noop,
  5078. state: NoState.init
  5079. })
  5080. ];
  5081. var setValue$3 = function (component, repConfig, repState, data) {
  5082. repState.set(data);
  5083. repConfig.onSetValue(component, data);
  5084. };
  5085. var getValue$3 = function (component, repConfig, repState) {
  5086. return repState.get();
  5087. };
  5088. var onLoad$4 = function (component, repConfig, repState) {
  5089. repConfig.store.initialValue.each(function (initVal) {
  5090. if (repState.isNotSet()) {
  5091. repState.set(initVal);
  5092. }
  5093. });
  5094. };
  5095. var onUnload$2 = function (component, repConfig, repState) {
  5096. repState.clear();
  5097. };
  5098. var MemoryStore = [
  5099. option('initialValue'),
  5100. output('manager', {
  5101. setValue: setValue$3,
  5102. getValue: getValue$3,
  5103. onLoad: onLoad$4,
  5104. onUnload: onUnload$2,
  5105. state: memory
  5106. })
  5107. ];
  5108. var RepresentSchema = [
  5109. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5110. memory: MemoryStore,
  5111. manual: ManualStore,
  5112. dataset: DatasetStore
  5113. })),
  5114. onHandler('onSetValue'),
  5115. defaulted$1('resetOnDom', false)
  5116. ];
  5117. var Representing = create$1({
  5118. fields: RepresentSchema,
  5119. name: 'representing',
  5120. active: ActiveRepresenting,
  5121. apis: RepresentApis,
  5122. extra: {
  5123. setValueFrom: function (component, source) {
  5124. var value = Representing.getValue(source);
  5125. Representing.setValue(component, value);
  5126. }
  5127. },
  5128. state: RepresentState
  5129. });
  5130. var api$1 = Dimension('width', function (element) {
  5131. return element.dom().offsetWidth;
  5132. });
  5133. var set$4 = function (element, h) {
  5134. api$1.set(element, h);
  5135. };
  5136. var get$7 = function (element) {
  5137. return api$1.get(element);
  5138. };
  5139. var r = function (left, top) {
  5140. var translate = function (x, y) {
  5141. return r(left + x, top + y);
  5142. };
  5143. return {
  5144. left: constant(left),
  5145. top: constant(top),
  5146. translate: translate
  5147. };
  5148. };
  5149. var Position = r;
  5150. var _sliderChangeEvent = 'slider.change.value';
  5151. var sliderChangeEvent = constant(_sliderChangeEvent);
  5152. var isTouchEvent = function (evt) {
  5153. return evt.type.indexOf('touch') !== -1;
  5154. };
  5155. var getEventSource = function (simulatedEvent) {
  5156. var evt = simulatedEvent.event().raw();
  5157. if (isTouchEvent(evt)) {
  5158. var touchEvent = evt;
  5159. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  5160. return Position(t.clientX, t.clientY);
  5161. }) : Option.none();
  5162. } else {
  5163. var mouseEvent = evt;
  5164. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  5165. return Position(me.clientX, me.clientY);
  5166. }) : Option.none();
  5167. }
  5168. };
  5169. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  5170. var minX = function (detail) {
  5171. return detail.model.minX;
  5172. };
  5173. var minY = function (detail) {
  5174. return detail.model.minY;
  5175. };
  5176. var min1X = function (detail) {
  5177. return detail.model.minX - 1;
  5178. };
  5179. var min1Y = function (detail) {
  5180. return detail.model.minY - 1;
  5181. };
  5182. var maxX = function (detail) {
  5183. return detail.model.maxX;
  5184. };
  5185. var maxY = function (detail) {
  5186. return detail.model.maxY;
  5187. };
  5188. var max1X = function (detail) {
  5189. return detail.model.maxX + 1;
  5190. };
  5191. var max1Y = function (detail) {
  5192. return detail.model.maxY + 1;
  5193. };
  5194. var range = function (detail, max, min) {
  5195. return max(detail) - min(detail);
  5196. };
  5197. var xRange = function (detail) {
  5198. return range(detail, maxX, minX);
  5199. };
  5200. var yRange = function (detail) {
  5201. return range(detail, maxY, minY);
  5202. };
  5203. var halfX = function (detail) {
  5204. return xRange(detail) / 2;
  5205. };
  5206. var halfY = function (detail) {
  5207. return yRange(detail) / 2;
  5208. };
  5209. var step = function (detail) {
  5210. return detail.stepSize;
  5211. };
  5212. var snap = function (detail) {
  5213. return detail.snapToGrid;
  5214. };
  5215. var snapStart = function (detail) {
  5216. return detail.snapStart;
  5217. };
  5218. var rounded = function (detail) {
  5219. return detail.rounded;
  5220. };
  5221. var hasEdge = function (detail, edgeName) {
  5222. return detail[edgeName + '-edge'] !== undefined;
  5223. };
  5224. var hasLEdge = function (detail) {
  5225. return hasEdge(detail, l);
  5226. };
  5227. var hasREdge = function (detail) {
  5228. return hasEdge(detail, r$1);
  5229. };
  5230. var hasTEdge = function (detail) {
  5231. return hasEdge(detail, t);
  5232. };
  5233. var hasBEdge = function (detail) {
  5234. return hasEdge(detail, b);
  5235. };
  5236. var currentValue = function (detail) {
  5237. return detail.model.value.get();
  5238. };
  5239. var xValue = function (x) {
  5240. return { x: constant(x) };
  5241. };
  5242. var yValue = function (y) {
  5243. return { y: constant(y) };
  5244. };
  5245. var xyValue = function (x, y) {
  5246. return {
  5247. x: constant(x),
  5248. y: constant(y)
  5249. };
  5250. };
  5251. var fireSliderChange = function (component, value) {
  5252. emitWith(component, sliderChangeEvent(), { value: value });
  5253. };
  5254. var setToTLEdgeXY = function (edge, detail) {
  5255. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  5256. };
  5257. var setToTEdge = function (edge, detail) {
  5258. fireSliderChange(edge, yValue(min1Y(detail)));
  5259. };
  5260. var setToTEdgeXY = function (edge, detail) {
  5261. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  5262. };
  5263. var setToTREdgeXY = function (edge, detail) {
  5264. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  5265. };
  5266. var setToREdge = function (edge, detail) {
  5267. fireSliderChange(edge, xValue(max1X(detail)));
  5268. };
  5269. var setToREdgeXY = function (edge, detail) {
  5270. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  5271. };
  5272. var setToBREdgeXY = function (edge, detail) {
  5273. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  5274. };
  5275. var setToBEdge = function (edge, detail) {
  5276. fireSliderChange(edge, yValue(max1Y(detail)));
  5277. };
  5278. var setToBEdgeXY = function (edge, detail) {
  5279. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  5280. };
  5281. var setToBLEdgeXY = function (edge, detail) {
  5282. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  5283. };
  5284. var setToLEdge = function (edge, detail) {
  5285. fireSliderChange(edge, xValue(min1X(detail)));
  5286. };
  5287. var setToLEdgeXY = function (edge, detail) {
  5288. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  5289. };
  5290. var reduceBy = function (value, min, max, step) {
  5291. if (value < min) {
  5292. return value;
  5293. } else if (value > max) {
  5294. return max;
  5295. } else if (value === min) {
  5296. return min - 1;
  5297. } else {
  5298. return Math.max(min, value - step);
  5299. }
  5300. };
  5301. var increaseBy = function (value, min, max, step) {
  5302. if (value > max) {
  5303. return value;
  5304. } else if (value < min) {
  5305. return min;
  5306. } else if (value === max) {
  5307. return max + 1;
  5308. } else {
  5309. return Math.min(max, value + step);
  5310. }
  5311. };
  5312. var capValue = function (value, min, max) {
  5313. return Math.max(min, Math.min(max, value));
  5314. };
  5315. var snapValueOf = function (value, min, max, step, snapStart) {
  5316. return snapStart.fold(function () {
  5317. var initValue = value - min;
  5318. var extraValue = Math.round(initValue / step) * step;
  5319. return capValue(min + extraValue, min - 1, max + 1);
  5320. }, function (start) {
  5321. var remainder = (value - start) % step;
  5322. var adjustment = Math.round(remainder / step);
  5323. var rawSteps = Math.floor((value - start) / step);
  5324. var maxSteps = Math.floor((max - start) / step);
  5325. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5326. var r = start + numSteps * step;
  5327. return Math.max(start, r);
  5328. });
  5329. };
  5330. var findOffsetOf = function (value, min, max) {
  5331. return Math.min(max, Math.max(value, min)) - min;
  5332. };
  5333. var findValueOf = function (args) {
  5334. 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;
  5335. var capMin = hasMinEdge ? min - 1 : min;
  5336. var capMax = hasMaxEdge ? max + 1 : max;
  5337. if (value < minBound) {
  5338. return capMin;
  5339. } else if (value > maxBound) {
  5340. return capMax;
  5341. } else {
  5342. var offset = findOffsetOf(value, minBound, maxBound);
  5343. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5344. if (snap && newValue >= min && newValue <= max) {
  5345. return snapValueOf(newValue, min, max, step, snapStart);
  5346. } else if (rounded) {
  5347. return Math.round(newValue);
  5348. } else {
  5349. return newValue;
  5350. }
  5351. }
  5352. };
  5353. var findOffsetOfValue = function (args) {
  5354. 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;
  5355. if (value < min) {
  5356. return hasMinEdge ? 0 : centerMinEdge;
  5357. } else if (value > max) {
  5358. return hasMaxEdge ? maxBound : centerMaxEdge;
  5359. } else {
  5360. return (value - min) / range * maxOffset;
  5361. }
  5362. };
  5363. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5364. var getBounds = function (component) {
  5365. return component.element().dom().getBoundingClientRect();
  5366. };
  5367. var getBoundsProperty = function (bounds, property) {
  5368. return bounds[property];
  5369. };
  5370. var getMinXBounds = function (component) {
  5371. var bounds = getBounds(component);
  5372. return getBoundsProperty(bounds, left);
  5373. };
  5374. var getMaxXBounds = function (component) {
  5375. var bounds = getBounds(component);
  5376. return getBoundsProperty(bounds, right);
  5377. };
  5378. var getMinYBounds = function (component) {
  5379. var bounds = getBounds(component);
  5380. return getBoundsProperty(bounds, top);
  5381. };
  5382. var getMaxYBounds = function (component) {
  5383. var bounds = getBounds(component);
  5384. return getBoundsProperty(bounds, bottom);
  5385. };
  5386. var getXScreenRange = function (component) {
  5387. var bounds = getBounds(component);
  5388. return getBoundsProperty(bounds, width);
  5389. };
  5390. var getYScreenRange = function (component) {
  5391. var bounds = getBounds(component);
  5392. return getBoundsProperty(bounds, height);
  5393. };
  5394. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5395. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5396. };
  5397. var getXCenterOffSetOf = function (component, spectrum) {
  5398. var componentBounds = getBounds(component);
  5399. var spectrumBounds = getBounds(spectrum);
  5400. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5401. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5402. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5403. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5404. };
  5405. var getYCenterOffSetOf = function (component, spectrum) {
  5406. var componentBounds = getBounds(component);
  5407. var spectrumBounds = getBounds(spectrum);
  5408. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5409. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5410. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5411. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5412. };
  5413. var fireSliderChange$1 = function (spectrum, value) {
  5414. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5415. };
  5416. var sliderValue = function (x) {
  5417. return { x: constant(x) };
  5418. };
  5419. var findValueOfOffset = function (spectrum, detail, left) {
  5420. var args = {
  5421. min: minX(detail),
  5422. max: maxX(detail),
  5423. range: xRange(detail),
  5424. value: left,
  5425. step: step(detail),
  5426. snap: snap(detail),
  5427. snapStart: snapStart(detail),
  5428. rounded: rounded(detail),
  5429. hasMinEdge: hasLEdge(detail),
  5430. hasMaxEdge: hasREdge(detail),
  5431. minBound: getMinXBounds(spectrum),
  5432. maxBound: getMaxXBounds(spectrum),
  5433. screenRange: getXScreenRange(spectrum)
  5434. };
  5435. return findValueOf(args);
  5436. };
  5437. var setValueFrom = function (spectrum, detail, value) {
  5438. var xValue = findValueOfOffset(spectrum, detail, value);
  5439. var sliderVal = sliderValue(xValue);
  5440. fireSliderChange$1(spectrum, sliderVal);
  5441. return xValue;
  5442. };
  5443. var setToMin = function (spectrum, detail) {
  5444. var min = minX(detail);
  5445. fireSliderChange$1(spectrum, sliderValue(min));
  5446. };
  5447. var setToMax = function (spectrum, detail) {
  5448. var max = maxX(detail);
  5449. fireSliderChange$1(spectrum, sliderValue(max));
  5450. };
  5451. var moveBy = function (direction, spectrum, detail) {
  5452. var f = direction > 0 ? increaseBy : reduceBy;
  5453. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  5454. fireSliderChange$1(spectrum, sliderValue(xValue));
  5455. return Option.some(xValue);
  5456. };
  5457. var handleMovement = function (direction) {
  5458. return function (spectrum, detail) {
  5459. return moveBy(direction, spectrum, detail).map(function () {
  5460. return true;
  5461. });
  5462. };
  5463. };
  5464. var getValueFromEvent = function (simulatedEvent) {
  5465. var pos = getEventSource(simulatedEvent);
  5466. return pos.map(function (p) {
  5467. return p.left();
  5468. });
  5469. };
  5470. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5471. var minOffset = 0;
  5472. var maxOffset = getXScreenRange(spectrum);
  5473. var centerMinEdge = minEdge.bind(function (edge) {
  5474. return Option.some(getXCenterOffSetOf(edge, spectrum));
  5475. }).getOr(minOffset);
  5476. var centerMaxEdge = maxEdge.bind(function (edge) {
  5477. return Option.some(getXCenterOffSetOf(edge, spectrum));
  5478. }).getOr(maxOffset);
  5479. var args = {
  5480. min: minX(detail),
  5481. max: maxX(detail),
  5482. range: xRange(detail),
  5483. value: value,
  5484. hasMinEdge: hasLEdge(detail),
  5485. hasMaxEdge: hasREdge(detail),
  5486. minBound: getMinXBounds(spectrum),
  5487. minOffset: minOffset,
  5488. maxBound: getMaxXBounds(spectrum),
  5489. maxOffset: maxOffset,
  5490. centerMinEdge: centerMinEdge,
  5491. centerMaxEdge: centerMaxEdge
  5492. };
  5493. return findOffsetOfValue(args);
  5494. };
  5495. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5496. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5497. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5498. };
  5499. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5500. var value = currentValue(detail);
  5501. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5502. var thumbRadius = get$7(thumb.element()) / 2;
  5503. set$3(thumb.element(), 'left', pos - thumbRadius + 'px');
  5504. };
  5505. var onLeft = handleMovement(-1);
  5506. var onRight = handleMovement(1);
  5507. var onUp = Option.none;
  5508. var onDown = Option.none;
  5509. var edgeActions = {
  5510. 'top-left': Option.none(),
  5511. 'top': Option.none(),
  5512. 'top-right': Option.none(),
  5513. 'right': Option.some(setToREdge),
  5514. 'bottom-right': Option.none(),
  5515. 'bottom': Option.none(),
  5516. 'bottom-left': Option.none(),
  5517. 'left': Option.some(setToLEdge)
  5518. };
  5519. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5520. __proto__: null,
  5521. setValueFrom: setValueFrom,
  5522. setToMin: setToMin,
  5523. setToMax: setToMax,
  5524. findValueOfOffset: findValueOfOffset,
  5525. getValueFromEvent: getValueFromEvent,
  5526. findPositionOfValue: findPositionOfValue,
  5527. setPositionFromValue: setPositionFromValue,
  5528. onLeft: onLeft,
  5529. onRight: onRight,
  5530. onUp: onUp,
  5531. onDown: onDown,
  5532. edgeActions: edgeActions
  5533. });
  5534. var fireSliderChange$2 = function (spectrum, value) {
  5535. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5536. };
  5537. var sliderValue$1 = function (y) {
  5538. return { y: constant(y) };
  5539. };
  5540. var findValueOfOffset$1 = function (spectrum, detail, top) {
  5541. var args = {
  5542. min: minY(detail),
  5543. max: maxY(detail),
  5544. range: yRange(detail),
  5545. value: top,
  5546. step: step(detail),
  5547. snap: snap(detail),
  5548. snapStart: snapStart(detail),
  5549. rounded: rounded(detail),
  5550. hasMinEdge: hasTEdge(detail),
  5551. hasMaxEdge: hasBEdge(detail),
  5552. minBound: getMinYBounds(spectrum),
  5553. maxBound: getMaxYBounds(spectrum),
  5554. screenRange: getYScreenRange(spectrum)
  5555. };
  5556. return findValueOf(args);
  5557. };
  5558. var setValueFrom$1 = function (spectrum, detail, value) {
  5559. var yValue = findValueOfOffset$1(spectrum, detail, value);
  5560. var sliderVal = sliderValue$1(yValue);
  5561. fireSliderChange$2(spectrum, sliderVal);
  5562. return yValue;
  5563. };
  5564. var setToMin$1 = function (spectrum, detail) {
  5565. var min = minY(detail);
  5566. fireSliderChange$2(spectrum, sliderValue$1(min));
  5567. };
  5568. var setToMax$1 = function (spectrum, detail) {
  5569. var max = maxY(detail);
  5570. fireSliderChange$2(spectrum, sliderValue$1(max));
  5571. };
  5572. var moveBy$1 = function (direction, spectrum, detail) {
  5573. var f = direction > 0 ? increaseBy : reduceBy;
  5574. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  5575. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  5576. return Option.some(yValue);
  5577. };
  5578. var handleMovement$1 = function (direction) {
  5579. return function (spectrum, detail) {
  5580. return moveBy$1(direction, spectrum, detail).map(function () {
  5581. return true;
  5582. });
  5583. };
  5584. };
  5585. var getValueFromEvent$1 = function (simulatedEvent) {
  5586. var pos = getEventSource(simulatedEvent);
  5587. return pos.map(function (p) {
  5588. return p.top();
  5589. });
  5590. };
  5591. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  5592. var minOffset = 0;
  5593. var maxOffset = getYScreenRange(spectrum);
  5594. var centerMinEdge = minEdge.bind(function (edge) {
  5595. return Option.some(getYCenterOffSetOf(edge, spectrum));
  5596. }).getOr(minOffset);
  5597. var centerMaxEdge = maxEdge.bind(function (edge) {
  5598. return Option.some(getYCenterOffSetOf(edge, spectrum));
  5599. }).getOr(maxOffset);
  5600. var args = {
  5601. min: minY(detail),
  5602. max: maxY(detail),
  5603. range: yRange(detail),
  5604. value: value,
  5605. hasMinEdge: hasTEdge(detail),
  5606. hasMaxEdge: hasBEdge(detail),
  5607. minBound: getMinYBounds(spectrum),
  5608. minOffset: minOffset,
  5609. maxBound: getMaxYBounds(spectrum),
  5610. maxOffset: maxOffset,
  5611. centerMinEdge: centerMinEdge,
  5612. centerMaxEdge: centerMaxEdge
  5613. };
  5614. return findOffsetOfValue(args);
  5615. };
  5616. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5617. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  5618. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5619. };
  5620. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5621. var value = currentValue(detail);
  5622. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5623. var thumbRadius = get$5(thumb.element()) / 2;
  5624. set$3(thumb.element(), 'top', pos - thumbRadius + 'px');
  5625. };
  5626. var onLeft$1 = Option.none;
  5627. var onRight$1 = Option.none;
  5628. var onUp$1 = handleMovement$1(-1);
  5629. var onDown$1 = handleMovement$1(1);
  5630. var edgeActions$1 = {
  5631. 'top-left': Option.none(),
  5632. 'top': Option.some(setToTEdge),
  5633. 'top-right': Option.none(),
  5634. 'right': Option.none(),
  5635. 'bottom-right': Option.none(),
  5636. 'bottom': Option.some(setToBEdge),
  5637. 'bottom-left': Option.none(),
  5638. 'left': Option.none()
  5639. };
  5640. var VerticalModel = /*#__PURE__*/Object.freeze({
  5641. __proto__: null,
  5642. setValueFrom: setValueFrom$1,
  5643. setToMin: setToMin$1,
  5644. setToMax: setToMax$1,
  5645. findValueOfOffset: findValueOfOffset$1,
  5646. getValueFromEvent: getValueFromEvent$1,
  5647. findPositionOfValue: findPositionOfValue$1,
  5648. setPositionFromValue: setPositionFromValue$1,
  5649. onLeft: onLeft$1,
  5650. onRight: onRight$1,
  5651. onUp: onUp$1,
  5652. onDown: onDown$1,
  5653. edgeActions: edgeActions$1
  5654. });
  5655. var fireSliderChange$3 = function (spectrum, value) {
  5656. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5657. };
  5658. var sliderValue$2 = function (x, y) {
  5659. return {
  5660. x: constant(x),
  5661. y: constant(y)
  5662. };
  5663. };
  5664. var setValueFrom$2 = function (spectrum, detail, value) {
  5665. var xValue = findValueOfOffset(spectrum, detail, value.left());
  5666. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  5667. var val = sliderValue$2(xValue, yValue);
  5668. fireSliderChange$3(spectrum, val);
  5669. return val;
  5670. };
  5671. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  5672. var f = direction > 0 ? increaseBy : reduceBy;
  5673. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  5674. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  5675. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  5676. return Option.some(xValue);
  5677. };
  5678. var handleMovement$2 = function (direction, isVerticalMovement) {
  5679. return function (spectrum, detail) {
  5680. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  5681. return true;
  5682. });
  5683. };
  5684. };
  5685. var setToMin$2 = function (spectrum, detail) {
  5686. var mX = minX(detail);
  5687. var mY = minY(detail);
  5688. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5689. };
  5690. var setToMax$2 = function (spectrum, detail) {
  5691. var mX = maxX(detail);
  5692. var mY = maxY(detail);
  5693. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5694. };
  5695. var getValueFromEvent$2 = function (simulatedEvent) {
  5696. return getEventSource(simulatedEvent);
  5697. };
  5698. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5699. var value = currentValue(detail);
  5700. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5701. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5702. var thumbXRadius = get$7(thumb.element()) / 2;
  5703. var thumbYRadius = get$5(thumb.element()) / 2;
  5704. set$3(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  5705. set$3(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  5706. };
  5707. var onLeft$2 = handleMovement$2(-1, false);
  5708. var onRight$2 = handleMovement$2(1, false);
  5709. var onUp$2 = handleMovement$2(-1, true);
  5710. var onDown$2 = handleMovement$2(1, true);
  5711. var edgeActions$2 = {
  5712. 'top-left': Option.some(setToTLEdgeXY),
  5713. 'top': Option.some(setToTEdgeXY),
  5714. 'top-right': Option.some(setToTREdgeXY),
  5715. 'right': Option.some(setToREdgeXY),
  5716. 'bottom-right': Option.some(setToBREdgeXY),
  5717. 'bottom': Option.some(setToBEdgeXY),
  5718. 'bottom-left': Option.some(setToBLEdgeXY),
  5719. 'left': Option.some(setToLEdgeXY)
  5720. };
  5721. var TwoDModel = /*#__PURE__*/Object.freeze({
  5722. __proto__: null,
  5723. setValueFrom: setValueFrom$2,
  5724. setToMin: setToMin$2,
  5725. setToMax: setToMax$2,
  5726. getValueFromEvent: getValueFromEvent$2,
  5727. setPositionFromValue: setPositionFromValue$2,
  5728. onLeft: onLeft$2,
  5729. onRight: onRight$2,
  5730. onUp: onUp$2,
  5731. onDown: onDown$2,
  5732. edgeActions: edgeActions$2
  5733. });
  5734. var SliderSchema = [
  5735. defaulted$1('stepSize', 1),
  5736. defaulted$1('onChange', noop),
  5737. defaulted$1('onChoose', noop),
  5738. defaulted$1('onInit', noop),
  5739. defaulted$1('onDragStart', noop),
  5740. defaulted$1('onDragEnd', noop),
  5741. defaulted$1('snapToGrid', false),
  5742. defaulted$1('rounded', true),
  5743. option('snapStart'),
  5744. strictOf('model', choose$1('mode', {
  5745. x: [
  5746. defaulted$1('minX', 0),
  5747. defaulted$1('maxX', 100),
  5748. state$1('value', function (spec) {
  5749. return Cell(spec.mode.minX);
  5750. }),
  5751. strict$1('getInitialValue'),
  5752. output('manager', HorizontalModel)
  5753. ],
  5754. y: [
  5755. defaulted$1('minY', 0),
  5756. defaulted$1('maxY', 100),
  5757. state$1('value', function (spec) {
  5758. return Cell(spec.mode.minY);
  5759. }),
  5760. strict$1('getInitialValue'),
  5761. output('manager', VerticalModel)
  5762. ],
  5763. xy: [
  5764. defaulted$1('minX', 0),
  5765. defaulted$1('maxX', 100),
  5766. defaulted$1('minY', 0),
  5767. defaulted$1('maxY', 100),
  5768. state$1('value', function (spec) {
  5769. return Cell({
  5770. x: constant(spec.mode.minX),
  5771. y: constant(spec.mode.minY)
  5772. });
  5773. }),
  5774. strict$1('getInitialValue'),
  5775. output('manager', TwoDModel)
  5776. ]
  5777. })),
  5778. field$1('sliderBehaviours', [
  5779. Keying,
  5780. Representing
  5781. ]),
  5782. state$1('mouseIsDown', function () {
  5783. return Cell(false);
  5784. })
  5785. ];
  5786. var mouseReleased = constant('mouse.released');
  5787. var sketch = function (detail, components, _spec, _externals) {
  5788. var _a;
  5789. var getThumb = function (component) {
  5790. return getPartOrDie(component, detail, 'thumb');
  5791. };
  5792. var getSpectrum = function (component) {
  5793. return getPartOrDie(component, detail, 'spectrum');
  5794. };
  5795. var getLeftEdge = function (component) {
  5796. return getPart(component, detail, 'left-edge');
  5797. };
  5798. var getRightEdge = function (component) {
  5799. return getPart(component, detail, 'right-edge');
  5800. };
  5801. var getTopEdge = function (component) {
  5802. return getPart(component, detail, 'top-edge');
  5803. };
  5804. var getBottomEdge = function (component) {
  5805. return getPart(component, detail, 'bottom-edge');
  5806. };
  5807. var modelDetail = detail.model;
  5808. var model = modelDetail.manager;
  5809. var refresh = function (slider, thumb) {
  5810. model.setPositionFromValue(slider, thumb, detail, {
  5811. getLeftEdge: getLeftEdge,
  5812. getRightEdge: getRightEdge,
  5813. getTopEdge: getTopEdge,
  5814. getBottomEdge: getBottomEdge,
  5815. getSpectrum: getSpectrum
  5816. });
  5817. };
  5818. var changeValue = function (slider, newValue) {
  5819. modelDetail.value.set(newValue);
  5820. var thumb = getThumb(slider);
  5821. refresh(slider, thumb);
  5822. detail.onChange(slider, thumb, newValue);
  5823. return Option.some(true);
  5824. };
  5825. var resetToMin = function (slider) {
  5826. model.setToMin(slider, detail);
  5827. };
  5828. var resetToMax = function (slider) {
  5829. model.setToMax(slider, detail);
  5830. };
  5831. var choose = function (slider) {
  5832. var fireOnChoose = function () {
  5833. getPart(slider, detail, 'thumb').each(function (thumb) {
  5834. var value = modelDetail.value.get();
  5835. detail.onChoose(slider, thumb, value);
  5836. });
  5837. };
  5838. var wasDown = detail.mouseIsDown.get();
  5839. detail.mouseIsDown.set(false);
  5840. if (wasDown) {
  5841. fireOnChoose();
  5842. }
  5843. };
  5844. var onDragStart = function (slider, simulatedEvent) {
  5845. simulatedEvent.stop();
  5846. detail.mouseIsDown.set(true);
  5847. detail.onDragStart(slider, getThumb(slider));
  5848. };
  5849. var onDragEnd = function (slider, simulatedEvent) {
  5850. simulatedEvent.stop();
  5851. detail.onDragEnd(slider, getThumb(slider));
  5852. choose(slider);
  5853. };
  5854. return {
  5855. uid: detail.uid,
  5856. dom: detail.dom,
  5857. components: components,
  5858. behaviours: augment(detail.sliderBehaviours, [
  5859. Keying.config({
  5860. mode: 'special',
  5861. focusIn: function (slider) {
  5862. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  5863. }
  5864. }),
  5865. Representing.config({
  5866. store: {
  5867. mode: 'manual',
  5868. getValue: function (_) {
  5869. return modelDetail.value.get();
  5870. }
  5871. }
  5872. }),
  5873. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  5874. ]),
  5875. events: derive([
  5876. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  5877. changeValue(slider, simulatedEvent.event().value());
  5878. }),
  5879. runOnAttached(function (slider, simulatedEvent) {
  5880. var getInitial = modelDetail.getInitialValue();
  5881. modelDetail.value.set(getInitial);
  5882. var thumb = getThumb(slider);
  5883. refresh(slider, thumb);
  5884. var spectrum = getSpectrum(slider);
  5885. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  5886. }),
  5887. run(touchstart(), onDragStart),
  5888. run(touchend(), onDragEnd),
  5889. run(mousedown(), onDragStart),
  5890. run(mouseup(), onDragEnd)
  5891. ]),
  5892. apis: {
  5893. resetToMin: resetToMin,
  5894. resetToMax: resetToMax,
  5895. changeValue: changeValue,
  5896. refresh: refresh
  5897. },
  5898. domModification: { styles: { position: 'relative' } }
  5899. };
  5900. };
  5901. var Slider = composite$1({
  5902. name: 'Slider',
  5903. configFields: SliderSchema,
  5904. partFields: SliderParts,
  5905. factory: sketch,
  5906. apis: {
  5907. resetToMin: function (apis, slider) {
  5908. apis.resetToMin(slider);
  5909. },
  5910. resetToMax: function (apis, slider) {
  5911. apis.resetToMax(slider);
  5912. },
  5913. refresh: function (apis, slider) {
  5914. apis.refresh(slider);
  5915. }
  5916. }
  5917. });
  5918. var button = function (realm, clazz, makeItems, editor) {
  5919. return Buttons.forToolbar(clazz, function () {
  5920. var items = makeItems();
  5921. realm.setContextToolbar([{
  5922. label: clazz + ' group',
  5923. items: items
  5924. }]);
  5925. }, {}, editor);
  5926. };
  5927. var BLACK = -1;
  5928. var makeSlider = function (spec$1) {
  5929. var getColor = function (hue) {
  5930. if (hue < 0) {
  5931. return 'black';
  5932. } else if (hue > 360) {
  5933. return 'white';
  5934. } else {
  5935. return 'hsl(' + hue + ', 100%, 50%)';
  5936. }
  5937. };
  5938. var onInit = function (slider, thumb, spectrum, value) {
  5939. var color = getColor(value.x());
  5940. set$3(thumb.element(), 'background-color', color);
  5941. };
  5942. var onChange = function (slider, thumb, value) {
  5943. var color = getColor(value.x());
  5944. set$3(thumb.element(), 'background-color', color);
  5945. spec$1.onChange(slider, thumb, color);
  5946. };
  5947. return Slider.sketch({
  5948. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  5949. components: [
  5950. Slider.parts()['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  5951. Slider.parts().spectrum({
  5952. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  5953. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  5954. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  5955. }),
  5956. Slider.parts()['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  5957. Slider.parts().thumb({
  5958. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  5959. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  5960. })
  5961. ],
  5962. onChange: onChange,
  5963. onDragStart: function (slider, thumb) {
  5964. Toggling.on(thumb);
  5965. },
  5966. onDragEnd: function (slider, thumb) {
  5967. Toggling.off(thumb);
  5968. },
  5969. onInit: onInit,
  5970. stepSize: 10,
  5971. model: {
  5972. mode: 'x',
  5973. minX: 0,
  5974. maxX: 360,
  5975. getInitialValue: function () {
  5976. return {
  5977. x: function () {
  5978. return spec$1.getInitialValue();
  5979. }
  5980. };
  5981. }
  5982. },
  5983. sliderBehaviours: derive$1([Receivers.orientation(Slider.refresh)])
  5984. });
  5985. };
  5986. var makeItems = function (spec) {
  5987. return [makeSlider(spec)];
  5988. };
  5989. var sketch$1 = function (realm, editor) {
  5990. var spec = {
  5991. onChange: function (slider, thumb, color) {
  5992. editor.undoManager.transact(function () {
  5993. editor.formatter.apply('forecolor', { value: color });
  5994. editor.nodeChanged();
  5995. });
  5996. },
  5997. getInitialValue: function () {
  5998. return BLACK;
  5999. }
  6000. };
  6001. return button(realm, 'color-levels', function () {
  6002. return makeItems(spec);
  6003. }, editor);
  6004. };
  6005. var ColorSlider = {
  6006. makeItems: makeItems,
  6007. sketch: sketch$1
  6008. };
  6009. var schema$7 = objOfOnly([
  6010. strict$1('getInitialValue'),
  6011. strict$1('onChange'),
  6012. strict$1('category'),
  6013. strict$1('sizes')
  6014. ]);
  6015. var sketch$2 = function (rawSpec) {
  6016. var spec$1 = asRawOrDie('SizeSlider', schema$7, rawSpec);
  6017. var isValidValue = function (valueIndex) {
  6018. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6019. };
  6020. var onChange = function (slider, thumb, valueIndex) {
  6021. var index = valueIndex.x();
  6022. if (isValidValue(index)) {
  6023. spec$1.onChange(index);
  6024. }
  6025. };
  6026. return Slider.sketch({
  6027. dom: {
  6028. tag: 'div',
  6029. classes: [
  6030. Styles.resolve('slider-' + spec$1.category + '-size-container'),
  6031. Styles.resolve('slider'),
  6032. Styles.resolve('slider-size-container')
  6033. ]
  6034. },
  6035. onChange: onChange,
  6036. onDragStart: function (slider, thumb) {
  6037. Toggling.on(thumb);
  6038. },
  6039. onDragEnd: function (slider, thumb) {
  6040. Toggling.off(thumb);
  6041. },
  6042. model: {
  6043. mode: 'x',
  6044. minX: 0,
  6045. maxX: spec$1.sizes.length - 1,
  6046. getInitialValue: function () {
  6047. return {
  6048. x: function () {
  6049. return spec$1.getInitialValue();
  6050. }
  6051. };
  6052. }
  6053. },
  6054. stepSize: 1,
  6055. snapToGrid: true,
  6056. sliderBehaviours: derive$1([Receivers.orientation(Slider.refresh)]),
  6057. components: [
  6058. Slider.parts().spectrum({
  6059. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6060. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  6061. }),
  6062. Slider.parts().thumb({
  6063. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6064. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  6065. })
  6066. ]
  6067. });
  6068. };
  6069. var SizeSlider = { sketch: sketch$2 };
  6070. var candidates = [
  6071. '9px',
  6072. '10px',
  6073. '11px',
  6074. '12px',
  6075. '14px',
  6076. '16px',
  6077. '18px',
  6078. '20px',
  6079. '24px',
  6080. '32px',
  6081. '36px'
  6082. ];
  6083. var defaultSize = 'medium';
  6084. var defaultIndex = 2;
  6085. var indexToSize = function (index) {
  6086. return Option.from(candidates[index]);
  6087. };
  6088. var sizeToIndex = function (size) {
  6089. return findIndex(candidates, function (v) {
  6090. return v === size;
  6091. });
  6092. };
  6093. var getRawOrComputed = function (isRoot, rawStart) {
  6094. var optStart = isElement(rawStart) ? Option.some(rawStart) : parent(rawStart).filter(isElement);
  6095. return optStart.map(function (start) {
  6096. var inline = closest$1(start, function (elem) {
  6097. return getRaw(elem, 'font-size').isSome();
  6098. }, isRoot).bind(function (elem) {
  6099. return getRaw(elem, 'font-size');
  6100. });
  6101. return inline.getOrThunk(function () {
  6102. return get$4(start, 'font-size');
  6103. });
  6104. }).getOr('');
  6105. };
  6106. var getSize = function (editor) {
  6107. var node = editor.selection.getStart();
  6108. var elem = Element.fromDom(node);
  6109. var root = Element.fromDom(editor.getBody());
  6110. var isRoot = function (e) {
  6111. return eq(root, e);
  6112. };
  6113. var elemSize = getRawOrComputed(isRoot, elem);
  6114. return find$2(candidates, function (size) {
  6115. return elemSize === size;
  6116. }).getOr(defaultSize);
  6117. };
  6118. var applySize = function (editor, value) {
  6119. var currentValue = getSize(editor);
  6120. if (currentValue !== value) {
  6121. editor.execCommand('fontSize', false, value);
  6122. }
  6123. };
  6124. var get$8 = function (editor) {
  6125. var size = getSize(editor);
  6126. return sizeToIndex(size).getOr(defaultIndex);
  6127. };
  6128. var apply$1 = function (editor, index) {
  6129. indexToSize(index).each(function (size) {
  6130. applySize(editor, size);
  6131. });
  6132. };
  6133. var FontSizes = {
  6134. candidates: constant(candidates),
  6135. get: get$8,
  6136. apply: apply$1
  6137. };
  6138. var sizes = FontSizes.candidates();
  6139. var makeSlider$1 = function (spec) {
  6140. return SizeSlider.sketch({
  6141. onChange: spec.onChange,
  6142. sizes: sizes,
  6143. category: 'font',
  6144. getInitialValue: spec.getInitialValue
  6145. });
  6146. };
  6147. var makeItems$1 = function (spec$1) {
  6148. return [
  6149. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6150. makeSlider$1(spec$1),
  6151. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6152. ];
  6153. };
  6154. var sketch$3 = function (realm, editor) {
  6155. var spec = {
  6156. onChange: function (value) {
  6157. FontSizes.apply(editor, value);
  6158. },
  6159. getInitialValue: function () {
  6160. return FontSizes.get(editor);
  6161. }
  6162. };
  6163. return button(realm, 'font-size', function () {
  6164. return makeItems$1(spec);
  6165. }, editor);
  6166. };
  6167. var record = function (spec) {
  6168. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$3('memento');
  6169. var get = function (anyInSystem) {
  6170. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6171. };
  6172. var getOpt = function (anyInSystem) {
  6173. return anyInSystem.getSystem().getByUid(uid).toOption();
  6174. };
  6175. var asSpec = function () {
  6176. return __assign(__assign({}, spec), { uid: uid });
  6177. };
  6178. return {
  6179. get: get,
  6180. getOpt: getOpt,
  6181. asSpec: asSpec
  6182. };
  6183. };
  6184. var promise = function () {
  6185. var Promise = function (fn) {
  6186. if (typeof this !== 'object') {
  6187. throw new TypeError('Promises must be constructed via new');
  6188. }
  6189. if (typeof fn !== 'function') {
  6190. throw new TypeError('not a function');
  6191. }
  6192. this._state = null;
  6193. this._value = null;
  6194. this._deferreds = [];
  6195. doResolve(fn, bind(resolve, this), bind(reject, this));
  6196. };
  6197. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  6198. domGlobals.setTimeout(fn, 1);
  6199. };
  6200. function bind(fn, thisArg) {
  6201. return function () {
  6202. return fn.apply(thisArg, arguments);
  6203. };
  6204. }
  6205. var isArray = Array.isArray || function (value) {
  6206. return Object.prototype.toString.call(value) === '[object Array]';
  6207. };
  6208. function handle(deferred) {
  6209. var me = this;
  6210. if (this._state === null) {
  6211. this._deferreds.push(deferred);
  6212. return;
  6213. }
  6214. asap(function () {
  6215. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  6216. if (cb === null) {
  6217. (me._state ? deferred.resolve : deferred.reject)(me._value);
  6218. return;
  6219. }
  6220. var ret;
  6221. try {
  6222. ret = cb(me._value);
  6223. } catch (e) {
  6224. deferred.reject(e);
  6225. return;
  6226. }
  6227. deferred.resolve(ret);
  6228. });
  6229. }
  6230. function resolve(newValue) {
  6231. try {
  6232. if (newValue === this) {
  6233. throw new TypeError('A promise cannot be resolved with itself.');
  6234. }
  6235. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6236. var then = newValue.then;
  6237. if (typeof then === 'function') {
  6238. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  6239. return;
  6240. }
  6241. }
  6242. this._state = true;
  6243. this._value = newValue;
  6244. finale.call(this);
  6245. } catch (e) {
  6246. reject.call(this, e);
  6247. }
  6248. }
  6249. function reject(newValue) {
  6250. this._state = false;
  6251. this._value = newValue;
  6252. finale.call(this);
  6253. }
  6254. function finale() {
  6255. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  6256. var deferred = _a[_i];
  6257. handle.call(this, deferred);
  6258. }
  6259. this._deferreds = [];
  6260. }
  6261. function Handler(onFulfilled, onRejected, resolve, reject) {
  6262. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6263. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6264. this.resolve = resolve;
  6265. this.reject = reject;
  6266. }
  6267. function doResolve(fn, onFulfilled, onRejected) {
  6268. var done = false;
  6269. try {
  6270. fn(function (value) {
  6271. if (done) {
  6272. return;
  6273. }
  6274. done = true;
  6275. onFulfilled(value);
  6276. }, function (reason) {
  6277. if (done) {
  6278. return;
  6279. }
  6280. done = true;
  6281. onRejected(reason);
  6282. });
  6283. } catch (ex) {
  6284. if (done) {
  6285. return;
  6286. }
  6287. done = true;
  6288. onRejected(ex);
  6289. }
  6290. }
  6291. Promise.prototype.catch = function (onRejected) {
  6292. return this.then(null, onRejected);
  6293. };
  6294. Promise.prototype.then = function (onFulfilled, onRejected) {
  6295. var me = this;
  6296. return new Promise(function (resolve, reject) {
  6297. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  6298. });
  6299. };
  6300. Promise.all = function () {
  6301. var values = [];
  6302. for (var _i = 0; _i < arguments.length; _i++) {
  6303. values[_i] = arguments[_i];
  6304. }
  6305. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  6306. return new Promise(function (resolve, reject) {
  6307. if (args.length === 0) {
  6308. return resolve([]);
  6309. }
  6310. var remaining = args.length;
  6311. function res(i, val) {
  6312. try {
  6313. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6314. var then = val.then;
  6315. if (typeof then === 'function') {
  6316. then.call(val, function (val) {
  6317. res(i, val);
  6318. }, reject);
  6319. return;
  6320. }
  6321. }
  6322. args[i] = val;
  6323. if (--remaining === 0) {
  6324. resolve(args);
  6325. }
  6326. } catch (ex) {
  6327. reject(ex);
  6328. }
  6329. }
  6330. for (var i = 0; i < args.length; i++) {
  6331. res(i, args[i]);
  6332. }
  6333. });
  6334. };
  6335. Promise.resolve = function (value) {
  6336. if (value && typeof value === 'object' && value.constructor === Promise) {
  6337. return value;
  6338. }
  6339. return new Promise(function (resolve) {
  6340. resolve(value);
  6341. });
  6342. };
  6343. Promise.reject = function (reason) {
  6344. return new Promise(function (resolve, reject) {
  6345. reject(reason);
  6346. });
  6347. };
  6348. Promise.race = function (values) {
  6349. return new Promise(function (resolve, reject) {
  6350. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  6351. var value = values_1[_i];
  6352. value.then(resolve, reject);
  6353. }
  6354. });
  6355. };
  6356. return Promise;
  6357. };
  6358. var Promise = window.Promise ? window.Promise : promise();
  6359. function blobToDataUri(blob) {
  6360. return new Promise(function (resolve) {
  6361. var reader = new domGlobals.FileReader();
  6362. reader.onloadend = function () {
  6363. resolve(reader.result);
  6364. };
  6365. reader.readAsDataURL(blob);
  6366. });
  6367. }
  6368. function blobToBase64(blob) {
  6369. return blobToDataUri(blob).then(function (dataUri) {
  6370. return dataUri.split(',')[1];
  6371. });
  6372. }
  6373. var blobToBase64$1 = function (blob) {
  6374. return blobToBase64(blob);
  6375. };
  6376. var addImage = function (editor, blob) {
  6377. blobToBase64$1(blob).then(function (base64) {
  6378. editor.undoManager.transact(function () {
  6379. var cache = editor.editorUpload.blobCache;
  6380. var info = cache.create(generate$1('mceu'), blob, base64);
  6381. cache.add(info);
  6382. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6383. editor.insertContent(img);
  6384. });
  6385. });
  6386. };
  6387. var extractBlob = function (simulatedEvent) {
  6388. var event = simulatedEvent.event();
  6389. var files = event.raw().target.files || event.raw().dataTransfer.files;
  6390. return Option.from(files[0]);
  6391. };
  6392. var sketch$4 = function (editor) {
  6393. var pickerDom = {
  6394. tag: 'input',
  6395. attributes: {
  6396. accept: 'image/*',
  6397. type: 'file',
  6398. title: ''
  6399. },
  6400. styles: {
  6401. visibility: 'hidden',
  6402. position: 'absolute'
  6403. }
  6404. };
  6405. var memPicker = record({
  6406. dom: pickerDom,
  6407. events: derive([
  6408. cutter(click()),
  6409. run(change(), function (picker, simulatedEvent) {
  6410. extractBlob(simulatedEvent).each(function (blob) {
  6411. addImage(editor, blob);
  6412. });
  6413. })
  6414. ])
  6415. });
  6416. return Button.sketch({
  6417. dom: Buttons.getToolbarIconButton('image', editor),
  6418. components: [memPicker.asSpec()],
  6419. action: function (button) {
  6420. var picker = memPicker.get(button);
  6421. picker.element().dom().click();
  6422. }
  6423. });
  6424. };
  6425. var get$9 = function (element) {
  6426. return element.dom().textContent;
  6427. };
  6428. var set$5 = function (element, value) {
  6429. element.dom().textContent = value;
  6430. };
  6431. var isNotEmpty = function (val) {
  6432. return val.length > 0;
  6433. };
  6434. var defaultToEmpty = function (str) {
  6435. return str === undefined || str === null ? '' : str;
  6436. };
  6437. var noLink = function (editor) {
  6438. var text = editor.selection.getContent({ format: 'text' });
  6439. return {
  6440. url: '',
  6441. text: text,
  6442. title: '',
  6443. target: '',
  6444. link: Option.none()
  6445. };
  6446. };
  6447. var fromLink = function (link) {
  6448. var text = get$9(link);
  6449. var url = get$1(link, 'href');
  6450. var title = get$1(link, 'title');
  6451. var target = get$1(link, 'target');
  6452. return {
  6453. url: defaultToEmpty(url),
  6454. text: text !== url ? defaultToEmpty(text) : '',
  6455. title: defaultToEmpty(title),
  6456. target: defaultToEmpty(target),
  6457. link: Option.some(link)
  6458. };
  6459. };
  6460. var getInfo = function (editor) {
  6461. return query(editor).fold(function () {
  6462. return noLink(editor);
  6463. }, function (link) {
  6464. return fromLink(link);
  6465. });
  6466. };
  6467. var wasSimple = function (link) {
  6468. var prevHref = get$1(link, 'href');
  6469. var prevText = get$9(link);
  6470. return prevHref === prevText;
  6471. };
  6472. var getTextToApply = function (link, url, info) {
  6473. return info.text.toOption().filter(isNotEmpty).fold(function () {
  6474. return wasSimple(link) ? Option.some(url) : Option.none();
  6475. }, Option.some);
  6476. };
  6477. var unlinkIfRequired = function (editor, info) {
  6478. var activeLink = info.link.bind(identity);
  6479. activeLink.each(function (link) {
  6480. editor.execCommand('unlink');
  6481. });
  6482. };
  6483. var getAttrs$1 = function (url, info) {
  6484. var attrs = {};
  6485. attrs.href = url;
  6486. info.title.toOption().filter(isNotEmpty).each(function (title) {
  6487. attrs.title = title;
  6488. });
  6489. info.target.toOption().filter(isNotEmpty).each(function (target) {
  6490. attrs.target = target;
  6491. });
  6492. return attrs;
  6493. };
  6494. var applyInfo = function (editor, info) {
  6495. info.url.toOption().filter(isNotEmpty).fold(function () {
  6496. unlinkIfRequired(editor, info);
  6497. }, function (url) {
  6498. var attrs = getAttrs$1(url, info);
  6499. var activeLink = info.link.bind(identity);
  6500. activeLink.fold(function () {
  6501. var text = info.text.toOption().filter(isNotEmpty).getOr(url);
  6502. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6503. }, function (link) {
  6504. var text = getTextToApply(link, url, info);
  6505. setAll(link, attrs);
  6506. text.each(function (newText) {
  6507. set$5(link, newText);
  6508. });
  6509. });
  6510. });
  6511. };
  6512. var query = function (editor) {
  6513. var start = Element.fromDom(editor.selection.getStart());
  6514. return closest$2(start, 'a');
  6515. };
  6516. var LinkBridge = {
  6517. getInfo: getInfo,
  6518. applyInfo: applyInfo,
  6519. query: query
  6520. };
  6521. var platform$1 = detect$3();
  6522. var preserve = function (f, editor) {
  6523. var rng = editor.selection.getRng();
  6524. f();
  6525. editor.selection.setRng(rng);
  6526. };
  6527. var forAndroid = function (editor, f) {
  6528. var wrapper = platform$1.os.isAndroid() ? preserve : apply;
  6529. wrapper(f, editor);
  6530. };
  6531. var RangePreserver = { forAndroid: forAndroid };
  6532. var events$6 = function (name, eventHandlers) {
  6533. var events = derive(eventHandlers);
  6534. return create$1({
  6535. fields: [strict$1('enabled')],
  6536. name: name,
  6537. active: { events: constant(events) }
  6538. });
  6539. };
  6540. var config = function (name, eventHandlers) {
  6541. var me = events$6(name, eventHandlers);
  6542. return {
  6543. key: name,
  6544. value: {
  6545. config: {},
  6546. me: me,
  6547. configAsRaw: constant({}),
  6548. initialConfig: {},
  6549. state: NoState
  6550. }
  6551. };
  6552. };
  6553. var getCurrent = function (component, composeConfig, composeState) {
  6554. return composeConfig.find(component);
  6555. };
  6556. var ComposeApis = /*#__PURE__*/Object.freeze({
  6557. __proto__: null,
  6558. getCurrent: getCurrent
  6559. });
  6560. var ComposeSchema = [strict$1('find')];
  6561. var Composing = create$1({
  6562. fields: ComposeSchema,
  6563. name: 'composing',
  6564. apis: ComposeApis
  6565. });
  6566. var factory$1 = function (detail) {
  6567. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6568. return {
  6569. uid: detail.uid,
  6570. dom: __assign({
  6571. tag: 'div',
  6572. attributes: __assign({ role: 'presentation' }, attributes)
  6573. }, domWithoutAttributes),
  6574. components: detail.components,
  6575. behaviours: get$6(detail.containerBehaviours),
  6576. events: detail.events,
  6577. domModification: detail.domModification,
  6578. eventOrder: detail.eventOrder
  6579. };
  6580. };
  6581. var Container = single$2({
  6582. name: 'Container',
  6583. factory: factory$1,
  6584. configFields: [
  6585. defaulted$1('components', []),
  6586. field$1('containerBehaviours', []),
  6587. defaulted$1('events', {}),
  6588. defaulted$1('domModification', {}),
  6589. defaulted$1('eventOrder', {})
  6590. ]
  6591. });
  6592. var factory$2 = function (detail) {
  6593. return {
  6594. uid: detail.uid,
  6595. dom: detail.dom,
  6596. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6597. Representing.config({
  6598. store: {
  6599. mode: 'memory',
  6600. initialValue: detail.getInitialValue()
  6601. }
  6602. }),
  6603. Composing.config({ find: Option.some })
  6604. ]),
  6605. events: derive([runOnAttached(function (component, simulatedEvent) {
  6606. Representing.setValue(component, detail.getInitialValue());
  6607. })])
  6608. };
  6609. };
  6610. var DataField = single$2({
  6611. name: 'DataField',
  6612. factory: factory$2,
  6613. configFields: [
  6614. strict$1('uid'),
  6615. strict$1('dom'),
  6616. strict$1('getInitialValue'),
  6617. SketchBehaviours.field('dataBehaviours', [
  6618. Representing,
  6619. Composing
  6620. ])
  6621. ]
  6622. });
  6623. var get$a = function (element) {
  6624. return element.dom().value;
  6625. };
  6626. var set$6 = function (element, value) {
  6627. if (value === undefined) {
  6628. throw new Error('Value.set was undefined');
  6629. }
  6630. element.dom().value = value;
  6631. };
  6632. var schema$8 = constant([
  6633. option('data'),
  6634. defaulted$1('inputAttributes', {}),
  6635. defaulted$1('inputStyles', {}),
  6636. defaulted$1('tag', 'input'),
  6637. defaulted$1('inputClasses', []),
  6638. onHandler('onSetValue'),
  6639. defaulted$1('styles', {}),
  6640. defaulted$1('eventOrder', {}),
  6641. field$1('inputBehaviours', [
  6642. Representing,
  6643. Focusing
  6644. ]),
  6645. defaulted$1('selectOnFocus', true)
  6646. ]);
  6647. var focusBehaviours = function (detail) {
  6648. return derive$1([Focusing.config({
  6649. onFocus: !detail.selectOnFocus ? noop : function (component) {
  6650. var input = component.element();
  6651. var value = get$a(input);
  6652. input.dom().setSelectionRange(0, value.length);
  6653. }
  6654. })]);
  6655. };
  6656. var behaviours = function (detail) {
  6657. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6658. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  6659. return { initialValue: data };
  6660. }).getOr({})), {
  6661. getValue: function (input) {
  6662. return get$a(input.element());
  6663. },
  6664. setValue: function (input, data) {
  6665. var current = get$a(input.element());
  6666. if (current !== data) {
  6667. set$6(input.element(), data);
  6668. }
  6669. }
  6670. }),
  6671. onSetValue: detail.onSetValue
  6672. })]));
  6673. };
  6674. var dom$2 = function (detail) {
  6675. return {
  6676. tag: detail.tag,
  6677. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6678. styles: detail.inputStyles,
  6679. classes: detail.inputClasses
  6680. };
  6681. };
  6682. var factory$3 = function (detail, spec) {
  6683. return {
  6684. uid: detail.uid,
  6685. dom: dom$2(detail),
  6686. components: [],
  6687. behaviours: behaviours(detail),
  6688. eventOrder: detail.eventOrder
  6689. };
  6690. };
  6691. var Input = single$2({
  6692. name: 'Input',
  6693. configFields: schema$8(),
  6694. factory: factory$3
  6695. });
  6696. var exhibit$3 = function (base, tabConfig) {
  6697. return nu$5({
  6698. attributes: wrapAll$1([{
  6699. key: tabConfig.tabAttr,
  6700. value: 'true'
  6701. }])
  6702. });
  6703. };
  6704. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6705. __proto__: null,
  6706. exhibit: exhibit$3
  6707. });
  6708. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  6709. var Tabstopping = create$1({
  6710. fields: TabstopSchema,
  6711. name: 'tabstopping',
  6712. active: ActiveTabstopping
  6713. });
  6714. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6715. var clearInputBehaviour = 'input-clearing';
  6716. var field$2 = function (name, placeholder) {
  6717. var inputSpec = record(Input.sketch({
  6718. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6719. onSetValue: function (input$1, data) {
  6720. emit(input$1, input());
  6721. },
  6722. inputBehaviours: derive$1([
  6723. Composing.config({ find: Option.some }),
  6724. Tabstopping.config({}),
  6725. Keying.config({ mode: 'execution' })
  6726. ]),
  6727. selectOnFocus: false
  6728. }));
  6729. var buttonSpec = record(Button.sketch({
  6730. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6731. action: function (button) {
  6732. var input = inputSpec.get(button);
  6733. Representing.setValue(input, '');
  6734. }
  6735. }));
  6736. return {
  6737. name: name,
  6738. spec: Container.sketch({
  6739. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6740. components: [
  6741. inputSpec.asSpec(),
  6742. buttonSpec.asSpec()
  6743. ],
  6744. containerBehaviours: derive$1([
  6745. Toggling.config({ toggleClass: Styles.resolve('input-container-empty') }),
  6746. Composing.config({
  6747. find: function (comp) {
  6748. return Option.some(inputSpec.get(comp));
  6749. }
  6750. }),
  6751. config(clearInputBehaviour, [run(input(), function (iContainer) {
  6752. var input = inputSpec.get(iContainer);
  6753. var val = Representing.getValue(input);
  6754. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6755. f(iContainer);
  6756. })])
  6757. ])
  6758. })
  6759. };
  6760. };
  6761. var hidden = function (name) {
  6762. return {
  6763. name: name,
  6764. spec: DataField.sketch({
  6765. dom: {
  6766. tag: 'span',
  6767. styles: { display: 'none' }
  6768. },
  6769. getInitialValue: function () {
  6770. return Option.none();
  6771. }
  6772. })
  6773. };
  6774. };
  6775. var nativeDisabled = [
  6776. 'input',
  6777. 'button',
  6778. 'textarea',
  6779. 'select'
  6780. ];
  6781. var onLoad$5 = function (component, disableConfig, disableState) {
  6782. if (disableConfig.disabled) {
  6783. disable(component, disableConfig);
  6784. }
  6785. };
  6786. var hasNative = function (component, config) {
  6787. return config.useNative === true && contains(nativeDisabled, name(component.element()));
  6788. };
  6789. var nativeIsDisabled = function (component) {
  6790. return has$1(component.element(), 'disabled');
  6791. };
  6792. var nativeDisable = function (component) {
  6793. set(component.element(), 'disabled', 'disabled');
  6794. };
  6795. var nativeEnable = function (component) {
  6796. remove$1(component.element(), 'disabled');
  6797. };
  6798. var ariaIsDisabled = function (component) {
  6799. return get$1(component.element(), 'aria-disabled') === 'true';
  6800. };
  6801. var ariaDisable = function (component) {
  6802. set(component.element(), 'aria-disabled', 'true');
  6803. };
  6804. var ariaEnable = function (component) {
  6805. set(component.element(), 'aria-disabled', 'false');
  6806. };
  6807. var disable = function (component, disableConfig, disableState) {
  6808. disableConfig.disableClass.each(function (disableClass) {
  6809. add$2(component.element(), disableClass);
  6810. });
  6811. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6812. f(component);
  6813. disableConfig.onDisabled(component);
  6814. };
  6815. var enable = function (component, disableConfig, disableState) {
  6816. disableConfig.disableClass.each(function (disableClass) {
  6817. remove$4(component.element(), disableClass);
  6818. });
  6819. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6820. f(component);
  6821. disableConfig.onEnabled(component);
  6822. };
  6823. var isDisabled = function (component, disableConfig) {
  6824. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6825. };
  6826. var set$7 = function (component, disableConfig, disableState, disabled) {
  6827. var f = disabled ? disable : enable;
  6828. f(component, disableConfig, disableState);
  6829. };
  6830. var DisableApis = /*#__PURE__*/Object.freeze({
  6831. __proto__: null,
  6832. enable: enable,
  6833. disable: disable,
  6834. isDisabled: isDisabled,
  6835. onLoad: onLoad$5,
  6836. set: set$7
  6837. });
  6838. var exhibit$4 = function (base, disableConfig) {
  6839. return nu$5({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  6840. };
  6841. var events$7 = function (disableConfig, disableState) {
  6842. return derive([
  6843. abort(execute(), function (component, simulatedEvent) {
  6844. return isDisabled(component, disableConfig);
  6845. }),
  6846. loadEvent(disableConfig, disableState, onLoad$5)
  6847. ]);
  6848. };
  6849. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6850. __proto__: null,
  6851. exhibit: exhibit$4,
  6852. events: events$7
  6853. });
  6854. var DisableSchema = [
  6855. defaulted$1('disabled', false),
  6856. defaulted$1('useNative', true),
  6857. option('disableClass'),
  6858. onHandler('onDisabled'),
  6859. onHandler('onEnabled')
  6860. ];
  6861. var Disabling = create$1({
  6862. fields: DisableSchema,
  6863. name: 'disabling',
  6864. active: ActiveDisable,
  6865. apis: DisableApis
  6866. });
  6867. var owner$1 = 'form';
  6868. var schema$9 = [field$1('formBehaviours', [Representing])];
  6869. var getPartName = function (name) {
  6870. return '<alloy.field.' + name + '>';
  6871. };
  6872. var sketch$5 = function (fSpec) {
  6873. var parts = function () {
  6874. var record = [];
  6875. var field = function (name, config) {
  6876. record.push(name);
  6877. return generateOne(owner$1, getPartName(name), config);
  6878. };
  6879. return {
  6880. field: field,
  6881. record: function () {
  6882. return record;
  6883. }
  6884. };
  6885. }();
  6886. var spec = fSpec(parts);
  6887. var partNames = parts.record();
  6888. var fieldParts = map$1(partNames, function (n) {
  6889. return required({
  6890. name: n,
  6891. pname: getPartName(n)
  6892. });
  6893. });
  6894. return composite(owner$1, schema$9, fieldParts, make, spec);
  6895. };
  6896. var toResult$1 = function (o, e) {
  6897. return o.fold(function () {
  6898. return Result.error(e);
  6899. }, Result.value);
  6900. };
  6901. var make = function (detail, components) {
  6902. return {
  6903. uid: detail.uid,
  6904. dom: detail.dom,
  6905. components: components,
  6906. behaviours: augment(detail.formBehaviours, [Representing.config({
  6907. store: {
  6908. mode: 'manual',
  6909. getValue: function (form) {
  6910. var resPs = getAllParts(form, detail);
  6911. return map(resPs, function (resPThunk, pName) {
  6912. return resPThunk().bind(function (v) {
  6913. var opt = Composing.getCurrent(v);
  6914. return toResult$1(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element())));
  6915. }).map(Representing.getValue);
  6916. });
  6917. },
  6918. setValue: function (form, values) {
  6919. each(values, function (newValue, key) {
  6920. getPart(form, detail, key).each(function (wrapper) {
  6921. Composing.getCurrent(wrapper).each(function (field) {
  6922. Representing.setValue(field, newValue);
  6923. });
  6924. });
  6925. });
  6926. }
  6927. }
  6928. })]),
  6929. apis: {
  6930. getField: function (form, key) {
  6931. return getPart(form, detail, key).bind(Composing.getCurrent);
  6932. }
  6933. }
  6934. };
  6935. };
  6936. var Form = {
  6937. getField: makeApi(function (apis, component, key) {
  6938. return apis.getField(component, key);
  6939. }),
  6940. sketch: sketch$5
  6941. };
  6942. var api$2 = function () {
  6943. var subject = Cell(Option.none());
  6944. var revoke = function () {
  6945. subject.get().each(function (s) {
  6946. s.destroy();
  6947. });
  6948. };
  6949. var clear = function () {
  6950. revoke();
  6951. subject.set(Option.none());
  6952. };
  6953. var set = function (s) {
  6954. revoke();
  6955. subject.set(Option.some(s));
  6956. };
  6957. var run = function (f) {
  6958. subject.get().each(f);
  6959. };
  6960. var isSet = function () {
  6961. return subject.get().isSome();
  6962. };
  6963. return {
  6964. clear: clear,
  6965. isSet: isSet,
  6966. set: set,
  6967. run: run
  6968. };
  6969. };
  6970. var value$2 = function () {
  6971. var subject = Cell(Option.none());
  6972. var clear = function () {
  6973. subject.set(Option.none());
  6974. };
  6975. var set = function (s) {
  6976. subject.set(Option.some(s));
  6977. };
  6978. var on = function (f) {
  6979. subject.get().each(f);
  6980. };
  6981. var isSet = function () {
  6982. return subject.get().isSome();
  6983. };
  6984. return {
  6985. clear: clear,
  6986. set: set,
  6987. isSet: isSet,
  6988. on: on
  6989. };
  6990. };
  6991. var SWIPING_LEFT = 1;
  6992. var SWIPING_RIGHT = -1;
  6993. var SWIPING_NONE = 0;
  6994. var init$2 = function (xValue) {
  6995. return {
  6996. xValue: xValue,
  6997. points: []
  6998. };
  6999. };
  7000. var move$1 = function (model, xValue) {
  7001. if (xValue === model.xValue) {
  7002. return model;
  7003. }
  7004. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7005. var newPoint = {
  7006. direction: currentDirection,
  7007. xValue: xValue
  7008. };
  7009. var priorPoints = function () {
  7010. if (model.points.length === 0) {
  7011. return [];
  7012. } else {
  7013. var prev = model.points[model.points.length - 1];
  7014. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7015. }
  7016. }();
  7017. return {
  7018. xValue: xValue,
  7019. points: priorPoints.concat([newPoint])
  7020. };
  7021. };
  7022. var complete = function (model) {
  7023. if (model.points.length === 0) {
  7024. return SWIPING_NONE;
  7025. } else {
  7026. var firstDirection = model.points[0].direction;
  7027. var lastDirection = model.points[model.points.length - 1].direction;
  7028. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7029. }
  7030. };
  7031. var SwipingModel = {
  7032. init: init$2,
  7033. move: move$1,
  7034. complete: complete
  7035. };
  7036. var sketch$6 = function (rawSpec) {
  7037. var navigateEvent = 'navigateEvent';
  7038. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7039. var formAdhocEvents = 'form-events';
  7040. var schema = objOf([
  7041. strict$1('fields'),
  7042. defaulted$1('maxFieldIndex', rawSpec.fields.length - 1),
  7043. strict$1('onExecute'),
  7044. strict$1('getInitialValue'),
  7045. state$1('state', function () {
  7046. return {
  7047. dialogSwipeState: value$2(),
  7048. currentScreen: Cell(0)
  7049. };
  7050. })
  7051. ]);
  7052. var spec$1 = asRawOrDie('SerialisedDialog', schema, rawSpec);
  7053. var navigationButton = function (direction, directionName, enabled) {
  7054. return Button.sketch({
  7055. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7056. action: function (button) {
  7057. emitWith(button, navigateEvent, { direction: direction });
  7058. },
  7059. buttonBehaviours: derive$1([Disabling.config({
  7060. disableClass: Styles.resolve('toolbar-navigation-disabled'),
  7061. disabled: !enabled
  7062. })])
  7063. });
  7064. };
  7065. var reposition = function (dialog, message) {
  7066. descendant$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
  7067. set$3(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  7068. });
  7069. };
  7070. var navigate = function (dialog, direction) {
  7071. var screens = descendants(dialog.element(), '.' + Styles.resolve('serialised-dialog-screen'));
  7072. descendant$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
  7073. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  7074. getRaw(parent, 'left').each(function (left) {
  7075. var currentLeft = parseInt(left, 10);
  7076. var w = get$7(screens[0]);
  7077. set$3(parent, 'left', currentLeft - direction * w + 'px');
  7078. });
  7079. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  7080. }
  7081. });
  7082. };
  7083. var focusInput = function (dialog) {
  7084. var inputs = descendants(dialog.element(), 'input');
  7085. var optInput = Option.from(inputs[spec$1.state.currentScreen.get()]);
  7086. optInput.each(function (input) {
  7087. dialog.getSystem().getByDom(input).each(function (inputComp) {
  7088. dispatchFocus(dialog, inputComp.element());
  7089. });
  7090. });
  7091. var dotitems = memDots.get(dialog);
  7092. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  7093. };
  7094. var resetState = function () {
  7095. spec$1.state.currentScreen.set(0);
  7096. spec$1.state.dialogSwipeState.clear();
  7097. };
  7098. var memForm = record(Form.sketch(function (parts) {
  7099. return {
  7100. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  7101. components: [Container.sketch({
  7102. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  7103. components: map$1(spec$1.fields, function (field, i) {
  7104. return i <= spec$1.maxFieldIndex ? Container.sketch({
  7105. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  7106. components: [
  7107. navigationButton(-1, 'previous', i > 0),
  7108. parts.field(field.name, field.spec),
  7109. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  7110. ]
  7111. }) : parts.field(field.name, field.spec);
  7112. })
  7113. })],
  7114. formBehaviours: derive$1([
  7115. Receivers.orientation(function (dialog, message) {
  7116. reposition(dialog, message);
  7117. }),
  7118. Keying.config({
  7119. mode: 'special',
  7120. focusIn: function (dialog) {
  7121. focusInput(dialog);
  7122. },
  7123. onTab: function (dialog) {
  7124. navigate(dialog, +1);
  7125. return Option.some(true);
  7126. },
  7127. onShiftTab: function (dialog) {
  7128. navigate(dialog, -1);
  7129. return Option.some(true);
  7130. }
  7131. }),
  7132. config(formAdhocEvents, [
  7133. runOnAttached(function (dialog, simulatedEvent) {
  7134. resetState();
  7135. var dotitems = memDots.get(dialog);
  7136. Highlighting.highlightFirst(dotitems);
  7137. spec$1.getInitialValue(dialog).each(function (v) {
  7138. Representing.setValue(dialog, v);
  7139. });
  7140. }),
  7141. runOnExecute(spec$1.onExecute),
  7142. run(transitionend(), function (dialog, simulatedEvent) {
  7143. var event = simulatedEvent.event();
  7144. if (event.raw().propertyName === 'left') {
  7145. focusInput(dialog);
  7146. }
  7147. }),
  7148. run(navigateEvent, function (dialog, simulatedEvent) {
  7149. var event = simulatedEvent.event();
  7150. var direction = event.direction();
  7151. navigate(dialog, direction);
  7152. })
  7153. ])
  7154. ])
  7155. };
  7156. }));
  7157. var memDots = record({
  7158. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7159. behaviours: derive$1([Highlighting.config({
  7160. highlightClass: Styles.resolve('dot-active'),
  7161. itemClass: Styles.resolve('dot-item')
  7162. })]),
  7163. components: bind(spec$1.fields, function (_f, i) {
  7164. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7165. })
  7166. });
  7167. return {
  7168. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7169. components: [
  7170. memForm.asSpec(),
  7171. memDots.asSpec()
  7172. ],
  7173. behaviours: derive$1([
  7174. Keying.config({
  7175. mode: 'special',
  7176. focusIn: function (wrapper) {
  7177. var form = memForm.get(wrapper);
  7178. Keying.focusIn(form);
  7179. }
  7180. }),
  7181. config(wrapperAdhocEvents, [
  7182. run(touchstart(), function (wrapper, simulatedEvent) {
  7183. var event = simulatedEvent.event();
  7184. spec$1.state.dialogSwipeState.set(SwipingModel.init(event.raw().touches[0].clientX));
  7185. }),
  7186. run(touchmove(), function (wrapper, simulatedEvent) {
  7187. var event = simulatedEvent.event();
  7188. spec$1.state.dialogSwipeState.on(function (state) {
  7189. simulatedEvent.event().prevent();
  7190. spec$1.state.dialogSwipeState.set(SwipingModel.move(state, event.raw().touches[0].clientX));
  7191. });
  7192. }),
  7193. run(touchend(), function (wrapper) {
  7194. spec$1.state.dialogSwipeState.on(function (state) {
  7195. var dialog = memForm.get(wrapper);
  7196. var direction = -1 * SwipingModel.complete(state);
  7197. navigate(dialog, direction);
  7198. });
  7199. })
  7200. ])
  7201. ])
  7202. };
  7203. };
  7204. var getGroups = cached(function (realm, editor) {
  7205. return [{
  7206. label: 'the link group',
  7207. items: [sketch$6({
  7208. fields: [
  7209. field$2('url', 'Type or paste URL'),
  7210. field$2('text', 'Link text'),
  7211. field$2('title', 'Link title'),
  7212. field$2('target', 'Link target'),
  7213. hidden('link')
  7214. ],
  7215. maxFieldIndex: [
  7216. 'url',
  7217. 'text',
  7218. 'title',
  7219. 'target'
  7220. ].length - 1,
  7221. getInitialValue: function () {
  7222. return Option.some(LinkBridge.getInfo(editor));
  7223. },
  7224. onExecute: function (dialog) {
  7225. var info = Representing.getValue(dialog);
  7226. LinkBridge.applyInfo(editor, info);
  7227. realm.restoreToolbar();
  7228. editor.focus();
  7229. }
  7230. })]
  7231. }];
  7232. });
  7233. var sketch$7 = function (realm, editor) {
  7234. return Buttons.forToolbarStateAction(editor, 'link', 'link', function () {
  7235. var groups = getGroups(realm, editor);
  7236. realm.setContextToolbar(groups);
  7237. RangePreserver.forAndroid(editor, function () {
  7238. realm.focusToolbar();
  7239. });
  7240. LinkBridge.query(editor).each(function (link) {
  7241. editor.selection.select(link.dom());
  7242. });
  7243. });
  7244. };
  7245. var DefaultStyleFormats = [
  7246. {
  7247. title: 'Headings',
  7248. items: [
  7249. {
  7250. title: 'Heading 1',
  7251. format: 'h1'
  7252. },
  7253. {
  7254. title: 'Heading 2',
  7255. format: 'h2'
  7256. },
  7257. {
  7258. title: 'Heading 3',
  7259. format: 'h3'
  7260. },
  7261. {
  7262. title: 'Heading 4',
  7263. format: 'h4'
  7264. },
  7265. {
  7266. title: 'Heading 5',
  7267. format: 'h5'
  7268. },
  7269. {
  7270. title: 'Heading 6',
  7271. format: 'h6'
  7272. }
  7273. ]
  7274. },
  7275. {
  7276. title: 'Inline',
  7277. items: [
  7278. {
  7279. title: 'Bold',
  7280. icon: 'bold',
  7281. format: 'bold'
  7282. },
  7283. {
  7284. title: 'Italic',
  7285. icon: 'italic',
  7286. format: 'italic'
  7287. },
  7288. {
  7289. title: 'Underline',
  7290. icon: 'underline',
  7291. format: 'underline'
  7292. },
  7293. {
  7294. title: 'Strikethrough',
  7295. icon: 'strikethrough',
  7296. format: 'strikethrough'
  7297. },
  7298. {
  7299. title: 'Superscript',
  7300. icon: 'superscript',
  7301. format: 'superscript'
  7302. },
  7303. {
  7304. title: 'Subscript',
  7305. icon: 'subscript',
  7306. format: 'subscript'
  7307. },
  7308. {
  7309. title: 'Code',
  7310. icon: 'code',
  7311. format: 'code'
  7312. }
  7313. ]
  7314. },
  7315. {
  7316. title: 'Blocks',
  7317. items: [
  7318. {
  7319. title: 'Paragraph',
  7320. format: 'p'
  7321. },
  7322. {
  7323. title: 'Blockquote',
  7324. format: 'blockquote'
  7325. },
  7326. {
  7327. title: 'Div',
  7328. format: 'div'
  7329. },
  7330. {
  7331. title: 'Pre',
  7332. format: 'pre'
  7333. }
  7334. ]
  7335. },
  7336. {
  7337. title: 'Alignment',
  7338. items: [
  7339. {
  7340. title: 'Left',
  7341. icon: 'alignleft',
  7342. format: 'alignleft'
  7343. },
  7344. {
  7345. title: 'Center',
  7346. icon: 'aligncenter',
  7347. format: 'aligncenter'
  7348. },
  7349. {
  7350. title: 'Right',
  7351. icon: 'alignright',
  7352. format: 'alignright'
  7353. },
  7354. {
  7355. title: 'Justify',
  7356. icon: 'alignjustify',
  7357. format: 'alignjustify'
  7358. }
  7359. ]
  7360. }
  7361. ];
  7362. var isRecursive = function (component, originator, target) {
  7363. return eq(originator, component.element()) && !eq(originator, target);
  7364. };
  7365. var events$8 = derive([can(focus(), function (component, simulatedEvent) {
  7366. var originator = simulatedEvent.event().originator();
  7367. var target = simulatedEvent.event().target();
  7368. if (isRecursive(component, originator, target)) {
  7369. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  7370. return false;
  7371. } else {
  7372. return true;
  7373. }
  7374. })]);
  7375. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7376. __proto__: null,
  7377. events: events$8
  7378. });
  7379. var make$1 = identity;
  7380. var NoContextApi = function (getComp) {
  7381. var fail = function (event) {
  7382. return function () {
  7383. throw new Error('The component must be in a context to send: ' + event + (getComp ? '\n' + element(getComp().element()) + ' is not in context.' : ''));
  7384. };
  7385. };
  7386. return {
  7387. debugInfo: constant('fake'),
  7388. triggerEvent: fail('triggerEvent'),
  7389. triggerFocus: fail('triggerFocus'),
  7390. triggerEscape: fail('triggerEscape'),
  7391. build: fail('build'),
  7392. addToWorld: fail('addToWorld'),
  7393. removeFromWorld: fail('removeFromWorld'),
  7394. addToGui: fail('addToGui'),
  7395. removeFromGui: fail('removeFromGui'),
  7396. getByUid: fail('getByUid'),
  7397. getByDom: fail('getByDom'),
  7398. broadcast: fail('broadcast'),
  7399. broadcastOn: fail('broadcastOn'),
  7400. broadcastEvent: fail('broadcastEvent'),
  7401. isConnected: constant(false)
  7402. };
  7403. };
  7404. var singleton = NoContextApi();
  7405. var generateFrom = function (spec, all) {
  7406. var schema = map$1(all, function (a) {
  7407. return optionObjOf(a.name(), [
  7408. strict$1('config'),
  7409. defaulted$1('state', NoState)
  7410. ]);
  7411. });
  7412. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7413. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7414. }, function (v) {
  7415. return v;
  7416. });
  7417. return {
  7418. list: all,
  7419. data: map(validated, function (optBlobThunk) {
  7420. var output = optBlobThunk.map(function (blob) {
  7421. return {
  7422. config: blob.config,
  7423. state: blob.state.init(blob.config)
  7424. };
  7425. });
  7426. return function () {
  7427. return output;
  7428. };
  7429. })
  7430. };
  7431. };
  7432. var getBehaviours = function (bData) {
  7433. return bData.list;
  7434. };
  7435. var getData = function (bData) {
  7436. return bData.data;
  7437. };
  7438. var byInnerKey = function (data, tuple) {
  7439. var r = {};
  7440. each(data, function (detail, key) {
  7441. each(detail, function (value, indexKey) {
  7442. var chain = get(r, indexKey).getOr([]);
  7443. r[indexKey] = chain.concat([tuple(key, value)]);
  7444. });
  7445. });
  7446. return r;
  7447. };
  7448. var combine$1 = function (info, baseMod, behaviours, base) {
  7449. var modsByBehaviour = __assign({}, baseMod);
  7450. each$1(behaviours, function (behaviour) {
  7451. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7452. });
  7453. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  7454. return {
  7455. name: name,
  7456. modification: modification
  7457. };
  7458. });
  7459. var combineObjects = function (objects) {
  7460. return foldr(objects, function (b, a) {
  7461. return __assign(__assign({}, a.modification), b);
  7462. }, {});
  7463. };
  7464. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7465. return a.modification.concat(b);
  7466. }, []);
  7467. var combinedAttributes = combineObjects(byAspect.attributes);
  7468. var combinedStyles = combineObjects(byAspect.styles);
  7469. return nu$5({
  7470. classes: combinedClasses,
  7471. attributes: combinedAttributes,
  7472. styles: combinedStyles
  7473. });
  7474. };
  7475. var sortKeys = function (label, keyName, array, order) {
  7476. try {
  7477. var sorted = sort(array, function (a, b) {
  7478. var aKey = a[keyName]();
  7479. var bKey = b[keyName]();
  7480. var aIndex = order.indexOf(aKey);
  7481. var bIndex = order.indexOf(bKey);
  7482. if (aIndex === -1) {
  7483. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7484. }
  7485. if (bIndex === -1) {
  7486. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7487. }
  7488. if (aIndex < bIndex) {
  7489. return -1;
  7490. } else if (bIndex < aIndex) {
  7491. return 1;
  7492. } else {
  7493. return 0;
  7494. }
  7495. });
  7496. return Result.value(sorted);
  7497. } catch (err) {
  7498. return Result.error([err]);
  7499. }
  7500. };
  7501. var uncurried = function (handler, purpose) {
  7502. return {
  7503. handler: handler,
  7504. purpose: constant(purpose)
  7505. };
  7506. };
  7507. var curried = function (handler, purpose) {
  7508. return {
  7509. cHandler: handler,
  7510. purpose: constant(purpose)
  7511. };
  7512. };
  7513. var curryArgs = function (descHandler, extraArgs) {
  7514. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  7515. };
  7516. var getCurried = function (descHandler) {
  7517. return descHandler.cHandler;
  7518. };
  7519. var behaviourTuple = function (name, handler) {
  7520. return {
  7521. name: constant(name),
  7522. handler: constant(handler)
  7523. };
  7524. };
  7525. var nameToHandlers = function (behaviours, info) {
  7526. var r = {};
  7527. each$1(behaviours, function (behaviour) {
  7528. r[behaviour.name()] = behaviour.handlers(info);
  7529. });
  7530. return r;
  7531. };
  7532. var groupByEvents = function (info, behaviours, base) {
  7533. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7534. return byInnerKey(behaviourEvents, behaviourTuple);
  7535. };
  7536. var combine$2 = function (info, eventOrder, behaviours, base) {
  7537. var byEventName = groupByEvents(info, behaviours, base);
  7538. return combineGroups(byEventName, eventOrder);
  7539. };
  7540. var assemble = function (rawHandler) {
  7541. var handler = read(rawHandler);
  7542. return function (component, simulatedEvent) {
  7543. var rest = [];
  7544. for (var _i = 2; _i < arguments.length; _i++) {
  7545. rest[_i - 2] = arguments[_i];
  7546. }
  7547. var args = [
  7548. component,
  7549. simulatedEvent
  7550. ].concat(rest);
  7551. if (handler.abort.apply(undefined, args)) {
  7552. simulatedEvent.stop();
  7553. } else if (handler.can.apply(undefined, args)) {
  7554. handler.run.apply(undefined, args);
  7555. }
  7556. };
  7557. };
  7558. var missingOrderError = function (eventName, tuples) {
  7559. 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$1(tuples, function (c) {
  7560. return c.name();
  7561. }), null, 2)]);
  7562. };
  7563. var fuse$1 = function (tuples, eventOrder, eventName) {
  7564. var order = eventOrder[eventName];
  7565. if (!order) {
  7566. return missingOrderError(eventName, tuples);
  7567. } else {
  7568. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7569. var handlers = map$1(sortedTuples, function (tuple) {
  7570. return tuple.handler();
  7571. });
  7572. return fuse(handlers);
  7573. });
  7574. }
  7575. };
  7576. var combineGroups = function (byEventName, eventOrder) {
  7577. var r = mapToArray(byEventName, function (tuples, eventName) {
  7578. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  7579. return combined.map(function (handler) {
  7580. var assembled = assemble(handler);
  7581. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  7582. return exists(tuples, function (t) {
  7583. return t.name() === o;
  7584. });
  7585. }).join(' > ') : tuples[0].name();
  7586. return wrap$1(eventName, uncurried(assembled, purpose));
  7587. });
  7588. });
  7589. return consolidate(r, {});
  7590. };
  7591. var toInfo = function (spec) {
  7592. return asRaw('custom.definition', objOf([
  7593. field('dom', 'dom', strict(), objOf([
  7594. strict$1('tag'),
  7595. defaulted$1('styles', {}),
  7596. defaulted$1('classes', []),
  7597. defaulted$1('attributes', {}),
  7598. option('value'),
  7599. option('innerHtml')
  7600. ])),
  7601. strict$1('components'),
  7602. strict$1('uid'),
  7603. defaulted$1('events', {}),
  7604. defaulted$1('apis', {}),
  7605. field('eventOrder', 'eventOrder', mergeWith({
  7606. 'alloy.execute': [
  7607. 'disabling',
  7608. 'alloy.base.behaviour',
  7609. 'toggling',
  7610. 'typeaheadevents'
  7611. ],
  7612. 'alloy.focus': [
  7613. 'alloy.base.behaviour',
  7614. 'focusing',
  7615. 'keying'
  7616. ],
  7617. 'alloy.system.init': [
  7618. 'alloy.base.behaviour',
  7619. 'disabling',
  7620. 'toggling',
  7621. 'representing'
  7622. ],
  7623. 'input': [
  7624. 'alloy.base.behaviour',
  7625. 'representing',
  7626. 'streaming',
  7627. 'invalidating'
  7628. ],
  7629. 'alloy.system.detached': [
  7630. 'alloy.base.behaviour',
  7631. 'representing',
  7632. 'item-events',
  7633. 'tooltipping'
  7634. ],
  7635. 'mousedown': [
  7636. 'focusing',
  7637. 'alloy.base.behaviour',
  7638. 'item-type-events'
  7639. ],
  7640. 'touchstart': [
  7641. 'focusing',
  7642. 'alloy.base.behaviour',
  7643. 'item-type-events'
  7644. ],
  7645. 'mouseover': [
  7646. 'item-type-events',
  7647. 'tooltipping'
  7648. ]
  7649. }), anyValue$1()),
  7650. option('domModification')
  7651. ]), spec);
  7652. };
  7653. var toDefinition = function (detail) {
  7654. return __assign(__assign({}, detail.dom), {
  7655. uid: detail.uid,
  7656. domChildren: map$1(detail.components, function (comp) {
  7657. return comp.element();
  7658. })
  7659. });
  7660. };
  7661. var toModification = function (detail) {
  7662. return detail.domModification.fold(function () {
  7663. return nu$5({});
  7664. }, nu$5);
  7665. };
  7666. var toEvents = function (info) {
  7667. return info.events;
  7668. };
  7669. var add$3 = function (element, classes) {
  7670. each$1(classes, function (x) {
  7671. add$2(element, x);
  7672. });
  7673. };
  7674. var remove$6 = function (element, classes) {
  7675. each$1(classes, function (x) {
  7676. remove$4(element, x);
  7677. });
  7678. };
  7679. var renderToDom = function (definition) {
  7680. var subject = Element.fromTag(definition.tag);
  7681. setAll(subject, definition.attributes);
  7682. add$3(subject, definition.classes);
  7683. setAll$1(subject, definition.styles);
  7684. definition.innerHtml.each(function (html) {
  7685. return set$1(subject, html);
  7686. });
  7687. var children = definition.domChildren;
  7688. append$1(subject, children);
  7689. definition.value.each(function (value) {
  7690. set$6(subject, value);
  7691. });
  7692. if (!definition.uid) {
  7693. debugger;
  7694. }
  7695. writeOnly(subject, definition.uid);
  7696. return subject;
  7697. };
  7698. var getBehaviours$1 = function (spec) {
  7699. var behaviours = get(spec, 'behaviours').getOr({});
  7700. var keys$1 = filter(keys(behaviours), function (k) {
  7701. return behaviours[k] !== undefined;
  7702. });
  7703. return map$1(keys$1, function (k) {
  7704. return behaviours[k].me;
  7705. });
  7706. };
  7707. var generateFrom$1 = function (spec, all) {
  7708. return generateFrom(spec, all);
  7709. };
  7710. var generate$4 = function (spec) {
  7711. var all = getBehaviours$1(spec);
  7712. return generateFrom$1(spec, all);
  7713. };
  7714. var getDomDefinition = function (info, bList, bData) {
  7715. var definition = toDefinition(info);
  7716. var infoModification = toModification(info);
  7717. var baseModification = { 'alloy.base.modification': infoModification };
  7718. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7719. return merge$1(definition, modification);
  7720. };
  7721. var getEvents = function (info, bList, bData) {
  7722. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7723. return combine$2(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7724. };
  7725. var build = function (spec) {
  7726. var getMe = function () {
  7727. return me;
  7728. };
  7729. var systemApi = Cell(singleton);
  7730. var info = getOrDie(toInfo(spec));
  7731. var bBlob = generate$4(spec);
  7732. var bList = getBehaviours(bBlob);
  7733. var bData = getData(bBlob);
  7734. var modDefinition = getDomDefinition(info, bList, bData);
  7735. var item = renderToDom(modDefinition);
  7736. var events = getEvents(info, bList, bData);
  7737. var subcomponents = Cell(info.components);
  7738. var connect = function (newApi) {
  7739. systemApi.set(newApi);
  7740. };
  7741. var disconnect = function () {
  7742. systemApi.set(NoContextApi(getMe));
  7743. };
  7744. var syncComponents = function () {
  7745. var children$1 = children(item);
  7746. var subs = bind(children$1, function (child) {
  7747. return systemApi.get().getByDom(child).fold(function () {
  7748. return [];
  7749. }, function (c) {
  7750. return [c];
  7751. });
  7752. });
  7753. subcomponents.set(subs);
  7754. };
  7755. var config = function (behaviour) {
  7756. var b = bData;
  7757. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7758. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7759. };
  7760. return f();
  7761. };
  7762. var hasConfigured = function (behaviour) {
  7763. return isFunction(bData[behaviour.name()]);
  7764. };
  7765. var getApis = function () {
  7766. return info.apis;
  7767. };
  7768. var readState = function (behaviourName) {
  7769. return bData[behaviourName]().map(function (b) {
  7770. return b.state.readState();
  7771. }).getOr('not enabled');
  7772. };
  7773. var me = {
  7774. getSystem: systemApi.get,
  7775. config: config,
  7776. hasConfigured: hasConfigured,
  7777. spec: constant(spec),
  7778. readState: readState,
  7779. getApis: getApis,
  7780. connect: connect,
  7781. disconnect: disconnect,
  7782. element: constant(item),
  7783. syncComponents: syncComponents,
  7784. components: subcomponents.get,
  7785. events: constant(events)
  7786. };
  7787. return me;
  7788. };
  7789. var buildSubcomponents = function (spec) {
  7790. var components = get(spec, 'components').getOr([]);
  7791. return map$1(components, build$1);
  7792. };
  7793. var buildFromSpec = function (userSpec) {
  7794. var _a = make$1(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7795. var components = buildSubcomponents(spec);
  7796. var completeSpec = __assign(__assign({}, spec), {
  7797. events: __assign(__assign({}, DefaultEvents), specEvents),
  7798. components: components
  7799. });
  7800. return Result.value(build(completeSpec));
  7801. };
  7802. var text = function (textContent) {
  7803. var element = Element.fromText(textContent);
  7804. return external$1({ element: element });
  7805. };
  7806. var external$1 = function (spec) {
  7807. var extSpec = asRawOrDie('external.component', objOfOnly([
  7808. strict$1('element'),
  7809. option('uid')
  7810. ]), spec);
  7811. var systemApi = Cell(NoContextApi());
  7812. var connect = function (newApi) {
  7813. systemApi.set(newApi);
  7814. };
  7815. var disconnect = function () {
  7816. systemApi.set(NoContextApi(function () {
  7817. return me;
  7818. }));
  7819. };
  7820. extSpec.uid.each(function (uid) {
  7821. writeOnly(extSpec.element, uid);
  7822. });
  7823. var me = {
  7824. getSystem: systemApi.get,
  7825. config: Option.none,
  7826. hasConfigured: constant(false),
  7827. connect: connect,
  7828. disconnect: disconnect,
  7829. getApis: function () {
  7830. return {};
  7831. },
  7832. element: constant(extSpec.element),
  7833. spec: constant(spec),
  7834. readState: constant('No state'),
  7835. syncComponents: noop,
  7836. components: constant([]),
  7837. events: constant({})
  7838. };
  7839. return premade(me);
  7840. };
  7841. var uids = generate$3;
  7842. var build$1 = function (spec) {
  7843. return getPremade(spec).fold(function () {
  7844. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  7845. return buildFromSpec(userSpecWithUid).getOrDie();
  7846. }, function (prebuilt) {
  7847. return prebuilt;
  7848. });
  7849. };
  7850. var premade$1 = premade;
  7851. var hoverEvent = 'alloy.item-hover';
  7852. var focusEvent = 'alloy.item-focus';
  7853. var onHover = function (item) {
  7854. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  7855. if (!Focusing.isFocused(item)) {
  7856. Focusing.focus(item);
  7857. }
  7858. emitWith(item, hoverEvent, { item: item });
  7859. }
  7860. };
  7861. var onFocus = function (item) {
  7862. emitWith(item, focusEvent, { item: item });
  7863. };
  7864. var hover = constant(hoverEvent);
  7865. var focus$3 = constant(focusEvent);
  7866. var builder = function (detail) {
  7867. return {
  7868. dom: detail.dom,
  7869. 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 } : {}) }),
  7870. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7871. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7872. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7873. }),
  7874. Focusing.config({
  7875. ignore: detail.ignoreFocus,
  7876. stopMousedown: detail.ignoreFocus,
  7877. onFocus: function (component) {
  7878. onFocus(component);
  7879. }
  7880. }),
  7881. Keying.config({ mode: 'execution' }),
  7882. Representing.config({
  7883. store: {
  7884. mode: 'memory',
  7885. initialValue: detail.data
  7886. }
  7887. }),
  7888. config('item-type-events', __spreadArrays(pointerEvents(), [
  7889. run(mouseover(), onHover),
  7890. run(focusItem(), Focusing.focus)
  7891. ]))
  7892. ]),
  7893. components: detail.components,
  7894. eventOrder: detail.eventOrder
  7895. };
  7896. };
  7897. var schema$a = [
  7898. strict$1('data'),
  7899. strict$1('components'),
  7900. strict$1('dom'),
  7901. defaulted$1('hasSubmenu', false),
  7902. option('toggling'),
  7903. SketchBehaviours.field('itemBehaviours', [
  7904. Toggling,
  7905. Focusing,
  7906. Keying,
  7907. Representing
  7908. ]),
  7909. defaulted$1('ignoreFocus', false),
  7910. defaulted$1('domModification', {}),
  7911. output('builder', builder),
  7912. defaulted$1('eventOrder', {})
  7913. ];
  7914. var builder$1 = function (detail) {
  7915. return {
  7916. dom: detail.dom,
  7917. components: detail.components,
  7918. events: derive([stopper(focusItem())])
  7919. };
  7920. };
  7921. var schema$b = [
  7922. strict$1('dom'),
  7923. strict$1('components'),
  7924. output('builder', builder$1)
  7925. ];
  7926. var owner$2 = function () {
  7927. return 'item-widget';
  7928. };
  7929. var parts = constant([required({
  7930. name: 'widget',
  7931. overrides: function (detail) {
  7932. return {
  7933. behaviours: derive$1([Representing.config({
  7934. store: {
  7935. mode: 'manual',
  7936. getValue: function (component) {
  7937. return detail.data;
  7938. },
  7939. setValue: function () {
  7940. }
  7941. }
  7942. })])
  7943. };
  7944. }
  7945. })]);
  7946. var builder$2 = function (detail) {
  7947. var subs = substitutes(owner$2(), detail, parts());
  7948. var components$1 = components(owner$2(), detail, subs.internals());
  7949. var focusWidget = function (component) {
  7950. return getPart(component, detail, 'widget').map(function (widget) {
  7951. Keying.focusIn(widget);
  7952. return widget;
  7953. });
  7954. };
  7955. var onHorizontalArrow = function (component, simulatedEvent) {
  7956. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  7957. if (detail.autofocus) {
  7958. simulatedEvent.setSource(component.element());
  7959. return Option.none();
  7960. } else {
  7961. return Option.none();
  7962. }
  7963. }();
  7964. };
  7965. return {
  7966. dom: detail.dom,
  7967. components: components$1,
  7968. domModification: detail.domModification,
  7969. events: derive([
  7970. runOnExecute(function (component, simulatedEvent) {
  7971. focusWidget(component).each(function (widget) {
  7972. simulatedEvent.stop();
  7973. });
  7974. }),
  7975. run(mouseover(), onHover),
  7976. run(focusItem(), function (component, simulatedEvent) {
  7977. if (detail.autofocus) {
  7978. focusWidget(component);
  7979. } else {
  7980. Focusing.focus(component);
  7981. }
  7982. })
  7983. ]),
  7984. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7985. Representing.config({
  7986. store: {
  7987. mode: 'memory',
  7988. initialValue: detail.data
  7989. }
  7990. }),
  7991. Focusing.config({
  7992. ignore: detail.ignoreFocus,
  7993. onFocus: function (component) {
  7994. onFocus(component);
  7995. }
  7996. }),
  7997. Keying.config({
  7998. mode: 'special',
  7999. focusIn: detail.autofocus ? function (component) {
  8000. focusWidget(component);
  8001. } : revoke(),
  8002. onLeft: onHorizontalArrow,
  8003. onRight: onHorizontalArrow,
  8004. onEscape: function (component, simulatedEvent) {
  8005. if (!Focusing.isFocused(component) && !detail.autofocus) {
  8006. Focusing.focus(component);
  8007. return Option.some(true);
  8008. } else if (detail.autofocus) {
  8009. simulatedEvent.setSource(component.element());
  8010. return Option.none();
  8011. } else {
  8012. return Option.none();
  8013. }
  8014. }
  8015. })
  8016. ])
  8017. };
  8018. };
  8019. var schema$c = [
  8020. strict$1('uid'),
  8021. strict$1('data'),
  8022. strict$1('components'),
  8023. strict$1('dom'),
  8024. defaulted$1('autofocus', false),
  8025. defaulted$1('ignoreFocus', false),
  8026. SketchBehaviours.field('widgetBehaviours', [
  8027. Representing,
  8028. Focusing,
  8029. Keying
  8030. ]),
  8031. defaulted$1('domModification', {}),
  8032. defaultUidsSchema(parts()),
  8033. output('builder', builder$2)
  8034. ];
  8035. var itemSchema$1 = choose$1('type', {
  8036. widget: schema$c,
  8037. item: schema$a,
  8038. separator: schema$b
  8039. });
  8040. var configureGrid = function (detail, movementInfo) {
  8041. return {
  8042. mode: 'flatgrid',
  8043. selector: '.' + detail.markers.item,
  8044. initSize: {
  8045. numColumns: movementInfo.initSize.numColumns,
  8046. numRows: movementInfo.initSize.numRows
  8047. },
  8048. focusManager: detail.focusManager
  8049. };
  8050. };
  8051. var configureMatrix = function (detail, movementInfo) {
  8052. return {
  8053. mode: 'matrix',
  8054. selectors: {
  8055. row: movementInfo.rowSelector,
  8056. cell: '.' + detail.markers.item
  8057. },
  8058. focusManager: detail.focusManager
  8059. };
  8060. };
  8061. var configureMenu = function (detail, movementInfo) {
  8062. return {
  8063. mode: 'menu',
  8064. selector: '.' + detail.markers.item,
  8065. moveOnTab: movementInfo.moveOnTab,
  8066. focusManager: detail.focusManager
  8067. };
  8068. };
  8069. var parts$1 = constant([group({
  8070. factory: {
  8071. sketch: function (spec) {
  8072. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  8073. return itemInfo.builder(itemInfo);
  8074. }
  8075. },
  8076. name: 'items',
  8077. unit: 'item',
  8078. defaults: function (detail, u) {
  8079. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$3('item') });
  8080. },
  8081. overrides: function (detail, u) {
  8082. return {
  8083. type: u.type,
  8084. ignoreFocus: detail.fakeFocus,
  8085. domModification: { classes: [detail.markers.item] }
  8086. };
  8087. }
  8088. })]);
  8089. var schema$d = constant([
  8090. strict$1('value'),
  8091. strict$1('items'),
  8092. strict$1('dom'),
  8093. strict$1('components'),
  8094. defaulted$1('eventOrder', {}),
  8095. field$1('menuBehaviours', [
  8096. Highlighting,
  8097. Representing,
  8098. Composing,
  8099. Keying
  8100. ]),
  8101. defaultedOf('movement', {
  8102. mode: 'menu',
  8103. moveOnTab: true
  8104. }, choose$1('mode', {
  8105. grid: [
  8106. initSize(),
  8107. output('config', configureGrid)
  8108. ],
  8109. matrix: [
  8110. output('config', configureMatrix),
  8111. strict$1('rowSelector')
  8112. ],
  8113. menu: [
  8114. defaulted$1('moveOnTab', true),
  8115. output('config', configureMenu)
  8116. ]
  8117. })),
  8118. itemMarkers(),
  8119. defaulted$1('fakeFocus', false),
  8120. defaulted$1('focusManager', dom()),
  8121. onHandler('onHighlight')
  8122. ]);
  8123. var focus$4 = constant('alloy.menu-focus');
  8124. var make$2 = function (detail, components, spec, externals) {
  8125. return {
  8126. uid: detail.uid,
  8127. dom: detail.dom,
  8128. markers: detail.markers,
  8129. behaviours: augment(detail.menuBehaviours, [
  8130. Highlighting.config({
  8131. highlightClass: detail.markers.selectedItem,
  8132. itemClass: detail.markers.item,
  8133. onHighlight: detail.onHighlight
  8134. }),
  8135. Representing.config({
  8136. store: {
  8137. mode: 'memory',
  8138. initialValue: detail.value
  8139. }
  8140. }),
  8141. Composing.config({ find: Option.some }),
  8142. Keying.config(detail.movement.config(detail, detail.movement))
  8143. ]),
  8144. events: derive([
  8145. run(focus$3(), function (menu, simulatedEvent) {
  8146. var event = simulatedEvent.event();
  8147. menu.getSystem().getByDom(event.target()).each(function (item) {
  8148. Highlighting.highlight(menu, item);
  8149. simulatedEvent.stop();
  8150. emitWith(menu, focus$4(), {
  8151. menu: menu,
  8152. item: item
  8153. });
  8154. });
  8155. }),
  8156. run(hover(), function (menu, simulatedEvent) {
  8157. var item = simulatedEvent.event().item();
  8158. Highlighting.highlight(menu, item);
  8159. })
  8160. ]),
  8161. components: components,
  8162. eventOrder: detail.eventOrder,
  8163. domModification: { attributes: { role: 'menu' } }
  8164. };
  8165. };
  8166. var Menu = composite$1({
  8167. name: 'Menu',
  8168. configFields: schema$d(),
  8169. partFields: parts$1(),
  8170. factory: make$2
  8171. });
  8172. var preserve$1 = function (f, container) {
  8173. var ownerDoc = owner(container);
  8174. var refocus = active(ownerDoc).bind(function (focused) {
  8175. var hasFocus = function (elem) {
  8176. return eq(focused, elem);
  8177. };
  8178. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  8179. });
  8180. var result = f(container);
  8181. refocus.each(function (oldFocus) {
  8182. active(ownerDoc).filter(function (newFocus) {
  8183. return eq(newFocus, oldFocus);
  8184. }).fold(function () {
  8185. focus$1(oldFocus);
  8186. }, noop);
  8187. });
  8188. return result;
  8189. };
  8190. var set$8 = function (component, replaceConfig, replaceState, data) {
  8191. preserve$1(function () {
  8192. var newChildren = map$1(data, component.getSystem().build);
  8193. replaceChildren(component, newChildren);
  8194. }, component.element());
  8195. };
  8196. var insert = function (component, replaceConfig, insertion, childSpec) {
  8197. var child = component.getSystem().build(childSpec);
  8198. attachWith(component, child, insertion);
  8199. };
  8200. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  8201. insert(component, replaceConfig, append, appendee);
  8202. };
  8203. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  8204. insert(component, replaceConfig, prepend, prependee);
  8205. };
  8206. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  8207. var children = contents(component);
  8208. var foundChild = find$2(children, function (child) {
  8209. return eq(removee.element(), child.element());
  8210. });
  8211. foundChild.each(detach);
  8212. };
  8213. var contents = function (component, replaceConfig) {
  8214. return component.components();
  8215. };
  8216. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8217. var children = contents(component);
  8218. return Option.from(children[replaceeIndex]).map(function (replacee) {
  8219. remove$7(component, replaceConfig, replaceState, replacee);
  8220. replacer.each(function (r) {
  8221. insert(component, replaceConfig, function (p, c) {
  8222. appendAt(p, c, replaceeIndex);
  8223. }, r);
  8224. });
  8225. return replacee;
  8226. });
  8227. };
  8228. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8229. var children = contents(component);
  8230. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  8231. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8232. });
  8233. };
  8234. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8235. __proto__: null,
  8236. append: append$2,
  8237. prepend: prepend$1,
  8238. remove: remove$7,
  8239. replaceAt: replaceAt,
  8240. replaceBy: replaceBy,
  8241. set: set$8,
  8242. contents: contents
  8243. });
  8244. var Replacing = create$1({
  8245. fields: [],
  8246. name: 'replacing',
  8247. apis: ReplaceApis
  8248. });
  8249. var transpose = function (obj) {
  8250. return tupleMap(obj, function (v, k) {
  8251. return {
  8252. k: v,
  8253. v: k
  8254. };
  8255. });
  8256. };
  8257. var trace = function (items, byItem, byMenu, finish) {
  8258. return get(byMenu, finish).bind(function (triggerItem) {
  8259. return get(items, triggerItem).bind(function (triggerMenu) {
  8260. var rest = trace(items, byItem, byMenu, triggerMenu);
  8261. return Option.some([triggerMenu].concat(rest));
  8262. });
  8263. }).getOr([]);
  8264. };
  8265. var generate$5 = function (menus, expansions) {
  8266. var items = {};
  8267. each(menus, function (menuItems, menu) {
  8268. each$1(menuItems, function (item) {
  8269. items[item] = menu;
  8270. });
  8271. });
  8272. var byItem = expansions;
  8273. var byMenu = transpose(expansions);
  8274. var menuPaths = map(byMenu, function (_triggerItem, submenu) {
  8275. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8276. });
  8277. return map(items, function (menu) {
  8278. return get(menuPaths, menu).getOr([menu]);
  8279. });
  8280. };
  8281. var init$3 = function () {
  8282. var expansions = Cell({});
  8283. var menus = Cell({});
  8284. var paths = Cell({});
  8285. var primary = Cell(Option.none());
  8286. var directory = Cell({});
  8287. var clear = function () {
  8288. expansions.set({});
  8289. menus.set({});
  8290. paths.set({});
  8291. primary.set(Option.none());
  8292. };
  8293. var isClear = function () {
  8294. return primary.get().isNone();
  8295. };
  8296. var setMenuBuilt = function (menuName, built) {
  8297. var _a;
  8298. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8299. type: 'prepared',
  8300. menu: built
  8301. }, _a)));
  8302. };
  8303. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8304. primary.set(Option.some(sPrimary));
  8305. expansions.set(sExpansions);
  8306. menus.set(sMenus);
  8307. directory.set(dir);
  8308. var sPaths = generate$5(dir, sExpansions);
  8309. paths.set(sPaths);
  8310. };
  8311. var getTriggeringItem = function (menuValue) {
  8312. return find(expansions.get(), function (v, k) {
  8313. return v === menuValue;
  8314. });
  8315. };
  8316. var getTriggerData = function (menuValue, getItemByValue, path) {
  8317. return getPreparedMenu(menuValue).bind(function (menu) {
  8318. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8319. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8320. return {
  8321. triggeredMenu: menu,
  8322. triggeringItem: triggeredItem,
  8323. triggeringPath: path
  8324. };
  8325. });
  8326. });
  8327. });
  8328. };
  8329. var getTriggeringPath = function (itemValue, getItemByValue) {
  8330. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  8331. return getPreparedMenu(menuValue).isSome();
  8332. });
  8333. return get(paths.get(), itemValue).bind(function (path) {
  8334. var revPath = reverse(extraPath.concat(path));
  8335. var triggers = bind(revPath, function (menuValue, menuIndex) {
  8336. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8337. return primary.get().is(menuValue) ? [] : [Option.none()];
  8338. }, function (data) {
  8339. return [Option.some(data)];
  8340. });
  8341. });
  8342. return sequence(triggers);
  8343. });
  8344. };
  8345. var expand = function (itemValue) {
  8346. return get(expansions.get(), itemValue).map(function (menu) {
  8347. var current = get(paths.get(), itemValue).getOr([]);
  8348. return [menu].concat(current);
  8349. });
  8350. };
  8351. var collapse = function (itemValue) {
  8352. return get(paths.get(), itemValue).bind(function (path) {
  8353. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  8354. });
  8355. };
  8356. var refresh = function (itemValue) {
  8357. return get(paths.get(), itemValue);
  8358. };
  8359. var getPreparedMenu = function (menuValue) {
  8360. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8361. };
  8362. var lookupMenu = function (menuValue) {
  8363. return get(menus.get(), menuValue);
  8364. };
  8365. var lookupItem = function (itemValue) {
  8366. return get(expansions.get(), itemValue);
  8367. };
  8368. var otherMenus = function (path) {
  8369. var menuValues = directory.get();
  8370. return difference(keys(menuValues), path);
  8371. };
  8372. var getPrimary = function () {
  8373. return primary.get().bind(getPreparedMenu);
  8374. };
  8375. var getMenus = function () {
  8376. return menus.get();
  8377. };
  8378. return {
  8379. setMenuBuilt: setMenuBuilt,
  8380. setContents: setContents,
  8381. expand: expand,
  8382. refresh: refresh,
  8383. collapse: collapse,
  8384. lookupMenu: lookupMenu,
  8385. lookupItem: lookupItem,
  8386. otherMenus: otherMenus,
  8387. getPrimary: getPrimary,
  8388. getMenus: getMenus,
  8389. clear: clear,
  8390. isClear: isClear,
  8391. getTriggeringPath: getTriggeringPath
  8392. };
  8393. };
  8394. var extractPreparedMenu = function (prep) {
  8395. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  8396. };
  8397. var LayeredState = {
  8398. init: init$3,
  8399. extractPreparedMenu: extractPreparedMenu
  8400. };
  8401. var make$3 = function (detail, rawUiSpec) {
  8402. var submenuParentItems = Cell(Option.none());
  8403. var buildMenus = function (container, primaryName, menus) {
  8404. return map(menus, function (spec, name) {
  8405. var makeSketch = function () {
  8406. return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), {
  8407. value: name,
  8408. items: spec.items,
  8409. markers: detail.markers,
  8410. fakeFocus: detail.fakeFocus,
  8411. onHighlight: detail.onHighlight,
  8412. focusManager: detail.fakeFocus ? highlights() : dom()
  8413. }));
  8414. };
  8415. return name === primaryName ? {
  8416. type: 'prepared',
  8417. menu: container.getSystem().build(makeSketch())
  8418. } : {
  8419. type: 'notbuilt',
  8420. nbMenu: makeSketch
  8421. };
  8422. });
  8423. };
  8424. var layeredState = LayeredState.init();
  8425. var setup = function (container) {
  8426. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8427. var directory = toDirectory();
  8428. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8429. return layeredState.getPrimary();
  8430. };
  8431. var getItemValue = function (item) {
  8432. return Representing.getValue(item).value;
  8433. };
  8434. var getItemByValue = function (container, menus, itemValue) {
  8435. return findMap(menus, function (menu) {
  8436. if (!menu.getSystem().isConnected()) {
  8437. return Option.none();
  8438. }
  8439. var candidates = Highlighting.getCandidates(menu);
  8440. return find$2(candidates, function (c) {
  8441. return getItemValue(c) === itemValue;
  8442. });
  8443. });
  8444. };
  8445. var toDirectory = function (container) {
  8446. return map(detail.data.menus, function (data, menuName) {
  8447. return bind(data.items, function (item) {
  8448. return item.type === 'separator' ? [] : [item.data.value];
  8449. });
  8450. });
  8451. };
  8452. var setActiveMenu = function (container, menu) {
  8453. Highlighting.highlight(container, menu);
  8454. Highlighting.getHighlighted(menu).orThunk(function () {
  8455. return Highlighting.getFirst(menu);
  8456. }).each(function (item) {
  8457. dispatch(container, item.element(), focusItem());
  8458. });
  8459. };
  8460. var getMenus = function (state, menuValues) {
  8461. return cat(map$1(menuValues, function (mv) {
  8462. return state.lookupMenu(mv).bind(function (prep) {
  8463. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  8464. });
  8465. }));
  8466. };
  8467. var closeOthers = function (container, state, path) {
  8468. var others = getMenus(state, state.otherMenus(path));
  8469. each$1(others, function (o) {
  8470. remove$6(o.element(), [detail.markers.backgroundMenu]);
  8471. if (!detail.stayInDom) {
  8472. Replacing.remove(container, o);
  8473. }
  8474. });
  8475. };
  8476. var getSubmenuParents = function (container) {
  8477. return submenuParentItems.get().getOrThunk(function () {
  8478. var r = {};
  8479. var items = descendants(container.element(), '.' + detail.markers.item);
  8480. var parentItems = filter(items, function (i) {
  8481. return get$1(i, 'aria-haspopup') === 'true';
  8482. });
  8483. each$1(parentItems, function (i) {
  8484. container.getSystem().getByDom(i).each(function (itemComp) {
  8485. var key = getItemValue(itemComp);
  8486. r[key] = itemComp;
  8487. });
  8488. });
  8489. submenuParentItems.set(Option.some(r));
  8490. return r;
  8491. });
  8492. };
  8493. var updateAriaExpansions = function (container, path) {
  8494. var parentItems = getSubmenuParents(container);
  8495. each(parentItems, function (v, k) {
  8496. var expanded = contains(path, k);
  8497. set(v.element(), 'aria-expanded', expanded);
  8498. });
  8499. };
  8500. var updateMenuPath = function (container, state, path) {
  8501. return Option.from(path[0]).bind(function (latestMenuName) {
  8502. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8503. if (menuPrep.type === 'notbuilt') {
  8504. return Option.none();
  8505. } else {
  8506. var activeMenu = menuPrep.menu;
  8507. var rest = getMenus(state, path.slice(1));
  8508. each$1(rest, function (r) {
  8509. add$2(r.element(), detail.markers.backgroundMenu);
  8510. });
  8511. if (!inBody(activeMenu.element())) {
  8512. Replacing.append(container, premade$1(activeMenu));
  8513. }
  8514. remove$6(activeMenu.element(), [detail.markers.backgroundMenu]);
  8515. setActiveMenu(container, activeMenu);
  8516. closeOthers(container, state, path);
  8517. return Option.some(activeMenu);
  8518. }
  8519. });
  8520. });
  8521. };
  8522. var ExpandHighlightDecision;
  8523. (function (ExpandHighlightDecision) {
  8524. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8525. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8526. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8527. var buildIfRequired = function (container, menuName, menuPrep) {
  8528. if (menuPrep.type === 'notbuilt') {
  8529. var menu = container.getSystem().build(menuPrep.nbMenu());
  8530. layeredState.setMenuBuilt(menuName, menu);
  8531. return menu;
  8532. } else {
  8533. return menuPrep.menu;
  8534. }
  8535. };
  8536. var expandRight = function (container, item, decision) {
  8537. if (decision === void 0) {
  8538. decision = ExpandHighlightDecision.HighlightSubmenu;
  8539. }
  8540. var value = getItemValue(item);
  8541. return layeredState.expand(value).bind(function (path) {
  8542. updateAriaExpansions(container, path);
  8543. return Option.from(path[0]).bind(function (menuName) {
  8544. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8545. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8546. if (!inBody(activeMenu.element())) {
  8547. Replacing.append(container, premade$1(activeMenu));
  8548. }
  8549. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8550. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8551. Highlighting.highlightFirst(activeMenu);
  8552. return updateMenuPath(container, layeredState, path);
  8553. } else {
  8554. Highlighting.dehighlightAll(activeMenu);
  8555. return Option.some(item);
  8556. }
  8557. });
  8558. });
  8559. });
  8560. };
  8561. var collapseLeft = function (container, item) {
  8562. var value = getItemValue(item);
  8563. return layeredState.collapse(value).bind(function (path) {
  8564. updateAriaExpansions(container, path);
  8565. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8566. detail.onCollapseMenu(container, item, activeMenu);
  8567. return activeMenu;
  8568. });
  8569. });
  8570. };
  8571. var updateView = function (container, item) {
  8572. var value = getItemValue(item);
  8573. return layeredState.refresh(value).bind(function (path) {
  8574. updateAriaExpansions(container, path);
  8575. return updateMenuPath(container, layeredState, path);
  8576. });
  8577. };
  8578. var onRight = function (container, item) {
  8579. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8580. };
  8581. var onLeft = function (container, item) {
  8582. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  8583. };
  8584. var onEscape = function (container, item) {
  8585. return collapseLeft(container, item).orThunk(function () {
  8586. return detail.onEscape(container, item).map(function () {
  8587. return container;
  8588. });
  8589. });
  8590. };
  8591. var keyOnItem = function (f) {
  8592. return function (container, simulatedEvent) {
  8593. return closest$2(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8594. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  8595. return f(container, item).map(function () {
  8596. return true;
  8597. });
  8598. });
  8599. });
  8600. };
  8601. };
  8602. var events = derive([
  8603. run(focus$4(), function (sandbox, simulatedEvent) {
  8604. var item = simulatedEvent.event().item();
  8605. layeredState.lookupItem(getItemValue(item)).each(function () {
  8606. var menu = simulatedEvent.event().menu();
  8607. Highlighting.highlight(sandbox, menu);
  8608. var value = getItemValue(simulatedEvent.event().item());
  8609. layeredState.refresh(value).each(function (path) {
  8610. return closeOthers(sandbox, layeredState, path);
  8611. });
  8612. });
  8613. }),
  8614. runOnExecute(function (component, simulatedEvent) {
  8615. var target = simulatedEvent.event().target();
  8616. component.getSystem().getByDom(target).each(function (item) {
  8617. var itemValue = getItemValue(item);
  8618. if (itemValue.indexOf('collapse-item') === 0) {
  8619. collapseLeft(component, item);
  8620. }
  8621. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8622. detail.onExecute(component, item);
  8623. }, function () {
  8624. });
  8625. });
  8626. }),
  8627. runOnAttached(function (container, simulatedEvent) {
  8628. setup(container).each(function (primary) {
  8629. Replacing.append(container, premade$1(primary));
  8630. detail.onOpenMenu(container, primary);
  8631. if (detail.highlightImmediately) {
  8632. setActiveMenu(container, primary);
  8633. }
  8634. });
  8635. })
  8636. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8637. var item = simulatedEvent.event().item();
  8638. updateView(sandbox, item);
  8639. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8640. detail.onHover(sandbox, item);
  8641. })] : []));
  8642. var getActiveItem = function (container) {
  8643. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8644. };
  8645. var collapseMenuApi = function (container) {
  8646. getActiveItem(container).each(function (currentItem) {
  8647. collapseLeft(container, currentItem);
  8648. });
  8649. };
  8650. var highlightPrimary = function (container) {
  8651. layeredState.getPrimary().each(function (primary) {
  8652. setActiveMenu(container, primary);
  8653. });
  8654. };
  8655. var extractMenuFromContainer = function (container) {
  8656. return Option.from(container.components()[0]).filter(function (comp) {
  8657. return get$1(comp.element(), 'role') === 'menu';
  8658. });
  8659. };
  8660. var repositionMenus = function (container) {
  8661. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8662. return getActiveItem(container).bind(function (currentItem) {
  8663. var itemValue = getItemValue(currentItem);
  8664. var allMenus = values(layeredState.getMenus());
  8665. var preparedMenus = cat(map$1(allMenus, LayeredState.extractPreparedMenu));
  8666. return layeredState.getTriggeringPath(itemValue, function (v) {
  8667. return getItemByValue(container, preparedMenus, v);
  8668. });
  8669. }).map(function (triggeringPath) {
  8670. return {
  8671. primary: primary,
  8672. triggeringPath: triggeringPath
  8673. };
  8674. });
  8675. });
  8676. maybeActivePrimary.fold(function () {
  8677. extractMenuFromContainer(container).each(function (primaryMenu) {
  8678. detail.onRepositionMenu(container, primaryMenu, []);
  8679. });
  8680. }, function (_a) {
  8681. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8682. detail.onRepositionMenu(container, primary, triggeringPath);
  8683. });
  8684. };
  8685. var apis = {
  8686. collapseMenu: collapseMenuApi,
  8687. highlightPrimary: highlightPrimary,
  8688. repositionMenus: repositionMenus
  8689. };
  8690. return {
  8691. uid: detail.uid,
  8692. dom: detail.dom,
  8693. markers: detail.markers,
  8694. behaviours: augment(detail.tmenuBehaviours, [
  8695. Keying.config({
  8696. mode: 'special',
  8697. onRight: keyOnItem(onRight),
  8698. onLeft: keyOnItem(onLeft),
  8699. onEscape: keyOnItem(onEscape),
  8700. focusIn: function (container, keyInfo) {
  8701. layeredState.getPrimary().each(function (primary) {
  8702. dispatch(container, primary.element(), focusItem());
  8703. });
  8704. }
  8705. }),
  8706. Highlighting.config({
  8707. highlightClass: detail.markers.selectedMenu,
  8708. itemClass: detail.markers.menu
  8709. }),
  8710. Composing.config({
  8711. find: function (container) {
  8712. return Highlighting.getHighlighted(container);
  8713. }
  8714. }),
  8715. Replacing.config({})
  8716. ]),
  8717. eventOrder: detail.eventOrder,
  8718. apis: apis,
  8719. events: events
  8720. };
  8721. };
  8722. var collapseItem = constant('collapse-item');
  8723. var tieredData = function (primary, menus, expansions) {
  8724. return {
  8725. primary: primary,
  8726. menus: menus,
  8727. expansions: expansions
  8728. };
  8729. };
  8730. var singleData = function (name, menu) {
  8731. return {
  8732. primary: name,
  8733. menus: wrap$1(name, menu),
  8734. expansions: {}
  8735. };
  8736. };
  8737. var collapseItem$1 = function (text) {
  8738. return {
  8739. value: generate$1(collapseItem()),
  8740. meta: { text: text }
  8741. };
  8742. };
  8743. var tieredMenu = single$2({
  8744. name: 'TieredMenu',
  8745. configFields: [
  8746. onStrictKeyboardHandler('onExecute'),
  8747. onStrictKeyboardHandler('onEscape'),
  8748. onStrictHandler('onOpenMenu'),
  8749. onStrictHandler('onOpenSubmenu'),
  8750. onHandler('onRepositionMenu'),
  8751. onHandler('onCollapseMenu'),
  8752. defaulted$1('highlightImmediately', true),
  8753. strictObjOf('data', [
  8754. strict$1('primary'),
  8755. strict$1('menus'),
  8756. strict$1('expansions')
  8757. ]),
  8758. defaulted$1('fakeFocus', false),
  8759. onHandler('onHighlight'),
  8760. onHandler('onHover'),
  8761. tieredMenuMarkers(),
  8762. strict$1('dom'),
  8763. defaulted$1('navigateOnHover', true),
  8764. defaulted$1('stayInDom', false),
  8765. field$1('tmenuBehaviours', [
  8766. Keying,
  8767. Highlighting,
  8768. Composing,
  8769. Replacing
  8770. ]),
  8771. defaulted$1('eventOrder', {})
  8772. ],
  8773. apis: {
  8774. collapseMenu: function (apis, tmenu) {
  8775. apis.collapseMenu(tmenu);
  8776. },
  8777. highlightPrimary: function (apis, tmenu) {
  8778. apis.highlightPrimary(tmenu);
  8779. },
  8780. repositionMenus: function (apis, tmenu) {
  8781. apis.repositionMenus(tmenu);
  8782. }
  8783. },
  8784. factory: make$3,
  8785. extraApis: {
  8786. tieredData: tieredData,
  8787. singleData: singleData,
  8788. collapseItem: collapseItem$1
  8789. }
  8790. });
  8791. var findRoute = function (component, transConfig, transState, route) {
  8792. return get(transConfig.routes, route.start).bind(function (sConfig) {
  8793. return get(sConfig, route.destination);
  8794. });
  8795. };
  8796. var getTransition = function (comp, transConfig, transState) {
  8797. var route = getCurrentRoute(comp, transConfig);
  8798. return route.bind(function (r) {
  8799. return getTransitionOf(comp, transConfig, transState, r);
  8800. });
  8801. };
  8802. var getTransitionOf = function (comp, transConfig, transState, route) {
  8803. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8804. return r.transition.map(function (t) {
  8805. return {
  8806. transition: t,
  8807. route: r
  8808. };
  8809. });
  8810. });
  8811. };
  8812. var disableTransition = function (comp, transConfig, transState) {
  8813. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8814. var t = routeTransition.transition;
  8815. remove$4(comp.element(), t.transitionClass);
  8816. remove$1(comp.element(), transConfig.destinationAttr);
  8817. });
  8818. };
  8819. var getNewRoute = function (comp, transConfig, transState, destination) {
  8820. return {
  8821. start: get$1(comp.element(), transConfig.stateAttr),
  8822. destination: destination
  8823. };
  8824. };
  8825. var getCurrentRoute = function (comp, transConfig, transState) {
  8826. var el = comp.element();
  8827. return has$1(el, transConfig.destinationAttr) ? Option.some({
  8828. start: get$1(comp.element(), transConfig.stateAttr),
  8829. destination: get$1(comp.element(), transConfig.destinationAttr)
  8830. }) : Option.none();
  8831. };
  8832. var jumpTo = function (comp, transConfig, transState, destination) {
  8833. disableTransition(comp, transConfig, transState);
  8834. if (has$1(comp.element(), transConfig.stateAttr) && get$1(comp.element(), transConfig.stateAttr) !== destination) {
  8835. transConfig.onFinish(comp, destination);
  8836. }
  8837. set(comp.element(), transConfig.stateAttr, destination);
  8838. };
  8839. var fasttrack = function (comp, transConfig, transState, destination) {
  8840. if (has$1(comp.element(), transConfig.destinationAttr)) {
  8841. set(comp.element(), transConfig.stateAttr, get$1(comp.element(), transConfig.destinationAttr));
  8842. remove$1(comp.element(), transConfig.destinationAttr);
  8843. }
  8844. };
  8845. var progressTo = function (comp, transConfig, transState, destination) {
  8846. fasttrack(comp, transConfig);
  8847. var route = getNewRoute(comp, transConfig, transState, destination);
  8848. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8849. jumpTo(comp, transConfig, transState, destination);
  8850. }, function (routeTransition) {
  8851. disableTransition(comp, transConfig, transState);
  8852. var t = routeTransition.transition;
  8853. add$2(comp.element(), t.transitionClass);
  8854. set(comp.element(), transConfig.destinationAttr, destination);
  8855. });
  8856. };
  8857. var getState$1 = function (comp, transConfig, transState) {
  8858. var e = comp.element();
  8859. return has$1(e, transConfig.stateAttr) ? Option.some(get$1(e, transConfig.stateAttr)) : Option.none();
  8860. };
  8861. var TransitionApis = /*#__PURE__*/Object.freeze({
  8862. __proto__: null,
  8863. findRoute: findRoute,
  8864. disableTransition: disableTransition,
  8865. getCurrentRoute: getCurrentRoute,
  8866. jumpTo: jumpTo,
  8867. progressTo: progressTo,
  8868. getState: getState$1
  8869. });
  8870. var events$9 = function (transConfig, transState) {
  8871. return derive([
  8872. run(transitionend(), function (component, simulatedEvent) {
  8873. var raw = simulatedEvent.event().raw();
  8874. getCurrentRoute(component, transConfig).each(function (route) {
  8875. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8876. rInfo.transition.each(function (rTransition) {
  8877. if (raw.propertyName === rTransition.property) {
  8878. jumpTo(component, transConfig, transState, route.destination);
  8879. transConfig.onTransition(component, route);
  8880. }
  8881. });
  8882. });
  8883. });
  8884. }),
  8885. runOnAttached(function (comp, se) {
  8886. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8887. })
  8888. ]);
  8889. };
  8890. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8891. __proto__: null,
  8892. events: events$9
  8893. });
  8894. var TransitionSchema = [
  8895. defaulted$1('destinationAttr', 'data-transitioning-destination'),
  8896. defaulted$1('stateAttr', 'data-transitioning-state'),
  8897. strict$1('initialState'),
  8898. onHandler('onTransition'),
  8899. onHandler('onFinish'),
  8900. strictOf('routes', setOf$1(Result.value, setOf$1(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8901. strict$1('property'),
  8902. strict$1('transitionClass')
  8903. ])]))))
  8904. ];
  8905. var createRoutes = function (routes) {
  8906. var r = {};
  8907. each(routes, function (v, k) {
  8908. var waypoints = k.split('<->');
  8909. r[waypoints[0]] = wrap$1(waypoints[1], v);
  8910. r[waypoints[1]] = wrap$1(waypoints[0], v);
  8911. });
  8912. return r;
  8913. };
  8914. var createBistate = function (first, second, transitions) {
  8915. return wrapAll$1([
  8916. {
  8917. key: first,
  8918. value: wrap$1(second, transitions)
  8919. },
  8920. {
  8921. key: second,
  8922. value: wrap$1(first, transitions)
  8923. }
  8924. ]);
  8925. };
  8926. var createTristate = function (first, second, third, transitions) {
  8927. return wrapAll$1([
  8928. {
  8929. key: first,
  8930. value: wrapAll$1([
  8931. {
  8932. key: second,
  8933. value: transitions
  8934. },
  8935. {
  8936. key: third,
  8937. value: transitions
  8938. }
  8939. ])
  8940. },
  8941. {
  8942. key: second,
  8943. value: wrapAll$1([
  8944. {
  8945. key: first,
  8946. value: transitions
  8947. },
  8948. {
  8949. key: third,
  8950. value: transitions
  8951. }
  8952. ])
  8953. },
  8954. {
  8955. key: third,
  8956. value: wrapAll$1([
  8957. {
  8958. key: first,
  8959. value: transitions
  8960. },
  8961. {
  8962. key: second,
  8963. value: transitions
  8964. }
  8965. ])
  8966. }
  8967. ]);
  8968. };
  8969. var Transitioning = create$1({
  8970. fields: TransitionSchema,
  8971. name: 'transitioning',
  8972. active: ActiveTransitioning,
  8973. apis: TransitionApis,
  8974. extra: {
  8975. createRoutes: createRoutes,
  8976. createBistate: createBistate,
  8977. createTristate: createTristate
  8978. }
  8979. });
  8980. var scrollable = Styles.resolve('scrollable');
  8981. var register = function (element) {
  8982. add$2(element, scrollable);
  8983. };
  8984. var deregister = function (element) {
  8985. remove$4(element, scrollable);
  8986. };
  8987. var Scrollable = {
  8988. register: register,
  8989. deregister: deregister,
  8990. scrollable: constant(scrollable)
  8991. };
  8992. var getValue$4 = function (item) {
  8993. return get(item, 'format').getOr(item.title);
  8994. };
  8995. var convert$1 = function (formats, memMenuThunk) {
  8996. var mainMenu = makeMenu('Styles', [].concat(map$1(formats.items, function (k) {
  8997. return makeItem(getValue$4(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue$4(k)));
  8998. })), memMenuThunk, false);
  8999. var submenus = map(formats.menus, function (menuItems, menuName) {
  9000. var items = map$1(menuItems, function (item) {
  9001. return makeItem(getValue$4(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue$4(item)));
  9002. });
  9003. return makeMenu(menuName, items, memMenuThunk, true);
  9004. });
  9005. var menus = deepMerge(submenus, wrap$1('styles', mainMenu));
  9006. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  9007. return { tmenu: tmenu };
  9008. };
  9009. var makeItem = function (value, text, selected, preview, isMenu) {
  9010. return {
  9011. data: {
  9012. value: value,
  9013. text: text
  9014. },
  9015. type: 'item',
  9016. dom: {
  9017. tag: 'div',
  9018. classes: isMenu ? [Styles.resolve('styles-item-is-menu')] : []
  9019. },
  9020. toggling: {
  9021. toggleOnExecute: false,
  9022. toggleClass: Styles.resolve('format-matches'),
  9023. selected: selected
  9024. },
  9025. itemBehaviours: derive$1(isMenu ? [] : [Receivers.format(value, function (comp, status) {
  9026. var toggle = status ? Toggling.on : Toggling.off;
  9027. toggle(comp);
  9028. })]),
  9029. components: [{
  9030. dom: {
  9031. tag: 'div',
  9032. attributes: { style: preview },
  9033. innerHtml: text
  9034. }
  9035. }]
  9036. };
  9037. };
  9038. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  9039. return {
  9040. value: value,
  9041. dom: { tag: 'div' },
  9042. components: [
  9043. Button.sketch({
  9044. dom: {
  9045. tag: 'div',
  9046. classes: [Styles.resolve('styles-collapser')]
  9047. },
  9048. components: collapsable ? [
  9049. {
  9050. dom: {
  9051. tag: 'span',
  9052. classes: [Styles.resolve('styles-collapse-icon')]
  9053. }
  9054. },
  9055. text(value)
  9056. ] : [text(value)],
  9057. action: function (item) {
  9058. if (collapsable) {
  9059. var comp = memMenuThunk().get(item);
  9060. tieredMenu.collapseMenu(comp);
  9061. }
  9062. }
  9063. }),
  9064. {
  9065. dom: {
  9066. tag: 'div',
  9067. classes: [Styles.resolve('styles-menu-items-container')]
  9068. },
  9069. components: [Menu.parts().items({})],
  9070. behaviours: derive$1([config('adhoc-scrollable-menu', [
  9071. runOnAttached(function (component, simulatedEvent) {
  9072. set$3(component.element(), 'overflow-y', 'auto');
  9073. set$3(component.element(), '-webkit-overflow-scrolling', 'touch');
  9074. Scrollable.register(component.element());
  9075. }),
  9076. runOnDetached(function (component) {
  9077. remove$5(component.element(), 'overflow-y');
  9078. remove$5(component.element(), '-webkit-overflow-scrolling');
  9079. Scrollable.deregister(component.element());
  9080. })
  9081. ])])
  9082. }
  9083. ],
  9084. items: items,
  9085. menuBehaviours: derive$1([Transitioning.config({
  9086. initialState: 'after',
  9087. routes: Transitioning.createTristate('before', 'current', 'after', {
  9088. transition: {
  9089. property: 'transform',
  9090. transitionClass: 'transitioning'
  9091. }
  9092. })
  9093. })])
  9094. };
  9095. };
  9096. var sketch$8 = function (settings) {
  9097. var dataset = convert$1(settings.formats, function () {
  9098. return memMenu;
  9099. });
  9100. var memMenu = record(tieredMenu.sketch({
  9101. dom: {
  9102. tag: 'div',
  9103. classes: [Styles.resolve('styles-menu')]
  9104. },
  9105. components: [],
  9106. fakeFocus: true,
  9107. stayInDom: true,
  9108. onExecute: function (tmenu, item) {
  9109. var v = Representing.getValue(item);
  9110. settings.handle(item, v.value);
  9111. return Option.none();
  9112. },
  9113. onEscape: function () {
  9114. return Option.none();
  9115. },
  9116. onOpenMenu: function (container, menu) {
  9117. var w = get$7(container.element());
  9118. set$4(menu.element(), w);
  9119. Transitioning.jumpTo(menu, 'current');
  9120. },
  9121. onOpenSubmenu: function (container, item, submenu) {
  9122. var w = get$7(container.element());
  9123. var menu = ancestor$2(item.element(), '[role="menu"]').getOrDie('hacky');
  9124. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9125. set$4(submenu.element(), w);
  9126. Transitioning.progressTo(menuComp, 'before');
  9127. Transitioning.jumpTo(submenu, 'after');
  9128. Transitioning.progressTo(submenu, 'current');
  9129. },
  9130. onCollapseMenu: function (container, item, menu) {
  9131. var submenu = ancestor$2(item.element(), '[role="menu"]').getOrDie('hacky');
  9132. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9133. Transitioning.progressTo(submenuComp, 'after');
  9134. Transitioning.progressTo(menu, 'current');
  9135. },
  9136. navigateOnHover: false,
  9137. highlightImmediately: true,
  9138. data: dataset.tmenu,
  9139. markers: {
  9140. backgroundMenu: Styles.resolve('styles-background-menu'),
  9141. menu: Styles.resolve('styles-menu'),
  9142. selectedMenu: Styles.resolve('styles-selected-menu'),
  9143. item: Styles.resolve('styles-item'),
  9144. selectedItem: Styles.resolve('styles-selected-item')
  9145. }
  9146. }));
  9147. return memMenu.asSpec();
  9148. };
  9149. var StylesMenu = { sketch: sketch$8 };
  9150. var getFromExpandingItem = function (item) {
  9151. var newItem = deepMerge(exclude$1(item, ['items']), { menu: true });
  9152. var rest = expand(item.items);
  9153. var newMenus = deepMerge(rest.menus, wrap$1(item.title, rest.items));
  9154. var newExpansions = deepMerge(rest.expansions, wrap$1(item.title, item.title));
  9155. return {
  9156. item: newItem,
  9157. menus: newMenus,
  9158. expansions: newExpansions
  9159. };
  9160. };
  9161. var getFromItem = function (item) {
  9162. return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : {
  9163. item: item,
  9164. menus: {},
  9165. expansions: {}
  9166. };
  9167. };
  9168. var expand = function (items) {
  9169. return foldr(items, function (acc, item) {
  9170. var newData = getFromItem(item);
  9171. return {
  9172. menus: deepMerge(acc.menus, newData.menus),
  9173. items: [newData.item].concat(acc.items),
  9174. expansions: deepMerge(acc.expansions, newData.expansions)
  9175. };
  9176. }, {
  9177. menus: {},
  9178. expansions: {},
  9179. items: []
  9180. });
  9181. };
  9182. var StyleConversions = { expand: expand };
  9183. var register$1 = function (editor, settings) {
  9184. var isSelectedFor = function (format) {
  9185. return function () {
  9186. return editor.formatter.match(format);
  9187. };
  9188. };
  9189. var getPreview = function (format) {
  9190. return function () {
  9191. var styles = editor.formatter.getCssText(format);
  9192. return styles;
  9193. };
  9194. };
  9195. var enrichSupported = function (item) {
  9196. return deepMerge(item, {
  9197. isSelected: isSelectedFor(item.format),
  9198. getPreview: getPreview(item.format)
  9199. });
  9200. };
  9201. var enrichMenu = function (item) {
  9202. return deepMerge(item, {
  9203. isSelected: constant(false),
  9204. getPreview: constant('')
  9205. });
  9206. };
  9207. var enrichCustom = function (item) {
  9208. var formatName = generate$1(item.title);
  9209. var newItem = deepMerge(item, {
  9210. format: formatName,
  9211. isSelected: isSelectedFor(formatName),
  9212. getPreview: getPreview(formatName)
  9213. });
  9214. editor.formatter.register(formatName, newItem);
  9215. return newItem;
  9216. };
  9217. var formats = get(settings, 'style_formats').getOr(DefaultStyleFormats);
  9218. var doEnrich = function (items) {
  9219. return map$1(items, function (item) {
  9220. if (hasNonNullableKey(item, 'items')) {
  9221. var newItems = doEnrich(item.items);
  9222. return deepMerge(enrichMenu(item), { items: newItems });
  9223. } else if (hasNonNullableKey(item, 'format')) {
  9224. return enrichSupported(item);
  9225. } else {
  9226. return enrichCustom(item);
  9227. }
  9228. });
  9229. };
  9230. return doEnrich(formats);
  9231. };
  9232. var prune = function (editor, formats) {
  9233. var doPrune = function (items) {
  9234. return bind(items, function (item) {
  9235. if (item.items !== undefined) {
  9236. var newItems = doPrune(item.items);
  9237. return newItems.length > 0 ? [item] : [];
  9238. } else {
  9239. var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9240. return keep ? [item] : [];
  9241. }
  9242. });
  9243. };
  9244. var prunedItems = doPrune(formats);
  9245. return StyleConversions.expand(prunedItems);
  9246. };
  9247. var ui = function (editor, formats, onDone) {
  9248. var pruned = prune(editor, formats);
  9249. return StylesMenu.sketch({
  9250. formats: pruned,
  9251. handle: function (item, value) {
  9252. editor.undoManager.transact(function () {
  9253. if (Toggling.isOn(item)) {
  9254. editor.formatter.remove(value);
  9255. } else {
  9256. editor.formatter.apply(value);
  9257. }
  9258. });
  9259. onDone();
  9260. }
  9261. });
  9262. };
  9263. var StyleFormats = {
  9264. register: register$1,
  9265. ui: ui
  9266. };
  9267. var defaults = [
  9268. 'undo',
  9269. 'bold',
  9270. 'italic',
  9271. 'link',
  9272. 'image',
  9273. 'bullist',
  9274. 'styleselect'
  9275. ];
  9276. var extract$1 = function (rawToolbar) {
  9277. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9278. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9279. };
  9280. var identifyFromArray = function (toolbar) {
  9281. return bind(toolbar, function (item) {
  9282. return isArray(item) ? identifyFromArray(item) : extract$1(item);
  9283. });
  9284. };
  9285. var identify = function (settings) {
  9286. var toolbar = settings.toolbar !== undefined ? settings.toolbar : defaults;
  9287. return isArray(toolbar) ? identifyFromArray(toolbar) : extract$1(toolbar);
  9288. };
  9289. var setup = function (realm, editor) {
  9290. var commandSketch = function (name) {
  9291. return function () {
  9292. return Buttons.forToolbarCommand(editor, name);
  9293. };
  9294. };
  9295. var stateCommandSketch = function (name) {
  9296. return function () {
  9297. return Buttons.forToolbarStateCommand(editor, name);
  9298. };
  9299. };
  9300. var actionSketch = function (name, query, action) {
  9301. return function () {
  9302. return Buttons.forToolbarStateAction(editor, name, query, action);
  9303. };
  9304. };
  9305. var undo = commandSketch('undo');
  9306. var redo = commandSketch('redo');
  9307. var bold = stateCommandSketch('bold');
  9308. var italic = stateCommandSketch('italic');
  9309. var underline = stateCommandSketch('underline');
  9310. var removeformat = commandSketch('removeformat');
  9311. var link = function () {
  9312. return sketch$7(realm, editor);
  9313. };
  9314. var unlink = actionSketch('unlink', 'link', function () {
  9315. editor.execCommand('unlink', null, false);
  9316. });
  9317. var image = function () {
  9318. return sketch$4(editor);
  9319. };
  9320. var bullist = actionSketch('unordered-list', 'ul', function () {
  9321. editor.execCommand('InsertUnorderedList', null, false);
  9322. });
  9323. var numlist = actionSketch('ordered-list', 'ol', function () {
  9324. editor.execCommand('InsertOrderedList', null, false);
  9325. });
  9326. var fontsizeselect = function () {
  9327. return sketch$3(realm, editor);
  9328. };
  9329. var forecolor = function () {
  9330. return ColorSlider.sketch(realm, editor);
  9331. };
  9332. var styleFormats = StyleFormats.register(editor, editor.settings);
  9333. var styleFormatsMenu = function () {
  9334. return StyleFormats.ui(editor, styleFormats, function () {
  9335. editor.fire('scrollIntoView');
  9336. });
  9337. };
  9338. var styleselect = function () {
  9339. return Buttons.forToolbar('style-formats', function (button) {
  9340. editor.fire('toReading');
  9341. realm.dropup().appear(styleFormatsMenu, Toggling.on, button);
  9342. }, derive$1([
  9343. Toggling.config({
  9344. toggleClass: Styles.resolve('toolbar-button-selected'),
  9345. toggleOnExecute: false,
  9346. aria: { mode: 'pressed' }
  9347. }),
  9348. Receiving.config({
  9349. channels: wrapAll$1([
  9350. Receivers.receive(TinyChannels.orientationChanged(), Toggling.off),
  9351. Receivers.receive(TinyChannels.dropupDismissed(), Toggling.off)
  9352. ])
  9353. })
  9354. ]), editor);
  9355. };
  9356. var feature = function (prereq, sketch) {
  9357. return {
  9358. isSupported: function () {
  9359. var buttons = editor.ui.registry.getAll().buttons;
  9360. return prereq.forall(function (p) {
  9361. return hasNonNullableKey(buttons, p);
  9362. });
  9363. },
  9364. sketch: sketch
  9365. };
  9366. };
  9367. return {
  9368. undo: feature(Option.none(), undo),
  9369. redo: feature(Option.none(), redo),
  9370. bold: feature(Option.none(), bold),
  9371. italic: feature(Option.none(), italic),
  9372. underline: feature(Option.none(), underline),
  9373. removeformat: feature(Option.none(), removeformat),
  9374. link: feature(Option.none(), link),
  9375. unlink: feature(Option.none(), unlink),
  9376. image: feature(Option.none(), image),
  9377. bullist: feature(Option.some('bullist'), bullist),
  9378. numlist: feature(Option.some('numlist'), numlist),
  9379. fontsizeselect: feature(Option.none(), fontsizeselect),
  9380. forecolor: feature(Option.none(), forecolor),
  9381. styleselect: feature(Option.none(), styleselect)
  9382. };
  9383. };
  9384. var detect$4 = function (settings, features) {
  9385. var itemNames = identify(settings);
  9386. var present = {};
  9387. return bind(itemNames, function (iName) {
  9388. var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9389. present[iName] = true;
  9390. return r;
  9391. });
  9392. };
  9393. var Features = {
  9394. identify: identify,
  9395. setup: setup,
  9396. detect: detect$4
  9397. };
  9398. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9399. return {
  9400. target: constant(target),
  9401. x: constant(x),
  9402. y: constant(y),
  9403. stop: stop,
  9404. prevent: prevent,
  9405. kill: kill,
  9406. raw: constant(raw)
  9407. };
  9408. };
  9409. var fromRawEvent = function (rawEvent) {
  9410. var target = Element.fromDom(rawEvent.target);
  9411. var stop = function () {
  9412. rawEvent.stopPropagation();
  9413. };
  9414. var prevent = function () {
  9415. rawEvent.preventDefault();
  9416. };
  9417. var kill = compose(prevent, stop);
  9418. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9419. };
  9420. var handle = function (filter, handler) {
  9421. return function (rawEvent) {
  9422. if (!filter(rawEvent)) {
  9423. return;
  9424. }
  9425. handler(fromRawEvent(rawEvent));
  9426. };
  9427. };
  9428. var binder = function (element, event, filter, handler, useCapture) {
  9429. var wrapped = handle(filter, handler);
  9430. element.dom().addEventListener(event, wrapped, useCapture);
  9431. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9432. };
  9433. var bind$2 = function (element, event, filter, handler) {
  9434. return binder(element, event, filter, handler, false);
  9435. };
  9436. var capture = function (element, event, filter, handler) {
  9437. return binder(element, event, filter, handler, true);
  9438. };
  9439. var unbind = function (element, event, handler, useCapture) {
  9440. element.dom().removeEventListener(event, handler, useCapture);
  9441. };
  9442. var filter$1 = constant(true);
  9443. var bind$3 = function (element, event, handler) {
  9444. return bind$2(element, event, filter$1, handler);
  9445. };
  9446. var capture$1 = function (element, event, handler) {
  9447. return capture(element, event, filter$1, handler);
  9448. };
  9449. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9450. var INTERVAL = 50;
  9451. var INSURANCE = 1000 / INTERVAL;
  9452. var get$b = function (outerWindow) {
  9453. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9454. return { isPortrait: constant(isPortrait) };
  9455. };
  9456. var getActualWidth = function (outerWindow) {
  9457. var isIos = detect$3().os.isiOS();
  9458. var isPortrait = get$b(outerWindow).isPortrait();
  9459. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9460. };
  9461. var onChange = function (outerWindow, listeners) {
  9462. var win = Element.fromDom(outerWindow);
  9463. var poller = null;
  9464. var change = function () {
  9465. global$4.clearInterval(poller);
  9466. var orientation = get$b(outerWindow);
  9467. listeners.onChange(orientation);
  9468. onAdjustment(function () {
  9469. listeners.onReady(orientation);
  9470. });
  9471. };
  9472. var orientationHandle = bind$3(win, 'orientationchange', change);
  9473. var onAdjustment = function (f) {
  9474. global$4.clearInterval(poller);
  9475. var flag = outerWindow.innerHeight;
  9476. var insurance = 0;
  9477. poller = global$4.setInterval(function () {
  9478. if (flag !== outerWindow.innerHeight) {
  9479. global$4.clearInterval(poller);
  9480. f(Option.some(outerWindow.innerHeight));
  9481. } else if (insurance > INSURANCE) {
  9482. global$4.clearInterval(poller);
  9483. f(Option.none());
  9484. }
  9485. insurance++;
  9486. }, INTERVAL);
  9487. };
  9488. var destroy = function () {
  9489. orientationHandle.unbind();
  9490. };
  9491. return {
  9492. onAdjustment: onAdjustment,
  9493. destroy: destroy
  9494. };
  9495. };
  9496. var Orientation = {
  9497. get: get$b,
  9498. onChange: onChange,
  9499. getActualWidth: getActualWidth
  9500. };
  9501. function DelayedFunction (fun, delay) {
  9502. var ref = null;
  9503. var schedule = function () {
  9504. var args = [];
  9505. for (var _i = 0; _i < arguments.length; _i++) {
  9506. args[_i] = arguments[_i];
  9507. }
  9508. ref = domGlobals.setTimeout(function () {
  9509. fun.apply(null, args);
  9510. ref = null;
  9511. }, delay);
  9512. };
  9513. var cancel = function () {
  9514. if (ref !== null) {
  9515. domGlobals.clearTimeout(ref);
  9516. ref = null;
  9517. }
  9518. };
  9519. return {
  9520. cancel: cancel,
  9521. schedule: schedule
  9522. };
  9523. }
  9524. var SIGNIFICANT_MOVE = 5;
  9525. var LONGPRESS_DELAY = 400;
  9526. var getTouch = function (event) {
  9527. var raw = event.raw();
  9528. if (raw.touches === undefined || raw.touches.length !== 1) {
  9529. return Option.none();
  9530. }
  9531. return Option.some(raw.touches[0]);
  9532. };
  9533. var isFarEnough = function (touch, data) {
  9534. var distX = Math.abs(touch.clientX - data.x());
  9535. var distY = Math.abs(touch.clientY - data.y());
  9536. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  9537. };
  9538. var monitor = function (settings) {
  9539. var startData = Cell(Option.none());
  9540. var longpressFired = Cell(false);
  9541. var longpress$1 = DelayedFunction(function (event) {
  9542. settings.triggerEvent(longpress(), event);
  9543. longpressFired.set(true);
  9544. }, LONGPRESS_DELAY);
  9545. var handleTouchstart = function (event) {
  9546. getTouch(event).each(function (touch) {
  9547. longpress$1.cancel();
  9548. var data = {
  9549. x: constant(touch.clientX),
  9550. y: constant(touch.clientY),
  9551. target: event.target
  9552. };
  9553. longpress$1.schedule(event);
  9554. longpressFired.set(false);
  9555. startData.set(Option.some(data));
  9556. });
  9557. return Option.none();
  9558. };
  9559. var handleTouchmove = function (event) {
  9560. longpress$1.cancel();
  9561. getTouch(event).each(function (touch) {
  9562. startData.get().each(function (data) {
  9563. if (isFarEnough(touch, data)) {
  9564. startData.set(Option.none());
  9565. }
  9566. });
  9567. });
  9568. return Option.none();
  9569. };
  9570. var handleTouchend = function (event) {
  9571. longpress$1.cancel();
  9572. var isSame = function (data) {
  9573. return eq(data.target(), event.target());
  9574. };
  9575. return startData.get().filter(isSame).map(function (data) {
  9576. if (longpressFired.get()) {
  9577. event.prevent();
  9578. return false;
  9579. } else {
  9580. return settings.triggerEvent(tap(), event);
  9581. }
  9582. });
  9583. };
  9584. var handlers = wrapAll$1([
  9585. {
  9586. key: touchstart(),
  9587. value: handleTouchstart
  9588. },
  9589. {
  9590. key: touchmove(),
  9591. value: handleTouchmove
  9592. },
  9593. {
  9594. key: touchend(),
  9595. value: handleTouchend
  9596. }
  9597. ]);
  9598. var fireIfReady = function (event, type) {
  9599. return get(handlers, type).bind(function (handler) {
  9600. return handler(event);
  9601. });
  9602. };
  9603. return { fireIfReady: fireIfReady };
  9604. };
  9605. var monitor$1 = function (editorApi) {
  9606. var tapEvent = monitor({
  9607. triggerEvent: function (type, evt) {
  9608. editorApi.onTapContent(evt);
  9609. }
  9610. });
  9611. var onTouchend = function () {
  9612. return bind$3(editorApi.body(), 'touchend', function (evt) {
  9613. tapEvent.fireIfReady(evt, 'touchend');
  9614. });
  9615. };
  9616. var onTouchmove = function () {
  9617. return bind$3(editorApi.body(), 'touchmove', function (evt) {
  9618. tapEvent.fireIfReady(evt, 'touchmove');
  9619. });
  9620. };
  9621. var fireTouchstart = function (evt) {
  9622. tapEvent.fireIfReady(evt, 'touchstart');
  9623. };
  9624. return {
  9625. fireTouchstart: fireTouchstart,
  9626. onTouchend: onTouchend,
  9627. onTouchmove: onTouchmove
  9628. };
  9629. };
  9630. var TappingEvent = { monitor: monitor$1 };
  9631. var isAndroid6 = detect$3().os.version.major >= 6;
  9632. var initEvents = function (editorApi, toolstrip, alloy) {
  9633. var tapping = TappingEvent.monitor(editorApi);
  9634. var outerDoc = owner(toolstrip);
  9635. var isRanged = function (sel) {
  9636. return !eq(sel.start(), sel.finish()) || sel.soffset() !== sel.foffset();
  9637. };
  9638. var hasRangeInUi = function () {
  9639. return active(outerDoc).filter(function (input) {
  9640. return name(input) === 'input';
  9641. }).exists(function (input) {
  9642. return input.dom().selectionStart !== input.dom().selectionEnd;
  9643. });
  9644. };
  9645. var updateMargin = function () {
  9646. var rangeInContent = editorApi.doc().dom().hasFocus() && editorApi.getSelection().exists(isRanged);
  9647. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  9648. };
  9649. var listeners = [
  9650. bind$3(editorApi.body(), 'touchstart', function (evt) {
  9651. editorApi.onTouchContent();
  9652. tapping.fireTouchstart(evt);
  9653. }),
  9654. tapping.onTouchmove(),
  9655. tapping.onTouchend(),
  9656. bind$3(toolstrip, 'touchstart', function (evt) {
  9657. editorApi.onTouchToolstrip();
  9658. }),
  9659. editorApi.onToReading(function () {
  9660. blur(editorApi.body());
  9661. }),
  9662. editorApi.onToEditing(noop),
  9663. editorApi.onScrollToCursor(function (tinyEvent) {
  9664. tinyEvent.preventDefault();
  9665. editorApi.getCursorBox().each(function (bounds) {
  9666. var cWin = editorApi.win();
  9667. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  9668. var cScrollBy = isOutside ? bounds.bottom() - cWin.innerHeight + 50 : 0;
  9669. if (cScrollBy !== 0) {
  9670. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  9671. }
  9672. });
  9673. })
  9674. ].concat(isAndroid6 === true ? [] : [
  9675. bind$3(Element.fromDom(editorApi.win()), 'blur', function () {
  9676. alloy.getByDom(toolstrip).each(Toggling.off);
  9677. }),
  9678. bind$3(outerDoc, 'select', updateMargin),
  9679. bind$3(editorApi.doc(), 'selectionchange', updateMargin)
  9680. ]);
  9681. var destroy = function () {
  9682. each$1(listeners, function (l) {
  9683. l.unbind();
  9684. });
  9685. };
  9686. return { destroy: destroy };
  9687. };
  9688. var AndroidEvents = { initEvents: initEvents };
  9689. var safeParse = function (element, attribute) {
  9690. var parsed = parseInt(get$1(element, attribute), 10);
  9691. return isNaN(parsed) ? 0 : parsed;
  9692. };
  9693. var DataAttributes = { safeParse: safeParse };
  9694. function NodeValue (is, name) {
  9695. var get = function (element) {
  9696. if (!is(element)) {
  9697. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9698. }
  9699. return getOption(element).getOr('');
  9700. };
  9701. var getOption = function (element) {
  9702. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  9703. };
  9704. var set = function (element, value) {
  9705. if (!is(element)) {
  9706. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9707. }
  9708. element.dom().nodeValue = value;
  9709. };
  9710. return {
  9711. get: get,
  9712. getOption: getOption,
  9713. set: set
  9714. };
  9715. }
  9716. var api$3 = NodeValue(isText, 'text');
  9717. var getOption = function (element) {
  9718. return api$3.getOption(element);
  9719. };
  9720. var getEnd = function (element) {
  9721. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  9722. return children(element).length;
  9723. }, function (v) {
  9724. return v.length;
  9725. });
  9726. };
  9727. var create$3 = Immutable('start', 'soffset', 'finish', 'foffset');
  9728. var SimRange = { create: create$3 };
  9729. var adt$4 = Adt.generate([
  9730. { before: ['element'] },
  9731. {
  9732. on: [
  9733. 'element',
  9734. 'offset'
  9735. ]
  9736. },
  9737. { after: ['element'] }
  9738. ]);
  9739. var cata = function (subject, onBefore, onOn, onAfter) {
  9740. return subject.fold(onBefore, onOn, onAfter);
  9741. };
  9742. var getStart = function (situ) {
  9743. return situ.fold(identity, identity, identity);
  9744. };
  9745. var before$1 = adt$4.before;
  9746. var on$1 = adt$4.on;
  9747. var after$1 = adt$4.after;
  9748. var Situ = {
  9749. before: before$1,
  9750. on: on$1,
  9751. after: after$1,
  9752. cata: cata,
  9753. getStart: getStart
  9754. };
  9755. var adt$5 = Adt.generate([
  9756. { domRange: ['rng'] },
  9757. {
  9758. relative: [
  9759. 'startSitu',
  9760. 'finishSitu'
  9761. ]
  9762. },
  9763. {
  9764. exact: [
  9765. 'start',
  9766. 'soffset',
  9767. 'finish',
  9768. 'foffset'
  9769. ]
  9770. }
  9771. ]);
  9772. var exactFromRange = function (simRange) {
  9773. return adt$5.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  9774. };
  9775. var getStart$1 = function (selection) {
  9776. return selection.match({
  9777. domRange: function (rng) {
  9778. return Element.fromDom(rng.startContainer);
  9779. },
  9780. relative: function (startSitu, finishSitu) {
  9781. return Situ.getStart(startSitu);
  9782. },
  9783. exact: function (start, soffset, finish, foffset) {
  9784. return start;
  9785. }
  9786. });
  9787. };
  9788. var domRange = adt$5.domRange;
  9789. var relative = adt$5.relative;
  9790. var exact = adt$5.exact;
  9791. var getWin = function (selection) {
  9792. var start = getStart$1(selection);
  9793. return defaultView(start);
  9794. };
  9795. var range$1 = SimRange.create;
  9796. var Selection = {
  9797. domRange: domRange,
  9798. relative: relative,
  9799. exact: exact,
  9800. exactFromRange: exactFromRange,
  9801. getWin: getWin,
  9802. range: range$1
  9803. };
  9804. var setStart = function (rng, situ) {
  9805. situ.fold(function (e) {
  9806. rng.setStartBefore(e.dom());
  9807. }, function (e, o) {
  9808. rng.setStart(e.dom(), o);
  9809. }, function (e) {
  9810. rng.setStartAfter(e.dom());
  9811. });
  9812. };
  9813. var setFinish = function (rng, situ) {
  9814. situ.fold(function (e) {
  9815. rng.setEndBefore(e.dom());
  9816. }, function (e, o) {
  9817. rng.setEnd(e.dom(), o);
  9818. }, function (e) {
  9819. rng.setEndAfter(e.dom());
  9820. });
  9821. };
  9822. var relativeToNative = function (win, startSitu, finishSitu) {
  9823. var range = win.document.createRange();
  9824. setStart(range, startSitu);
  9825. setFinish(range, finishSitu);
  9826. return range;
  9827. };
  9828. var exactToNative = function (win, start, soffset, finish, foffset) {
  9829. var rng = win.document.createRange();
  9830. rng.setStart(start.dom(), soffset);
  9831. rng.setEnd(finish.dom(), foffset);
  9832. return rng;
  9833. };
  9834. var toRect = function (rect) {
  9835. return {
  9836. left: constant(rect.left),
  9837. top: constant(rect.top),
  9838. right: constant(rect.right),
  9839. bottom: constant(rect.bottom),
  9840. width: constant(rect.width),
  9841. height: constant(rect.height)
  9842. };
  9843. };
  9844. var getFirstRect = function (rng) {
  9845. var rects = rng.getClientRects();
  9846. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9847. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  9848. };
  9849. var adt$6 = Adt.generate([
  9850. {
  9851. ltr: [
  9852. 'start',
  9853. 'soffset',
  9854. 'finish',
  9855. 'foffset'
  9856. ]
  9857. },
  9858. {
  9859. rtl: [
  9860. 'start',
  9861. 'soffset',
  9862. 'finish',
  9863. 'foffset'
  9864. ]
  9865. }
  9866. ]);
  9867. var fromRange = function (win, type, range) {
  9868. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  9869. };
  9870. var getRanges = function (win, selection) {
  9871. return selection.match({
  9872. domRange: function (rng) {
  9873. return {
  9874. ltr: constant(rng),
  9875. rtl: Option.none
  9876. };
  9877. },
  9878. relative: function (startSitu, finishSitu) {
  9879. return {
  9880. ltr: cached(function () {
  9881. return relativeToNative(win, startSitu, finishSitu);
  9882. }),
  9883. rtl: cached(function () {
  9884. return Option.some(relativeToNative(win, finishSitu, startSitu));
  9885. })
  9886. };
  9887. },
  9888. exact: function (start, soffset, finish, foffset) {
  9889. return {
  9890. ltr: cached(function () {
  9891. return exactToNative(win, start, soffset, finish, foffset);
  9892. }),
  9893. rtl: cached(function () {
  9894. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  9895. })
  9896. };
  9897. }
  9898. });
  9899. };
  9900. var doDiagnose = function (win, ranges) {
  9901. var rng = ranges.ltr();
  9902. if (rng.collapsed) {
  9903. var reversed = ranges.rtl().filter(function (rev) {
  9904. return rev.collapsed === false;
  9905. });
  9906. return reversed.map(function (rev) {
  9907. return adt$6.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  9908. }).getOrThunk(function () {
  9909. return fromRange(win, adt$6.ltr, rng);
  9910. });
  9911. } else {
  9912. return fromRange(win, adt$6.ltr, rng);
  9913. }
  9914. };
  9915. var diagnose = function (win, selection) {
  9916. var ranges = getRanges(win, selection);
  9917. return doDiagnose(win, ranges);
  9918. };
  9919. var asLtrRange = function (win, selection) {
  9920. var diagnosis = diagnose(win, selection);
  9921. return diagnosis.match({
  9922. ltr: function (start, soffset, finish, foffset) {
  9923. var rng = win.document.createRange();
  9924. rng.setStart(start.dom(), soffset);
  9925. rng.setEnd(finish.dom(), foffset);
  9926. return rng;
  9927. },
  9928. rtl: function (start, soffset, finish, foffset) {
  9929. var rng = win.document.createRange();
  9930. rng.setStart(finish.dom(), foffset);
  9931. rng.setEnd(start.dom(), soffset);
  9932. return rng;
  9933. }
  9934. });
  9935. };
  9936. var ltr = adt$6.ltr;
  9937. var rtl = adt$6.rtl;
  9938. var beforeSpecial = function (element, offset) {
  9939. var name$1 = name(element);
  9940. if ('input' === name$1) {
  9941. return Situ.after(element);
  9942. } else if (!contains([
  9943. 'br',
  9944. 'img'
  9945. ], name$1)) {
  9946. return Situ.on(element, offset);
  9947. } else {
  9948. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9949. }
  9950. };
  9951. var preprocessExact = function (start, soffset, finish, foffset) {
  9952. var startSitu = beforeSpecial(start, soffset);
  9953. var finishSitu = beforeSpecial(finish, foffset);
  9954. return Selection.relative(startSitu, finishSitu);
  9955. };
  9956. var makeRange = function (start, soffset, finish, foffset) {
  9957. var doc = owner(start);
  9958. var rng = doc.dom().createRange();
  9959. rng.setStart(start.dom(), soffset);
  9960. rng.setEnd(finish.dom(), foffset);
  9961. return rng;
  9962. };
  9963. var after$2 = function (start, soffset, finish, foffset) {
  9964. var r = makeRange(start, soffset, finish, foffset);
  9965. var same = eq(start, finish) && soffset === foffset;
  9966. return r.collapsed && !same;
  9967. };
  9968. var doSetNativeRange = function (win, rng) {
  9969. Option.from(win.getSelection()).each(function (selection) {
  9970. selection.removeAllRanges();
  9971. selection.addRange(rng);
  9972. });
  9973. };
  9974. var doSetRange = function (win, start, soffset, finish, foffset) {
  9975. var rng = exactToNative(win, start, soffset, finish, foffset);
  9976. doSetNativeRange(win, rng);
  9977. };
  9978. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9979. selection.collapse(start.dom(), soffset);
  9980. selection.extend(finish.dom(), foffset);
  9981. };
  9982. var setRangeFromRelative = function (win, relative) {
  9983. return diagnose(win, relative).match({
  9984. ltr: function (start, soffset, finish, foffset) {
  9985. doSetRange(win, start, soffset, finish, foffset);
  9986. },
  9987. rtl: function (start, soffset, finish, foffset) {
  9988. var selection = win.getSelection();
  9989. if (selection.setBaseAndExtent) {
  9990. selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
  9991. } else if (selection.extend) {
  9992. try {
  9993. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9994. } catch (e) {
  9995. doSetRange(win, finish, foffset, start, soffset);
  9996. }
  9997. } else {
  9998. doSetRange(win, finish, foffset, start, soffset);
  9999. }
  10000. }
  10001. });
  10002. };
  10003. var setExact = function (win, start, soffset, finish, foffset) {
  10004. var relative = preprocessExact(start, soffset, finish, foffset);
  10005. setRangeFromRelative(win, relative);
  10006. };
  10007. var readRange = function (selection) {
  10008. if (selection.rangeCount > 0) {
  10009. var firstRng = selection.getRangeAt(0);
  10010. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  10011. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  10012. } else {
  10013. return Option.none();
  10014. }
  10015. };
  10016. var doGetExact = function (selection) {
  10017. var anchor = Element.fromDom(selection.anchorNode);
  10018. var focus = Element.fromDom(selection.focusNode);
  10019. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  10020. };
  10021. var getExact = function (win) {
  10022. return Option.from(win.getSelection()).filter(function (sel) {
  10023. return sel.rangeCount > 0;
  10024. }).bind(doGetExact);
  10025. };
  10026. var get$c = function (win) {
  10027. return getExact(win).map(function (range) {
  10028. return Selection.exact(range.start(), range.soffset(), range.finish(), range.foffset());
  10029. });
  10030. };
  10031. var getFirstRect$1 = function (win, selection) {
  10032. var rng = asLtrRange(win, selection);
  10033. return getFirstRect(rng);
  10034. };
  10035. var clear$1 = function (win) {
  10036. var selection = win.getSelection();
  10037. selection.removeAllRanges();
  10038. };
  10039. var COLLAPSED_WIDTH = 2;
  10040. var collapsedRect = function (rect) {
  10041. return {
  10042. left: rect.left,
  10043. top: rect.top,
  10044. right: rect.right,
  10045. bottom: rect.bottom,
  10046. width: constant(COLLAPSED_WIDTH),
  10047. height: rect.height
  10048. };
  10049. };
  10050. var toRect$1 = function (rawRect) {
  10051. return {
  10052. left: constant(rawRect.left),
  10053. top: constant(rawRect.top),
  10054. right: constant(rawRect.right),
  10055. bottom: constant(rawRect.bottom),
  10056. width: constant(rawRect.width),
  10057. height: constant(rawRect.height)
  10058. };
  10059. };
  10060. var getRectsFromRange = function (range) {
  10061. if (!range.collapsed) {
  10062. return map$1(range.getClientRects(), toRect$1);
  10063. } else {
  10064. var start_1 = Element.fromDom(range.startContainer);
  10065. return parent(start_1).bind(function (parent) {
  10066. var selection = Selection.exact(start_1, range.startOffset, parent, getEnd(parent));
  10067. var optRect = getFirstRect$1(range.startContainer.ownerDocument.defaultView, selection);
  10068. return optRect.map(collapsedRect).map(pure);
  10069. }).getOr([]);
  10070. }
  10071. };
  10072. var getRectangles = function (cWin) {
  10073. var sel = cWin.getSelection();
  10074. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  10075. };
  10076. var Rectangles = { getRectangles: getRectangles };
  10077. var autocompleteHack = function () {
  10078. return function (f) {
  10079. global$4.setTimeout(function () {
  10080. f();
  10081. }, 0);
  10082. };
  10083. };
  10084. var resume = function (cWin) {
  10085. cWin.focus();
  10086. var iBody = Element.fromDom(cWin.document.body);
  10087. var inInput = active().exists(function (elem) {
  10088. return contains([
  10089. 'input',
  10090. 'textarea'
  10091. ], name(elem));
  10092. });
  10093. var transaction = inInput ? autocompleteHack() : apply;
  10094. transaction(function () {
  10095. active().each(blur);
  10096. focus$1(iBody);
  10097. });
  10098. };
  10099. var ResumeEditing = { resume: resume };
  10100. var EXTRA_SPACING = 50;
  10101. var data = 'data-' + Styles.resolve('last-outer-height');
  10102. var setLastHeight = function (cBody, value) {
  10103. set(cBody, data, value);
  10104. };
  10105. var getLastHeight = function (cBody) {
  10106. return DataAttributes.safeParse(cBody, data);
  10107. };
  10108. var getBoundsFrom = function (rect) {
  10109. return {
  10110. top: constant(rect.top()),
  10111. bottom: constant(rect.top() + rect.height())
  10112. };
  10113. };
  10114. var getBounds$1 = function (cWin) {
  10115. var rects = Rectangles.getRectangles(cWin);
  10116. return rects.length > 0 ? Option.some(rects[0]).map(getBoundsFrom) : Option.none();
  10117. };
  10118. var findDelta = function (outerWindow, cBody) {
  10119. var last = getLastHeight(cBody);
  10120. var current = outerWindow.innerHeight;
  10121. return last > current ? Option.some(last - current) : Option.none();
  10122. };
  10123. var calculate = function (cWin, bounds, delta) {
  10124. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  10125. return isOutside ? Math.min(delta, bounds.bottom() - cWin.innerHeight + EXTRA_SPACING) : 0;
  10126. };
  10127. var setup$1 = function (outerWindow, cWin) {
  10128. var cBody = Element.fromDom(cWin.document.body);
  10129. var toEditing = function () {
  10130. ResumeEditing.resume(cWin);
  10131. };
  10132. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  10133. findDelta(outerWindow, cBody).each(function (delta) {
  10134. getBounds$1(cWin).each(function (bounds) {
  10135. var cScrollBy = calculate(cWin, bounds, delta);
  10136. if (cScrollBy !== 0) {
  10137. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10138. }
  10139. });
  10140. });
  10141. setLastHeight(cBody, outerWindow.innerHeight);
  10142. });
  10143. setLastHeight(cBody, outerWindow.innerHeight);
  10144. var destroy = function () {
  10145. onResize.unbind();
  10146. };
  10147. return {
  10148. toEditing: toEditing,
  10149. destroy: destroy
  10150. };
  10151. };
  10152. var AndroidSetup = { setup: setup$1 };
  10153. var getBodyFromFrame = function (frame) {
  10154. return Option.some(Element.fromDom(frame.dom().contentWindow.document.body));
  10155. };
  10156. var getDocFromFrame = function (frame) {
  10157. return Option.some(Element.fromDom(frame.dom().contentWindow.document));
  10158. };
  10159. var getWinFromFrame = function (frame) {
  10160. return Option.from(frame.dom().contentWindow);
  10161. };
  10162. var getSelectionFromFrame = function (frame) {
  10163. var optWin = getWinFromFrame(frame);
  10164. return optWin.bind(getExact);
  10165. };
  10166. var getFrame = function (editor) {
  10167. return editor.getFrame();
  10168. };
  10169. var getOrDerive = function (name, f) {
  10170. return function (editor) {
  10171. var g = editor[name].getOrThunk(function () {
  10172. var frame = getFrame(editor);
  10173. return function () {
  10174. return f(frame);
  10175. };
  10176. });
  10177. return g();
  10178. };
  10179. };
  10180. var getOrListen = function (editor, doc, name, type) {
  10181. return editor[name].getOrThunk(function () {
  10182. return function (handler) {
  10183. return bind$3(doc, type, handler);
  10184. };
  10185. });
  10186. };
  10187. var toRect$2 = function (rect) {
  10188. return {
  10189. left: constant(rect.left),
  10190. top: constant(rect.top),
  10191. right: constant(rect.right),
  10192. bottom: constant(rect.bottom),
  10193. width: constant(rect.width),
  10194. height: constant(rect.height)
  10195. };
  10196. };
  10197. var getActiveApi = function (editor) {
  10198. var frame = getFrame(editor);
  10199. var tryFallbackBox = function (win) {
  10200. var isCollapsed = function (sel) {
  10201. return eq(sel.start(), sel.finish()) && sel.soffset() === sel.foffset();
  10202. };
  10203. var toStartRect = function (sel) {
  10204. var rect = sel.start().dom().getBoundingClientRect();
  10205. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect$2) : Option.none();
  10206. };
  10207. return getExact(win).filter(isCollapsed).bind(toStartRect);
  10208. };
  10209. return getBodyFromFrame(frame).bind(function (body) {
  10210. return getDocFromFrame(frame).bind(function (doc) {
  10211. return getWinFromFrame(frame).map(function (win) {
  10212. var html = Element.fromDom(doc.dom().documentElement);
  10213. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  10214. return function () {
  10215. return get$c(win).bind(function (sel) {
  10216. return getFirstRect$1(win, sel).orThunk(function () {
  10217. return tryFallbackBox(win);
  10218. });
  10219. });
  10220. };
  10221. });
  10222. var setSelection = editor.setSelection.getOrThunk(function () {
  10223. return function (start, soffset, finish, foffset) {
  10224. setExact(win, start, soffset, finish, foffset);
  10225. };
  10226. });
  10227. var clearSelection = editor.clearSelection.getOrThunk(function () {
  10228. return function () {
  10229. clear$1(win);
  10230. };
  10231. });
  10232. return {
  10233. body: constant(body),
  10234. doc: constant(doc),
  10235. win: constant(win),
  10236. html: constant(html),
  10237. getSelection: curry(getSelectionFromFrame, frame),
  10238. setSelection: setSelection,
  10239. clearSelection: clearSelection,
  10240. frame: constant(frame),
  10241. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  10242. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  10243. onDomChanged: editor.onDomChanged,
  10244. onScrollToCursor: editor.onScrollToCursor,
  10245. onScrollToElement: editor.onScrollToElement,
  10246. onToReading: editor.onToReading,
  10247. onToEditing: editor.onToEditing,
  10248. onToolbarScrollStart: editor.onToolbarScrollStart,
  10249. onTouchContent: editor.onTouchContent,
  10250. onTapContent: editor.onTapContent,
  10251. onTouchToolstrip: editor.onTouchToolstrip,
  10252. getCursorBox: getCursorBox
  10253. };
  10254. });
  10255. });
  10256. });
  10257. };
  10258. var PlatformEditor = {
  10259. getBody: getOrDerive('getBody', getBodyFromFrame),
  10260. getDoc: getOrDerive('getDoc', getDocFromFrame),
  10261. getWin: getOrDerive('getWin', getWinFromFrame),
  10262. getSelection: getOrDerive('getSelection', getSelectionFromFrame),
  10263. getFrame: getFrame,
  10264. getActiveApi: getActiveApi
  10265. };
  10266. var attr = 'data-ephox-mobile-fullscreen-style';
  10267. var siblingStyles = 'display:none!important;';
  10268. var ancestorPosition = 'position:absolute!important;';
  10269. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  10270. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  10271. var isAndroid = detect$3().os.isAndroid();
  10272. var matchColor = function (editorBody) {
  10273. var color = get$4(editorBody, 'background-color');
  10274. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  10275. };
  10276. var clobberStyles = function (container, editorBody) {
  10277. var gatherSibilings = function (element) {
  10278. var siblings = siblings$2(element, '*');
  10279. return siblings;
  10280. };
  10281. var clobber = function (clobberStyle) {
  10282. return function (element) {
  10283. var styles = get$1(element, 'style');
  10284. var backup = styles === undefined ? 'no-styles' : styles.trim();
  10285. if (backup === clobberStyle) {
  10286. return;
  10287. } else {
  10288. set(element, attr, backup);
  10289. set(element, 'style', clobberStyle);
  10290. }
  10291. };
  10292. };
  10293. var ancestors = ancestors$1(container, '*');
  10294. var siblings = bind(ancestors, gatherSibilings);
  10295. var bgColor = matchColor(editorBody);
  10296. each$1(siblings, clobber(siblingStyles));
  10297. each$1(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor));
  10298. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  10299. clobber(containerStyles + ancestorStyles + bgColor)(container);
  10300. };
  10301. var restoreStyles = function () {
  10302. var clobberedEls = all$2('[' + attr + ']');
  10303. each$1(clobberedEls, function (element) {
  10304. var restore = get$1(element, attr);
  10305. if (restore !== 'no-styles') {
  10306. set(element, 'style', restore);
  10307. } else {
  10308. remove$1(element, 'style');
  10309. }
  10310. remove$1(element, attr);
  10311. });
  10312. };
  10313. var Thor = {
  10314. clobberStyles: clobberStyles,
  10315. restoreStyles: restoreStyles
  10316. };
  10317. var tag = function () {
  10318. var head = first('head').getOrDie();
  10319. var nu = function () {
  10320. var meta = Element.fromTag('meta');
  10321. set(meta, 'name', 'viewport');
  10322. append(head, meta);
  10323. return meta;
  10324. };
  10325. var element = first('meta[name="viewport"]').getOrThunk(nu);
  10326. var backup = get$1(element, 'content');
  10327. var maximize = function () {
  10328. set(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  10329. };
  10330. var restore = function () {
  10331. if (backup !== undefined && backup !== null && backup.length > 0) {
  10332. set(element, 'content', backup);
  10333. } else {
  10334. set(element, 'content', 'user-scalable=yes');
  10335. }
  10336. };
  10337. return {
  10338. maximize: maximize,
  10339. restore: restore
  10340. };
  10341. };
  10342. var MetaViewport = { tag: tag };
  10343. var create$4 = function (platform, mask) {
  10344. var meta = MetaViewport.tag();
  10345. var androidApi = api$2();
  10346. var androidEvents = api$2();
  10347. var enter = function () {
  10348. mask.hide();
  10349. add$2(platform.container, Styles.resolve('fullscreen-maximized'));
  10350. add$2(platform.container, Styles.resolve('android-maximized'));
  10351. meta.maximize();
  10352. add$2(platform.body, Styles.resolve('android-scroll-reload'));
  10353. androidApi.set(AndroidSetup.setup(platform.win, PlatformEditor.getWin(platform.editor).getOrDie('no')));
  10354. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  10355. Thor.clobberStyles(platform.container, editorApi.body());
  10356. androidEvents.set(AndroidEvents.initEvents(editorApi, platform.toolstrip, platform.alloy));
  10357. });
  10358. };
  10359. var exit = function () {
  10360. meta.restore();
  10361. mask.show();
  10362. remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
  10363. remove$4(platform.container, Styles.resolve('android-maximized'));
  10364. Thor.restoreStyles();
  10365. remove$4(platform.body, Styles.resolve('android-scroll-reload'));
  10366. androidEvents.clear();
  10367. androidApi.clear();
  10368. };
  10369. return {
  10370. enter: enter,
  10371. exit: exit
  10372. };
  10373. };
  10374. var AndroidMode = { create: create$4 };
  10375. var first$1 = function (fn, rate) {
  10376. var timer = null;
  10377. var cancel = function () {
  10378. if (timer !== null) {
  10379. domGlobals.clearTimeout(timer);
  10380. timer = null;
  10381. }
  10382. };
  10383. var throttle = function () {
  10384. var args = [];
  10385. for (var _i = 0; _i < arguments.length; _i++) {
  10386. args[_i] = arguments[_i];
  10387. }
  10388. if (timer === null) {
  10389. timer = domGlobals.setTimeout(function () {
  10390. fn.apply(null, args);
  10391. timer = null;
  10392. }, rate);
  10393. }
  10394. };
  10395. return {
  10396. cancel: cancel,
  10397. throttle: throttle
  10398. };
  10399. };
  10400. var last = function (fn, rate) {
  10401. var timer = null;
  10402. var cancel = function () {
  10403. if (timer !== null) {
  10404. domGlobals.clearTimeout(timer);
  10405. timer = null;
  10406. }
  10407. };
  10408. var throttle = function () {
  10409. var args = [];
  10410. for (var _i = 0; _i < arguments.length; _i++) {
  10411. args[_i] = arguments[_i];
  10412. }
  10413. if (timer !== null) {
  10414. domGlobals.clearTimeout(timer);
  10415. }
  10416. timer = domGlobals.setTimeout(function () {
  10417. fn.apply(null, args);
  10418. timer = null;
  10419. }, rate);
  10420. };
  10421. return {
  10422. cancel: cancel,
  10423. throttle: throttle
  10424. };
  10425. };
  10426. var sketch$9 = function (onView, translate) {
  10427. var memIcon = record(Container.sketch({
  10428. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10429. containerBehaviours: derive$1([Toggling.config({
  10430. toggleClass: Styles.resolve('mask-tap-icon-selected'),
  10431. toggleOnExecute: false
  10432. })])
  10433. }));
  10434. var onViewThrottle = first$1(onView, 200);
  10435. return Container.sketch({
  10436. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10437. components: [Container.sketch({
  10438. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10439. components: [Button.sketch({
  10440. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10441. components: [memIcon.asSpec()],
  10442. action: function (button) {
  10443. onViewThrottle.throttle();
  10444. },
  10445. buttonBehaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('mask-tap-icon-selected') })])
  10446. })]
  10447. })]
  10448. });
  10449. };
  10450. var TapToEditMask = { sketch: sketch$9 };
  10451. var MobileSchema = objOf([
  10452. strictObjOf('editor', [
  10453. strict$1('getFrame'),
  10454. option('getBody'),
  10455. option('getDoc'),
  10456. option('getWin'),
  10457. option('getSelection'),
  10458. option('setSelection'),
  10459. option('clearSelection'),
  10460. option('cursorSaver'),
  10461. option('onKeyup'),
  10462. option('onNodeChanged'),
  10463. option('getCursorBox'),
  10464. strict$1('onDomChanged'),
  10465. defaulted$1('onTouchContent', noop),
  10466. defaulted$1('onTapContent', noop),
  10467. defaulted$1('onTouchToolstrip', noop),
  10468. defaulted$1('onScrollToCursor', constant({ unbind: noop })),
  10469. defaulted$1('onScrollToElement', constant({ unbind: noop })),
  10470. defaulted$1('onToEditing', constant({ unbind: noop })),
  10471. defaulted$1('onToReading', constant({ unbind: noop })),
  10472. defaulted$1('onToolbarScrollStart', identity)
  10473. ]),
  10474. strict$1('socket'),
  10475. strict$1('toolstrip'),
  10476. strict$1('dropup'),
  10477. strict$1('toolbar'),
  10478. strict$1('container'),
  10479. strict$1('alloy'),
  10480. state$1('win', function (spec) {
  10481. return owner(spec.socket).dom().defaultView;
  10482. }),
  10483. state$1('body', function (spec) {
  10484. return Element.fromDom(spec.socket.dom().ownerDocument.body);
  10485. }),
  10486. defaulted$1('translate', identity),
  10487. defaulted$1('setReadOnly', noop),
  10488. defaulted$1('readOnlyOnInit', constant(true))
  10489. ]);
  10490. var produce = function (raw) {
  10491. var mobile = asRawOrDie('Getting AndroidWebapp schema', MobileSchema, raw);
  10492. set$3(mobile.toolstrip, 'width', '100%');
  10493. var onTap = function () {
  10494. mobile.setReadOnly(mobile.readOnlyOnInit());
  10495. mode.enter();
  10496. };
  10497. var mask = build$1(TapToEditMask.sketch(onTap, mobile.translate));
  10498. mobile.alloy.add(mask);
  10499. var maskApi = {
  10500. show: function () {
  10501. mobile.alloy.add(mask);
  10502. },
  10503. hide: function () {
  10504. mobile.alloy.remove(mask);
  10505. }
  10506. };
  10507. append(mobile.container, mask.element());
  10508. var mode = AndroidMode.create(mobile, maskApi);
  10509. return {
  10510. setReadOnly: mobile.setReadOnly,
  10511. refreshStructure: noop,
  10512. enter: mode.enter,
  10513. exit: mode.exit,
  10514. destroy: noop
  10515. };
  10516. };
  10517. var AndroidWebapp = { produce: produce };
  10518. var schema$e = constant([
  10519. strict$1('dom'),
  10520. defaulted$1('shell', true),
  10521. field$1('toolbarBehaviours', [Replacing])
  10522. ]);
  10523. var enhanceGroups = function () {
  10524. return { behaviours: derive$1([Replacing.config({})]) };
  10525. };
  10526. var parts$2 = constant([optional({
  10527. name: 'groups',
  10528. overrides: enhanceGroups
  10529. })]);
  10530. var factory$4 = function (detail, components, spec, _externals) {
  10531. var setGroups = function (toolbar, groups) {
  10532. getGroupContainer(toolbar).fold(function () {
  10533. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10534. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10535. }, function (container) {
  10536. Replacing.set(container, groups);
  10537. });
  10538. };
  10539. var getGroupContainer = function (component) {
  10540. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  10541. };
  10542. var extra = detail.shell ? {
  10543. behaviours: [Replacing.config({})],
  10544. components: []
  10545. } : {
  10546. behaviours: [],
  10547. components: components
  10548. };
  10549. return {
  10550. uid: detail.uid,
  10551. dom: detail.dom,
  10552. components: extra.components,
  10553. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10554. apis: { setGroups: setGroups },
  10555. domModification: { attributes: { role: 'group' } }
  10556. };
  10557. };
  10558. var Toolbar = composite$1({
  10559. name: 'Toolbar',
  10560. configFields: schema$e(),
  10561. partFields: parts$2(),
  10562. factory: factory$4,
  10563. apis: {
  10564. setGroups: function (apis, toolbar, groups) {
  10565. apis.setGroups(toolbar, groups);
  10566. }
  10567. }
  10568. });
  10569. var schema$f = constant([
  10570. strict$1('items'),
  10571. markers(['itemSelector']),
  10572. field$1('tgroupBehaviours', [Keying])
  10573. ]);
  10574. var parts$3 = constant([group({
  10575. name: 'items',
  10576. unit: 'item'
  10577. })]);
  10578. var factory$5 = function (detail, components, spec, _externals) {
  10579. return {
  10580. uid: detail.uid,
  10581. dom: detail.dom,
  10582. components: components,
  10583. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10584. mode: 'flow',
  10585. selector: detail.markers.itemSelector
  10586. })]),
  10587. domModification: { attributes: { role: 'toolbar' } }
  10588. };
  10589. };
  10590. var ToolbarGroup = composite$1({
  10591. name: 'ToolbarGroup',
  10592. configFields: schema$f(),
  10593. partFields: parts$3(),
  10594. factory: factory$5
  10595. });
  10596. var dataHorizontal = 'data-' + Styles.resolve('horizontal-scroll');
  10597. var canScrollVertically = function (container) {
  10598. container.dom().scrollTop = 1;
  10599. var result = container.dom().scrollTop !== 0;
  10600. container.dom().scrollTop = 0;
  10601. return result;
  10602. };
  10603. var canScrollHorizontally = function (container) {
  10604. container.dom().scrollLeft = 1;
  10605. var result = container.dom().scrollLeft !== 0;
  10606. container.dom().scrollLeft = 0;
  10607. return result;
  10608. };
  10609. var hasVerticalScroll = function (container) {
  10610. return container.dom().scrollTop > 0 || canScrollVertically(container);
  10611. };
  10612. var hasHorizontalScroll = function (container) {
  10613. return container.dom().scrollLeft > 0 || canScrollHorizontally(container);
  10614. };
  10615. var markAsHorizontal = function (container) {
  10616. set(container, dataHorizontal, 'true');
  10617. };
  10618. var hasScroll = function (container) {
  10619. return get$1(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10620. };
  10621. var exclusive = function (scope, selector) {
  10622. return bind$3(scope, 'touchmove', function (event) {
  10623. closest$2(event.target(), selector).filter(hasScroll).fold(function () {
  10624. event.raw().preventDefault();
  10625. }, noop);
  10626. });
  10627. };
  10628. var Scrollables = {
  10629. exclusive: exclusive,
  10630. markAsHorizontal: markAsHorizontal
  10631. };
  10632. function ScrollingToolbar () {
  10633. var makeGroup = function (gSpec) {
  10634. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10635. return {
  10636. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10637. tgroupBehaviours: derive$1([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, simulatedEvent) {
  10638. set$3(component.element(), 'overflow-x', 'auto');
  10639. Scrollables.markAsHorizontal(component.element());
  10640. Scrollable.register(component.element());
  10641. })] : [])]),
  10642. components: [Container.sketch({ components: [ToolbarGroup.parts().items({})] })],
  10643. markers: { itemSelector: '.' + Styles.resolve('toolbar-group-item') },
  10644. items: gSpec.items
  10645. };
  10646. };
  10647. var toolbar = build$1(Toolbar.sketch({
  10648. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10649. components: [Toolbar.parts().groups({})],
  10650. toolbarBehaviours: derive$1([
  10651. Toggling.config({
  10652. toggleClass: Styles.resolve('context-toolbar'),
  10653. toggleOnExecute: false,
  10654. aria: { mode: 'none' }
  10655. }),
  10656. Keying.config({ mode: 'cyclic' })
  10657. ]),
  10658. shell: true
  10659. }));
  10660. var wrapper = build$1(Container.sketch({
  10661. dom: { classes: [Styles.resolve('toolstrip')] },
  10662. components: [premade$1(toolbar)],
  10663. containerBehaviours: derive$1([Toggling.config({
  10664. toggleClass: Styles.resolve('android-selection-context-toolbar'),
  10665. toggleOnExecute: false
  10666. })])
  10667. }));
  10668. var resetGroups = function () {
  10669. Toolbar.setGroups(toolbar, initGroups.get());
  10670. Toggling.off(toolbar);
  10671. };
  10672. var initGroups = Cell([]);
  10673. var setGroups = function (gs) {
  10674. initGroups.set(gs);
  10675. resetGroups();
  10676. };
  10677. var createGroups = function (gs) {
  10678. return map$1(gs, compose(ToolbarGroup.sketch, makeGroup));
  10679. };
  10680. var refresh = function () {
  10681. };
  10682. var setContextToolbar = function (gs) {
  10683. Toggling.on(toolbar);
  10684. Toolbar.setGroups(toolbar, gs);
  10685. };
  10686. var restoreToolbar = function () {
  10687. if (Toggling.isOn(toolbar)) {
  10688. resetGroups();
  10689. }
  10690. };
  10691. var focus = function () {
  10692. Keying.focusIn(toolbar);
  10693. };
  10694. return {
  10695. wrapper: constant(wrapper),
  10696. toolbar: constant(toolbar),
  10697. createGroups: createGroups,
  10698. setGroups: setGroups,
  10699. setContextToolbar: setContextToolbar,
  10700. restoreToolbar: restoreToolbar,
  10701. refresh: refresh,
  10702. focus: focus
  10703. };
  10704. }
  10705. var makeEditSwitch = function (webapp) {
  10706. return build$1(Button.sketch({
  10707. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10708. action: function () {
  10709. webapp.run(function (w) {
  10710. w.setReadOnly(false);
  10711. });
  10712. }
  10713. }));
  10714. };
  10715. var makeSocket = function () {
  10716. return build$1(Container.sketch({
  10717. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10718. components: [],
  10719. containerBehaviours: derive$1([Replacing.config({})])
  10720. }));
  10721. };
  10722. var showEdit = function (socket, switchToEdit) {
  10723. Replacing.append(socket, premade$1(switchToEdit));
  10724. };
  10725. var hideEdit = function (socket, switchToEdit) {
  10726. Replacing.remove(socket, switchToEdit);
  10727. };
  10728. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10729. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10730. swap(root);
  10731. var f = readOnly ? showEdit : hideEdit;
  10732. f(socket, switchToEdit);
  10733. };
  10734. var CommonRealm = {
  10735. makeEditSwitch: makeEditSwitch,
  10736. makeSocket: makeSocket,
  10737. updateMode: updateMode
  10738. };
  10739. var getAnimationRoot = function (component, slideConfig) {
  10740. return slideConfig.getAnimationRoot.fold(function () {
  10741. return component.element();
  10742. }, function (get) {
  10743. return get(component);
  10744. });
  10745. };
  10746. var getDimensionProperty = function (slideConfig) {
  10747. return slideConfig.dimension.property;
  10748. };
  10749. var getDimension = function (slideConfig, elem) {
  10750. return slideConfig.dimension.getDimension(elem);
  10751. };
  10752. var disableTransitions = function (component, slideConfig) {
  10753. var root = getAnimationRoot(component, slideConfig);
  10754. remove$6(root, [
  10755. slideConfig.shrinkingClass,
  10756. slideConfig.growingClass
  10757. ]);
  10758. };
  10759. var setShrunk = function (component, slideConfig) {
  10760. remove$4(component.element(), slideConfig.openClass);
  10761. add$2(component.element(), slideConfig.closedClass);
  10762. set$3(component.element(), getDimensionProperty(slideConfig), '0px');
  10763. reflow(component.element());
  10764. };
  10765. var setGrown = function (component, slideConfig) {
  10766. remove$4(component.element(), slideConfig.closedClass);
  10767. add$2(component.element(), slideConfig.openClass);
  10768. remove$5(component.element(), getDimensionProperty(slideConfig));
  10769. };
  10770. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10771. slideState.setCollapsed();
  10772. set$3(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  10773. reflow(component.element());
  10774. disableTransitions(component, slideConfig);
  10775. setShrunk(component, slideConfig);
  10776. slideConfig.onStartShrink(component);
  10777. slideConfig.onShrunk(component);
  10778. };
  10779. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10780. var size = calculatedSize.getOrThunk(function () {
  10781. return getDimension(slideConfig, component.element());
  10782. });
  10783. slideState.setCollapsed();
  10784. set$3(component.element(), getDimensionProperty(slideConfig), size);
  10785. reflow(component.element());
  10786. var root = getAnimationRoot(component, slideConfig);
  10787. remove$4(root, slideConfig.growingClass);
  10788. add$2(root, slideConfig.shrinkingClass);
  10789. setShrunk(component, slideConfig);
  10790. slideConfig.onStartShrink(component);
  10791. };
  10792. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10793. var size = getDimension(slideConfig, component.element());
  10794. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10795. shrinker(component, slideConfig, slideState, Option.some(size));
  10796. };
  10797. var doStartGrow = function (component, slideConfig, slideState) {
  10798. var root = getAnimationRoot(component, slideConfig);
  10799. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  10800. var beforeSize = getDimension(slideConfig, component.element());
  10801. setGrown(component, slideConfig);
  10802. var fullSize = getDimension(slideConfig, component.element());
  10803. var startPartialGrow = function () {
  10804. set$3(component.element(), getDimensionProperty(slideConfig), beforeSize);
  10805. reflow(component.element());
  10806. };
  10807. var startCompleteGrow = function () {
  10808. setShrunk(component, slideConfig);
  10809. };
  10810. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  10811. setStartSize();
  10812. remove$4(root, slideConfig.shrinkingClass);
  10813. add$2(root, slideConfig.growingClass);
  10814. setGrown(component, slideConfig);
  10815. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  10816. slideState.setExpanded();
  10817. slideConfig.onStartGrow(component);
  10818. };
  10819. var refresh = function (component, slideConfig, slideState) {
  10820. if (slideState.isExpanded()) {
  10821. remove$5(component.element(), getDimensionProperty(slideConfig));
  10822. var fullSize = getDimension(slideConfig, component.element());
  10823. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  10824. }
  10825. };
  10826. var grow = function (component, slideConfig, slideState) {
  10827. if (!slideState.isExpanded()) {
  10828. doStartGrow(component, slideConfig, slideState);
  10829. }
  10830. };
  10831. var shrink = function (component, slideConfig, slideState) {
  10832. if (slideState.isExpanded()) {
  10833. doStartSmartShrink(component, slideConfig, slideState);
  10834. }
  10835. };
  10836. var immediateShrink = function (component, slideConfig, slideState) {
  10837. if (slideState.isExpanded()) {
  10838. doImmediateShrink(component, slideConfig, slideState, Option.none());
  10839. }
  10840. };
  10841. var hasGrown = function (component, slideConfig, slideState) {
  10842. return slideState.isExpanded();
  10843. };
  10844. var hasShrunk = function (component, slideConfig, slideState) {
  10845. return slideState.isCollapsed();
  10846. };
  10847. var isGrowing = function (component, slideConfig, slideState) {
  10848. var root = getAnimationRoot(component, slideConfig);
  10849. return has$2(root, slideConfig.growingClass) === true;
  10850. };
  10851. var isShrinking = function (component, slideConfig, slideState) {
  10852. var root = getAnimationRoot(component, slideConfig);
  10853. return has$2(root, slideConfig.shrinkingClass) === true;
  10854. };
  10855. var isTransitioning = function (component, slideConfig, slideState) {
  10856. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  10857. };
  10858. var toggleGrow = function (component, slideConfig, slideState) {
  10859. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  10860. f(component, slideConfig, slideState);
  10861. };
  10862. var SlidingApis = /*#__PURE__*/Object.freeze({
  10863. __proto__: null,
  10864. refresh: refresh,
  10865. grow: grow,
  10866. shrink: shrink,
  10867. immediateShrink: immediateShrink,
  10868. hasGrown: hasGrown,
  10869. hasShrunk: hasShrunk,
  10870. isGrowing: isGrowing,
  10871. isShrinking: isShrinking,
  10872. isTransitioning: isTransitioning,
  10873. toggleGrow: toggleGrow,
  10874. disableTransitions: disableTransitions
  10875. });
  10876. var exhibit$5 = function (base, slideConfig) {
  10877. var expanded = slideConfig.expanded;
  10878. return expanded ? nu$5({
  10879. classes: [slideConfig.openClass],
  10880. styles: {}
  10881. }) : nu$5({
  10882. classes: [slideConfig.closedClass],
  10883. styles: wrap$1(slideConfig.dimension.property, '0px')
  10884. });
  10885. };
  10886. var events$a = function (slideConfig, slideState) {
  10887. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  10888. var raw = simulatedEvent.event().raw();
  10889. if (raw.propertyName === slideConfig.dimension.property) {
  10890. disableTransitions(component, slideConfig);
  10891. if (slideState.isExpanded()) {
  10892. remove$5(component.element(), slideConfig.dimension.property);
  10893. }
  10894. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  10895. notify(component);
  10896. }
  10897. })]);
  10898. };
  10899. var ActiveSliding = /*#__PURE__*/Object.freeze({
  10900. __proto__: null,
  10901. exhibit: exhibit$5,
  10902. events: events$a
  10903. });
  10904. var SlidingSchema = [
  10905. strict$1('closedClass'),
  10906. strict$1('openClass'),
  10907. strict$1('shrinkingClass'),
  10908. strict$1('growingClass'),
  10909. option('getAnimationRoot'),
  10910. onHandler('onShrunk'),
  10911. onHandler('onStartShrink'),
  10912. onHandler('onGrown'),
  10913. onHandler('onStartGrow'),
  10914. defaulted$1('expanded', false),
  10915. strictOf('dimension', choose$1('property', {
  10916. width: [
  10917. output('property', 'width'),
  10918. output('getDimension', function (elem) {
  10919. return get$7(elem) + 'px';
  10920. })
  10921. ],
  10922. height: [
  10923. output('property', 'height'),
  10924. output('getDimension', function (elem) {
  10925. return get$5(elem) + 'px';
  10926. })
  10927. ]
  10928. }))
  10929. ];
  10930. var init$4 = function (spec) {
  10931. var state = Cell(spec.expanded);
  10932. var readState = function () {
  10933. return 'expanded: ' + state.get();
  10934. };
  10935. return nu$6({
  10936. isExpanded: function () {
  10937. return state.get() === true;
  10938. },
  10939. isCollapsed: function () {
  10940. return state.get() === false;
  10941. },
  10942. setCollapsed: curry(state.set, false),
  10943. setExpanded: curry(state.set, true),
  10944. readState: readState
  10945. });
  10946. };
  10947. var SlidingState = /*#__PURE__*/Object.freeze({
  10948. __proto__: null,
  10949. init: init$4
  10950. });
  10951. var Sliding = create$1({
  10952. fields: SlidingSchema,
  10953. name: 'sliding',
  10954. active: ActiveSliding,
  10955. apis: SlidingApis,
  10956. state: SlidingState
  10957. });
  10958. var build$2 = function (refresh, scrollIntoView) {
  10959. var dropup = build$1(Container.sketch({
  10960. dom: {
  10961. tag: 'div',
  10962. classes: [Styles.resolve('dropup')]
  10963. },
  10964. components: [],
  10965. containerBehaviours: derive$1([
  10966. Replacing.config({}),
  10967. Sliding.config({
  10968. closedClass: Styles.resolve('dropup-closed'),
  10969. openClass: Styles.resolve('dropup-open'),
  10970. shrinkingClass: Styles.resolve('dropup-shrinking'),
  10971. growingClass: Styles.resolve('dropup-growing'),
  10972. dimension: { property: 'height' },
  10973. onShrunk: function (component) {
  10974. refresh();
  10975. scrollIntoView();
  10976. Replacing.set(component, []);
  10977. },
  10978. onGrown: function (component) {
  10979. refresh();
  10980. scrollIntoView();
  10981. }
  10982. }),
  10983. Receivers.orientation(function (component, data) {
  10984. disappear(noop);
  10985. })
  10986. ])
  10987. }));
  10988. var appear = function (menu, update, component) {
  10989. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  10990. domGlobals.window.requestAnimationFrame(function () {
  10991. update(component);
  10992. Replacing.set(dropup, [menu()]);
  10993. Sliding.grow(dropup);
  10994. });
  10995. }
  10996. };
  10997. var disappear = function (onReadyToShrink) {
  10998. domGlobals.window.requestAnimationFrame(function () {
  10999. onReadyToShrink();
  11000. Sliding.shrink(dropup);
  11001. });
  11002. };
  11003. return {
  11004. appear: appear,
  11005. disappear: disappear,
  11006. component: constant(dropup),
  11007. element: dropup.element
  11008. };
  11009. };
  11010. var closest$3 = function (scope, selector, isRoot) {
  11011. return closest$2(scope, selector, isRoot).isSome();
  11012. };
  11013. var isDangerous = function (event) {
  11014. var keyEv = event.raw();
  11015. return keyEv.which === BACKSPACE()[0] && !contains([
  11016. 'input',
  11017. 'textarea'
  11018. ], name(event.target())) && !closest$3(event.target(), '[contenteditable="true"]');
  11019. };
  11020. var isFirefox = detect$3().browser.isFirefox();
  11021. var settingsSchema = objOfOnly([
  11022. strictFunction('triggerEvent'),
  11023. defaulted$1('stopBackspace', true)
  11024. ]);
  11025. var bindFocus = function (container, handler) {
  11026. if (isFirefox) {
  11027. return capture$1(container, 'focus', handler);
  11028. } else {
  11029. return bind$3(container, 'focusin', handler);
  11030. }
  11031. };
  11032. var bindBlur = function (container, handler) {
  11033. if (isFirefox) {
  11034. return capture$1(container, 'blur', handler);
  11035. } else {
  11036. return bind$3(container, 'focusout', handler);
  11037. }
  11038. };
  11039. var setup$2 = function (container, rawSettings) {
  11040. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  11041. var pointerEvents = [
  11042. 'touchstart',
  11043. 'touchmove',
  11044. 'touchend',
  11045. 'touchcancel',
  11046. 'gesturestart',
  11047. 'mousedown',
  11048. 'mouseup',
  11049. 'mouseover',
  11050. 'mousemove',
  11051. 'mouseout',
  11052. 'click'
  11053. ];
  11054. var tapEvent = monitor(settings);
  11055. var simpleEvents = map$1(pointerEvents.concat([
  11056. 'selectstart',
  11057. 'input',
  11058. 'contextmenu',
  11059. 'change',
  11060. 'transitionend',
  11061. 'drag',
  11062. 'dragstart',
  11063. 'dragend',
  11064. 'dragenter',
  11065. 'dragleave',
  11066. 'dragover',
  11067. 'drop',
  11068. 'keyup'
  11069. ]), function (type) {
  11070. return bind$3(container, type, function (event) {
  11071. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  11072. if (tapStopped) {
  11073. event.kill();
  11074. }
  11075. });
  11076. var stopped = settings.triggerEvent(type, event);
  11077. if (stopped) {
  11078. event.kill();
  11079. }
  11080. });
  11081. });
  11082. var pasteTimeout = Cell(Option.none());
  11083. var onPaste = bind$3(container, 'paste', function (event) {
  11084. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11085. if (tapStopped) {
  11086. event.kill();
  11087. }
  11088. });
  11089. var stopped = settings.triggerEvent('paste', event);
  11090. if (stopped) {
  11091. event.kill();
  11092. }
  11093. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11094. settings.triggerEvent(postPaste(), event);
  11095. }, 0)));
  11096. });
  11097. var onKeydown = bind$3(container, 'keydown', function (event) {
  11098. var stopped = settings.triggerEvent('keydown', event);
  11099. if (stopped) {
  11100. event.kill();
  11101. } else if (settings.stopBackspace === true && isDangerous(event)) {
  11102. event.prevent();
  11103. }
  11104. });
  11105. var onFocusIn = bindFocus(container, function (event) {
  11106. var stopped = settings.triggerEvent('focusin', event);
  11107. if (stopped) {
  11108. event.kill();
  11109. }
  11110. });
  11111. var focusoutTimeout = Cell(Option.none());
  11112. var onFocusOut = bindBlur(container, function (event) {
  11113. var stopped = settings.triggerEvent('focusout', event);
  11114. if (stopped) {
  11115. event.kill();
  11116. }
  11117. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11118. settings.triggerEvent(postBlur(), event);
  11119. }, 0)));
  11120. });
  11121. var unbind = function () {
  11122. each$1(simpleEvents, function (e) {
  11123. e.unbind();
  11124. });
  11125. onKeydown.unbind();
  11126. onFocusIn.unbind();
  11127. onFocusOut.unbind();
  11128. onPaste.unbind();
  11129. pasteTimeout.get().each(domGlobals.clearTimeout);
  11130. focusoutTimeout.get().each(domGlobals.clearTimeout);
  11131. };
  11132. return { unbind: unbind };
  11133. };
  11134. var derive$2 = function (rawEvent, rawTarget) {
  11135. var source = get(rawEvent, 'target').map(function (getTarget) {
  11136. return getTarget();
  11137. }).getOr(rawTarget);
  11138. return Cell(source);
  11139. };
  11140. var fromSource = function (event, source) {
  11141. var stopper = Cell(false);
  11142. var cutter = Cell(false);
  11143. var stop = function () {
  11144. stopper.set(true);
  11145. };
  11146. var cut = function () {
  11147. cutter.set(true);
  11148. };
  11149. return {
  11150. stop: stop,
  11151. cut: cut,
  11152. isStopped: stopper.get,
  11153. isCut: cutter.get,
  11154. event: constant(event),
  11155. setSource: source.set,
  11156. getSource: source.get
  11157. };
  11158. };
  11159. var fromExternal = function (event) {
  11160. var stopper = Cell(false);
  11161. var stop = function () {
  11162. stopper.set(true);
  11163. };
  11164. return {
  11165. stop: stop,
  11166. cut: noop,
  11167. isStopped: stopper.get,
  11168. isCut: constant(false),
  11169. event: constant(event),
  11170. setSource: die('Cannot set source of a broadcasted event'),
  11171. getSource: die('Cannot get source of a broadcasted event')
  11172. };
  11173. };
  11174. var adt$7 = Adt.generate([
  11175. { stopped: [] },
  11176. { resume: ['element'] },
  11177. { complete: [] }
  11178. ]);
  11179. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11180. var handler = lookup(eventType, target);
  11181. var simulatedEvent = fromSource(rawEvent, source);
  11182. return handler.fold(function () {
  11183. logger.logEventNoHandlers(eventType, target);
  11184. return adt$7.complete();
  11185. }, function (handlerInfo) {
  11186. var descHandler = handlerInfo.descHandler();
  11187. var eventHandler = getCurried(descHandler);
  11188. eventHandler(simulatedEvent);
  11189. if (simulatedEvent.isStopped()) {
  11190. logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose());
  11191. return adt$7.stopped();
  11192. } else if (simulatedEvent.isCut()) {
  11193. logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose());
  11194. return adt$7.complete();
  11195. } else {
  11196. return parent(handlerInfo.element()).fold(function () {
  11197. logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose());
  11198. return adt$7.complete();
  11199. }, function (parent) {
  11200. logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose());
  11201. return adt$7.resume(parent);
  11202. });
  11203. }
  11204. });
  11205. };
  11206. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11207. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  11208. return true;
  11209. }, function (parent) {
  11210. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11211. }, function () {
  11212. return false;
  11213. });
  11214. };
  11215. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11216. var source = derive$2(rawEvent, target);
  11217. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11218. };
  11219. var broadcast = function (listeners, rawEvent, logger) {
  11220. var simulatedEvent = fromExternal(rawEvent);
  11221. each$1(listeners, function (listener) {
  11222. var descHandler = listener.descHandler();
  11223. var handler = getCurried(descHandler);
  11224. handler(simulatedEvent);
  11225. });
  11226. return simulatedEvent.isStopped();
  11227. };
  11228. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11229. var rawTarget = rawEvent.target();
  11230. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  11231. };
  11232. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11233. var source = derive$2(rawEvent, rawTarget);
  11234. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11235. };
  11236. var eventHandler = Immutable('element', 'descHandler');
  11237. var broadcastHandler = function (id, handler) {
  11238. return {
  11239. id: constant(id),
  11240. descHandler: constant(handler)
  11241. };
  11242. };
  11243. function EventRegistry () {
  11244. var registry = {};
  11245. var registerId = function (extraArgs, id, events) {
  11246. each(events, function (v, k) {
  11247. var handlers = registry[k] !== undefined ? registry[k] : {};
  11248. handlers[id] = curryArgs(v, extraArgs);
  11249. registry[k] = handlers;
  11250. });
  11251. };
  11252. var findHandler = function (handlers, elem) {
  11253. return read$2(elem).fold(function () {
  11254. return Option.none();
  11255. }, function (id) {
  11256. return handlers.bind(function (h) {
  11257. return get(h, id);
  11258. }).map(function (descHandler) {
  11259. return eventHandler(elem, descHandler);
  11260. });
  11261. });
  11262. };
  11263. var filterByType = function (type) {
  11264. return get(registry, type).map(function (handlers) {
  11265. return mapToArray(handlers, function (f, id) {
  11266. return broadcastHandler(id, f);
  11267. });
  11268. }).getOr([]);
  11269. };
  11270. var find = function (isAboveRoot, type, target) {
  11271. var handlers = get(registry, type);
  11272. return closest(target, function (elem) {
  11273. return findHandler(handlers, elem);
  11274. }, isAboveRoot);
  11275. };
  11276. var unregisterId = function (id) {
  11277. each(registry, function (handlersById, eventName) {
  11278. if (handlersById.hasOwnProperty(id)) {
  11279. delete handlersById[id];
  11280. }
  11281. });
  11282. };
  11283. return {
  11284. registerId: registerId,
  11285. unregisterId: unregisterId,
  11286. filterByType: filterByType,
  11287. find: find
  11288. };
  11289. }
  11290. function Registry () {
  11291. var events = EventRegistry();
  11292. var components = {};
  11293. var readOrTag = function (component) {
  11294. var elem = component.element();
  11295. return read$2(elem).fold(function () {
  11296. return write('uid-', component.element());
  11297. }, function (uid) {
  11298. return uid;
  11299. });
  11300. };
  11301. var failOnDuplicate = function (component, tagId) {
  11302. var conflict = components[tagId];
  11303. if (conflict === component) {
  11304. unregister(component);
  11305. } else {
  11306. 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');
  11307. }
  11308. };
  11309. var register = function (component) {
  11310. var tagId = readOrTag(component);
  11311. if (hasNonNullableKey(components, tagId)) {
  11312. failOnDuplicate(component, tagId);
  11313. }
  11314. var extraArgs = [component];
  11315. events.registerId(extraArgs, tagId, component.events());
  11316. components[tagId] = component;
  11317. };
  11318. var unregister = function (component) {
  11319. read$2(component.element()).each(function (tagId) {
  11320. delete components[tagId];
  11321. events.unregisterId(tagId);
  11322. });
  11323. };
  11324. var filter = function (type) {
  11325. return events.filterByType(type);
  11326. };
  11327. var find = function (isAboveRoot, type, target) {
  11328. return events.find(isAboveRoot, type, target);
  11329. };
  11330. var getById = function (id) {
  11331. return get(components, id);
  11332. };
  11333. return {
  11334. find: find,
  11335. filter: filter,
  11336. register: register,
  11337. unregister: unregister,
  11338. getById: getById
  11339. };
  11340. }
  11341. var takeover = function (root) {
  11342. var isAboveRoot = function (el) {
  11343. return parent(root.element()).fold(function () {
  11344. return true;
  11345. }, function (parent) {
  11346. return eq(el, parent);
  11347. });
  11348. };
  11349. var registry = Registry();
  11350. var lookup = function (eventName, target) {
  11351. return registry.find(isAboveRoot, eventName, target);
  11352. };
  11353. var domEvents = setup$2(root.element(), {
  11354. triggerEvent: function (eventName, event) {
  11355. return monitorEvent(eventName, event.target(), function (logger) {
  11356. return triggerUntilStopped(lookup, eventName, event, logger);
  11357. });
  11358. }
  11359. });
  11360. var systemApi = {
  11361. debugInfo: constant('real'),
  11362. triggerEvent: function (eventName, target, data) {
  11363. monitorEvent(eventName, target, function (logger) {
  11364. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11365. });
  11366. },
  11367. triggerFocus: function (target, originator) {
  11368. read$2(target).fold(function () {
  11369. focus$1(target);
  11370. }, function (_alloyId) {
  11371. monitorEvent(focus(), target, function (logger) {
  11372. triggerHandler(lookup, focus(), {
  11373. originator: constant(originator),
  11374. kill: noop,
  11375. prevent: noop,
  11376. target: constant(target)
  11377. }, target, logger);
  11378. return false;
  11379. });
  11380. });
  11381. },
  11382. triggerEscape: function (comp, simulatedEvent) {
  11383. systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
  11384. },
  11385. getByUid: function (uid) {
  11386. return getByUid(uid);
  11387. },
  11388. getByDom: function (elem) {
  11389. return getByDom(elem);
  11390. },
  11391. build: build$1,
  11392. addToGui: function (c) {
  11393. add(c);
  11394. },
  11395. removeFromGui: function (c) {
  11396. remove$1(c);
  11397. },
  11398. addToWorld: function (c) {
  11399. addToWorld(c);
  11400. },
  11401. removeFromWorld: function (c) {
  11402. removeFromWorld(c);
  11403. },
  11404. broadcast: function (message) {
  11405. broadcast$1(message);
  11406. },
  11407. broadcastOn: function (channels, message) {
  11408. broadcastOn(channels, message);
  11409. },
  11410. broadcastEvent: function (eventName, event) {
  11411. broadcastEvent(eventName, event);
  11412. },
  11413. isConnected: constant(true)
  11414. };
  11415. var addToWorld = function (component) {
  11416. component.connect(systemApi);
  11417. if (!isText(component.element())) {
  11418. registry.register(component);
  11419. each$1(component.components(), addToWorld);
  11420. systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
  11421. }
  11422. };
  11423. var removeFromWorld = function (component) {
  11424. if (!isText(component.element())) {
  11425. each$1(component.components(), removeFromWorld);
  11426. registry.unregister(component);
  11427. }
  11428. component.disconnect();
  11429. };
  11430. var add = function (component) {
  11431. attach$1(root, component);
  11432. };
  11433. var remove$1 = function (component) {
  11434. detach(component);
  11435. };
  11436. var destroy = function () {
  11437. domEvents.unbind();
  11438. remove(root.element());
  11439. };
  11440. var broadcastData = function (data) {
  11441. var receivers = registry.filter(receive());
  11442. each$1(receivers, function (receiver) {
  11443. var descHandler = receiver.descHandler();
  11444. var handler = getCurried(descHandler);
  11445. handler(data);
  11446. });
  11447. };
  11448. var broadcast$1 = function (message) {
  11449. broadcastData({
  11450. universal: constant(true),
  11451. data: constant(message)
  11452. });
  11453. };
  11454. var broadcastOn = function (channels, message) {
  11455. broadcastData({
  11456. universal: constant(false),
  11457. channels: constant(channels),
  11458. data: constant(message)
  11459. });
  11460. };
  11461. var broadcastEvent = function (eventName, event) {
  11462. var listeners = registry.filter(eventName);
  11463. return broadcast(listeners, event);
  11464. };
  11465. var getByUid = function (uid) {
  11466. return registry.getById(uid).fold(function () {
  11467. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11468. }, Result.value);
  11469. };
  11470. var getByDom = function (elem) {
  11471. var uid = read$2(elem).getOr('not found');
  11472. return getByUid(uid);
  11473. };
  11474. addToWorld(root);
  11475. return {
  11476. root: constant(root),
  11477. element: root.element,
  11478. destroy: destroy,
  11479. add: add,
  11480. remove: remove$1,
  11481. getByUid: getByUid,
  11482. getByDom: getByDom,
  11483. addToWorld: addToWorld,
  11484. removeFromWorld: removeFromWorld,
  11485. broadcast: broadcast$1,
  11486. broadcastOn: broadcastOn,
  11487. broadcastEvent: broadcastEvent
  11488. };
  11489. };
  11490. var READ_ONLY_MODE_CLASS = constant(Styles.resolve('readonly-mode'));
  11491. var EDIT_MODE_CLASS = constant(Styles.resolve('edit-mode'));
  11492. function OuterContainer (spec) {
  11493. var root = build$1(Container.sketch({
  11494. dom: { classes: [Styles.resolve('outer-container')].concat(spec.classes) },
  11495. containerBehaviours: derive$1([Swapping.config({
  11496. alpha: READ_ONLY_MODE_CLASS(),
  11497. omega: EDIT_MODE_CLASS()
  11498. })])
  11499. }));
  11500. return takeover(root);
  11501. }
  11502. function AndroidRealm (scrollIntoView) {
  11503. var alloy = OuterContainer({ classes: [Styles.resolve('android-container')] });
  11504. var toolbar = ScrollingToolbar();
  11505. var webapp = api$2();
  11506. var switchToEdit = CommonRealm.makeEditSwitch(webapp);
  11507. var socket = CommonRealm.makeSocket();
  11508. var dropup = build$2(noop, scrollIntoView);
  11509. alloy.add(toolbar.wrapper());
  11510. alloy.add(socket);
  11511. alloy.add(dropup.component());
  11512. var setToolbarGroups = function (rawGroups) {
  11513. var groups = toolbar.createGroups(rawGroups);
  11514. toolbar.setGroups(groups);
  11515. };
  11516. var setContextToolbar = function (rawGroups) {
  11517. var groups = toolbar.createGroups(rawGroups);
  11518. toolbar.setContextToolbar(groups);
  11519. };
  11520. var focusToolbar = function () {
  11521. toolbar.focus();
  11522. };
  11523. var restoreToolbar = function () {
  11524. toolbar.restoreToolbar();
  11525. };
  11526. var init = function (spec) {
  11527. webapp.set(AndroidWebapp.produce(spec));
  11528. };
  11529. var exit = function () {
  11530. webapp.run(function (w) {
  11531. w.exit();
  11532. Replacing.remove(socket, switchToEdit);
  11533. });
  11534. };
  11535. var updateMode = function (readOnly) {
  11536. CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
  11537. };
  11538. return {
  11539. system: constant(alloy),
  11540. element: alloy.element,
  11541. init: init,
  11542. exit: exit,
  11543. setToolbarGroups: setToolbarGroups,
  11544. setContextToolbar: setContextToolbar,
  11545. focusToolbar: focusToolbar,
  11546. restoreToolbar: restoreToolbar,
  11547. updateMode: updateMode,
  11548. socket: constant(socket),
  11549. dropup: constant(dropup)
  11550. };
  11551. }
  11552. var input$1 = function (parent, operation) {
  11553. var input = Element.fromTag('input');
  11554. setAll$1(input, {
  11555. opacity: '0',
  11556. position: 'absolute',
  11557. top: '-1000px',
  11558. left: '-1000px'
  11559. });
  11560. append(parent, input);
  11561. focus$1(input);
  11562. operation(input);
  11563. remove(input);
  11564. };
  11565. var CaptureBin = { input: input$1 };
  11566. var refreshInput = function (input) {
  11567. var start = input.dom().selectionStart;
  11568. var end = input.dom().selectionEnd;
  11569. var dir = input.dom().selectionDirection;
  11570. global$4.setTimeout(function () {
  11571. input.dom().setSelectionRange(start, end, dir);
  11572. focus$1(input);
  11573. }, 50);
  11574. };
  11575. var refresh$1 = function (winScope) {
  11576. var sel = winScope.getSelection();
  11577. if (sel.rangeCount > 0) {
  11578. var br = sel.getRangeAt(0);
  11579. var r = winScope.document.createRange();
  11580. r.setStart(br.startContainer, br.startOffset);
  11581. r.setEnd(br.endContainer, br.endOffset);
  11582. sel.removeAllRanges();
  11583. sel.addRange(r);
  11584. }
  11585. };
  11586. var CursorRefresh = {
  11587. refreshInput: refreshInput,
  11588. refresh: refresh$1
  11589. };
  11590. var resume$1 = function (cWin, frame) {
  11591. active().each(function (active) {
  11592. if (!eq(active, frame)) {
  11593. blur(active);
  11594. }
  11595. });
  11596. cWin.focus();
  11597. focus$1(Element.fromDom(cWin.document.body));
  11598. CursorRefresh.refresh(cWin);
  11599. };
  11600. var ResumeEditing$1 = { resume: resume$1 };
  11601. var stubborn = function (outerBody, cWin, page, frame) {
  11602. var toEditing = function () {
  11603. ResumeEditing$1.resume(cWin, frame);
  11604. };
  11605. var toReading = function () {
  11606. CaptureBin.input(outerBody, blur);
  11607. };
  11608. var captureInput = bind$3(page, 'keydown', function (evt) {
  11609. if (!contains([
  11610. 'input',
  11611. 'textarea'
  11612. ], name(evt.target()))) {
  11613. toEditing();
  11614. }
  11615. });
  11616. var onToolbarTouch = function () {
  11617. };
  11618. var destroy = function () {
  11619. captureInput.unbind();
  11620. };
  11621. return {
  11622. toReading: toReading,
  11623. toEditing: toEditing,
  11624. onToolbarTouch: onToolbarTouch,
  11625. destroy: destroy
  11626. };
  11627. };
  11628. var timid = function (outerBody, cWin, page, frame) {
  11629. var dismissKeyboard = function () {
  11630. blur(frame);
  11631. };
  11632. var onToolbarTouch = function () {
  11633. dismissKeyboard();
  11634. };
  11635. var toReading = function () {
  11636. dismissKeyboard();
  11637. };
  11638. var toEditing = function () {
  11639. ResumeEditing$1.resume(cWin, frame);
  11640. };
  11641. return {
  11642. toReading: toReading,
  11643. toEditing: toEditing,
  11644. onToolbarTouch: onToolbarTouch,
  11645. destroy: noop
  11646. };
  11647. };
  11648. var IosKeyboard = {
  11649. stubborn: stubborn,
  11650. timid: timid
  11651. };
  11652. var initEvents$1 = function (editorApi, iosApi, toolstrip, socket, dropup) {
  11653. var saveSelectionFirst = function () {
  11654. iosApi.run(function (api) {
  11655. api.highlightSelection();
  11656. });
  11657. };
  11658. var refreshIosSelection = function () {
  11659. iosApi.run(function (api) {
  11660. api.refreshSelection();
  11661. });
  11662. };
  11663. var scrollToY = function (yTop, height) {
  11664. var y = yTop - socket.dom().scrollTop;
  11665. iosApi.run(function (api) {
  11666. api.scrollIntoView(y, y + height);
  11667. });
  11668. };
  11669. var scrollToElement = function (target) {
  11670. scrollToY(iosApi, socket);
  11671. };
  11672. var scrollToCursor = function () {
  11673. editorApi.getCursorBox().each(function (box) {
  11674. scrollToY(box.top(), box.height());
  11675. });
  11676. };
  11677. var clearSelection = function () {
  11678. iosApi.run(function (api) {
  11679. api.clearSelection();
  11680. });
  11681. };
  11682. var clearAndRefresh = function () {
  11683. clearSelection();
  11684. refreshThrottle.throttle();
  11685. };
  11686. var refreshView = function () {
  11687. scrollToCursor();
  11688. iosApi.run(function (api) {
  11689. api.syncHeight();
  11690. });
  11691. };
  11692. var reposition = function () {
  11693. var toolbarHeight = get$5(toolstrip);
  11694. iosApi.run(function (api) {
  11695. api.setViewportOffset(toolbarHeight);
  11696. });
  11697. refreshIosSelection();
  11698. refreshView();
  11699. };
  11700. var toEditing = function () {
  11701. iosApi.run(function (api) {
  11702. api.toEditing();
  11703. });
  11704. };
  11705. var toReading = function () {
  11706. iosApi.run(function (api) {
  11707. api.toReading();
  11708. });
  11709. };
  11710. var onToolbarTouch = function (event) {
  11711. iosApi.run(function (api) {
  11712. api.onToolbarTouch(event);
  11713. });
  11714. };
  11715. var tapping = TappingEvent.monitor(editorApi);
  11716. var refreshThrottle = last(refreshView, 300);
  11717. var listeners = [
  11718. editorApi.onKeyup(clearAndRefresh),
  11719. editorApi.onNodeChanged(refreshIosSelection),
  11720. editorApi.onDomChanged(refreshThrottle.throttle),
  11721. editorApi.onDomChanged(refreshIosSelection),
  11722. editorApi.onScrollToCursor(function (tinyEvent) {
  11723. tinyEvent.preventDefault();
  11724. refreshThrottle.throttle();
  11725. }),
  11726. editorApi.onScrollToElement(function (event) {
  11727. scrollToElement(event.element());
  11728. }),
  11729. editorApi.onToEditing(toEditing),
  11730. editorApi.onToReading(toReading),
  11731. bind$3(editorApi.doc(), 'touchend', function (touchEvent) {
  11732. if (eq(editorApi.html(), touchEvent.target()) || eq(editorApi.body(), touchEvent.target())) ;
  11733. }),
  11734. bind$3(toolstrip, 'transitionend', function (transitionEvent) {
  11735. if (transitionEvent.raw().propertyName === 'height') {
  11736. reposition();
  11737. }
  11738. }),
  11739. capture$1(toolstrip, 'touchstart', function (touchEvent) {
  11740. saveSelectionFirst();
  11741. onToolbarTouch(touchEvent);
  11742. editorApi.onTouchToolstrip();
  11743. }),
  11744. bind$3(editorApi.body(), 'touchstart', function (evt) {
  11745. clearSelection();
  11746. editorApi.onTouchContent();
  11747. tapping.fireTouchstart(evt);
  11748. }),
  11749. tapping.onTouchmove(),
  11750. tapping.onTouchend(),
  11751. bind$3(editorApi.body(), 'click', function (event) {
  11752. event.kill();
  11753. }),
  11754. bind$3(toolstrip, 'touchmove', function () {
  11755. editorApi.onToolbarScrollStart();
  11756. })
  11757. ];
  11758. var destroy = function () {
  11759. each$1(listeners, function (l) {
  11760. l.unbind();
  11761. });
  11762. };
  11763. return { destroy: destroy };
  11764. };
  11765. var IosEvents = { initEvents: initEvents$1 };
  11766. function FakeSelection (win, frame) {
  11767. var doc = win.document;
  11768. var container = Element.fromTag('div');
  11769. add$2(container, Styles.resolve('unfocused-selections'));
  11770. append(Element.fromDom(doc.documentElement), container);
  11771. var onTouch = bind$3(container, 'touchstart', function (event) {
  11772. event.prevent();
  11773. ResumeEditing$1.resume(win, frame);
  11774. clear();
  11775. });
  11776. var make = function (rectangle) {
  11777. var span = Element.fromTag('span');
  11778. add$3(span, [
  11779. Styles.resolve('layer-editor'),
  11780. Styles.resolve('unfocused-selection')
  11781. ]);
  11782. setAll$1(span, {
  11783. left: rectangle.left() + 'px',
  11784. top: rectangle.top() + 'px',
  11785. width: rectangle.width() + 'px',
  11786. height: rectangle.height() + 'px'
  11787. });
  11788. return span;
  11789. };
  11790. var update = function () {
  11791. clear();
  11792. var rectangles = Rectangles.getRectangles(win);
  11793. var spans = map$1(rectangles, make);
  11794. append$1(container, spans);
  11795. };
  11796. var clear = function () {
  11797. empty(container);
  11798. };
  11799. var destroy = function () {
  11800. onTouch.unbind();
  11801. remove(container);
  11802. };
  11803. var isActive = function () {
  11804. return children(container).length > 0;
  11805. };
  11806. return {
  11807. update: update,
  11808. isActive: isActive,
  11809. destroy: destroy,
  11810. clear: clear
  11811. };
  11812. }
  11813. var exports$1 = {}, module = { exports: exports$1 };
  11814. (function (define, exports, module, require) {
  11815. (function (f) {
  11816. if (typeof exports === 'object' && typeof module !== 'undefined') {
  11817. module.exports = f();
  11818. } else if (typeof define === 'function' && define.amd) {
  11819. define([], f);
  11820. } else {
  11821. var g;
  11822. if (typeof window !== 'undefined') {
  11823. g = window;
  11824. } else if (typeof global !== 'undefined') {
  11825. g = global;
  11826. } else if (typeof self !== 'undefined') {
  11827. g = self;
  11828. } else {
  11829. g = this;
  11830. }
  11831. g.EphoxContactWrapper = f();
  11832. }
  11833. }(function () {
  11834. return function () {
  11835. function r(e, n, t) {
  11836. function o(i, f) {
  11837. if (!n[i]) {
  11838. if (!e[i]) {
  11839. var c = 'function' == typeof require && require;
  11840. if (!f && c)
  11841. return c(i, !0);
  11842. if (u)
  11843. return u(i, !0);
  11844. var a = new Error('Cannot find module \'' + i + '\'');
  11845. throw a.code = 'MODULE_NOT_FOUND', a;
  11846. }
  11847. var p = n[i] = { exports: {} };
  11848. e[i][0].call(p.exports, function (r) {
  11849. var n = e[i][1][r];
  11850. return o(n || r);
  11851. }, p, p.exports, r, e, n, t);
  11852. }
  11853. return n[i].exports;
  11854. }
  11855. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  11856. o(t[i]);
  11857. return o;
  11858. }
  11859. return r;
  11860. }()({
  11861. 1: [
  11862. function (require, module, exports) {
  11863. var process = module.exports = {};
  11864. var cachedSetTimeout;
  11865. var cachedClearTimeout;
  11866. function defaultSetTimout() {
  11867. throw new Error('setTimeout has not been defined');
  11868. }
  11869. function defaultClearTimeout() {
  11870. throw new Error('clearTimeout has not been defined');
  11871. }
  11872. (function () {
  11873. try {
  11874. if (typeof setTimeout === 'function') {
  11875. cachedSetTimeout = setTimeout;
  11876. } else {
  11877. cachedSetTimeout = defaultSetTimout;
  11878. }
  11879. } catch (e) {
  11880. cachedSetTimeout = defaultSetTimout;
  11881. }
  11882. try {
  11883. if (typeof clearTimeout === 'function') {
  11884. cachedClearTimeout = clearTimeout;
  11885. } else {
  11886. cachedClearTimeout = defaultClearTimeout;
  11887. }
  11888. } catch (e) {
  11889. cachedClearTimeout = defaultClearTimeout;
  11890. }
  11891. }());
  11892. function runTimeout(fun) {
  11893. if (cachedSetTimeout === setTimeout) {
  11894. return setTimeout(fun, 0);
  11895. }
  11896. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11897. cachedSetTimeout = setTimeout;
  11898. return setTimeout(fun, 0);
  11899. }
  11900. try {
  11901. return cachedSetTimeout(fun, 0);
  11902. } catch (e) {
  11903. try {
  11904. return cachedSetTimeout.call(null, fun, 0);
  11905. } catch (e) {
  11906. return cachedSetTimeout.call(this, fun, 0);
  11907. }
  11908. }
  11909. }
  11910. function runClearTimeout(marker) {
  11911. if (cachedClearTimeout === clearTimeout) {
  11912. return clearTimeout(marker);
  11913. }
  11914. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11915. cachedClearTimeout = clearTimeout;
  11916. return clearTimeout(marker);
  11917. }
  11918. try {
  11919. return cachedClearTimeout(marker);
  11920. } catch (e) {
  11921. try {
  11922. return cachedClearTimeout.call(null, marker);
  11923. } catch (e) {
  11924. return cachedClearTimeout.call(this, marker);
  11925. }
  11926. }
  11927. }
  11928. var queue = [];
  11929. var draining = false;
  11930. var currentQueue;
  11931. var queueIndex = -1;
  11932. function cleanUpNextTick() {
  11933. if (!draining || !currentQueue) {
  11934. return;
  11935. }
  11936. draining = false;
  11937. if (currentQueue.length) {
  11938. queue = currentQueue.concat(queue);
  11939. } else {
  11940. queueIndex = -1;
  11941. }
  11942. if (queue.length) {
  11943. drainQueue();
  11944. }
  11945. }
  11946. function drainQueue() {
  11947. if (draining) {
  11948. return;
  11949. }
  11950. var timeout = runTimeout(cleanUpNextTick);
  11951. draining = true;
  11952. var len = queue.length;
  11953. while (len) {
  11954. currentQueue = queue;
  11955. queue = [];
  11956. while (++queueIndex < len) {
  11957. if (currentQueue) {
  11958. currentQueue[queueIndex].run();
  11959. }
  11960. }
  11961. queueIndex = -1;
  11962. len = queue.length;
  11963. }
  11964. currentQueue = null;
  11965. draining = false;
  11966. runClearTimeout(timeout);
  11967. }
  11968. process.nextTick = function (fun) {
  11969. var args = new Array(arguments.length - 1);
  11970. if (arguments.length > 1) {
  11971. for (var i = 1; i < arguments.length; i++) {
  11972. args[i - 1] = arguments[i];
  11973. }
  11974. }
  11975. queue.push(new Item(fun, args));
  11976. if (queue.length === 1 && !draining) {
  11977. runTimeout(drainQueue);
  11978. }
  11979. };
  11980. function Item(fun, array) {
  11981. this.fun = fun;
  11982. this.array = array;
  11983. }
  11984. Item.prototype.run = function () {
  11985. this.fun.apply(null, this.array);
  11986. };
  11987. process.title = 'browser';
  11988. process.browser = true;
  11989. process.env = {};
  11990. process.argv = [];
  11991. process.version = '';
  11992. process.versions = {};
  11993. function noop() {
  11994. }
  11995. process.on = noop;
  11996. process.addListener = noop;
  11997. process.once = noop;
  11998. process.off = noop;
  11999. process.removeListener = noop;
  12000. process.removeAllListeners = noop;
  12001. process.emit = noop;
  12002. process.prependListener = noop;
  12003. process.prependOnceListener = noop;
  12004. process.listeners = function (name) {
  12005. return [];
  12006. };
  12007. process.binding = function (name) {
  12008. throw new Error('process.binding is not supported');
  12009. };
  12010. process.cwd = function () {
  12011. return '/';
  12012. };
  12013. process.chdir = function (dir) {
  12014. throw new Error('process.chdir is not supported');
  12015. };
  12016. process.umask = function () {
  12017. return 0;
  12018. };
  12019. },
  12020. {}
  12021. ],
  12022. 2: [
  12023. function (require, module, exports) {
  12024. (function (setImmediate) {
  12025. (function (root) {
  12026. var setTimeoutFunc = setTimeout;
  12027. function noop() {
  12028. }
  12029. function bind(fn, thisArg) {
  12030. return function () {
  12031. fn.apply(thisArg, arguments);
  12032. };
  12033. }
  12034. function Promise(fn) {
  12035. if (typeof this !== 'object')
  12036. throw new TypeError('Promises must be constructed via new');
  12037. if (typeof fn !== 'function')
  12038. throw new TypeError('not a function');
  12039. this._state = 0;
  12040. this._handled = false;
  12041. this._value = undefined;
  12042. this._deferreds = [];
  12043. doResolve(fn, this);
  12044. }
  12045. function handle(self, deferred) {
  12046. while (self._state === 3) {
  12047. self = self._value;
  12048. }
  12049. if (self._state === 0) {
  12050. self._deferreds.push(deferred);
  12051. return;
  12052. }
  12053. self._handled = true;
  12054. Promise._immediateFn(function () {
  12055. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  12056. if (cb === null) {
  12057. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  12058. return;
  12059. }
  12060. var ret;
  12061. try {
  12062. ret = cb(self._value);
  12063. } catch (e) {
  12064. reject(deferred.promise, e);
  12065. return;
  12066. }
  12067. resolve(deferred.promise, ret);
  12068. });
  12069. }
  12070. function resolve(self, newValue) {
  12071. try {
  12072. if (newValue === self)
  12073. throw new TypeError('A promise cannot be resolved with itself.');
  12074. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  12075. var then = newValue.then;
  12076. if (newValue instanceof Promise) {
  12077. self._state = 3;
  12078. self._value = newValue;
  12079. finale(self);
  12080. return;
  12081. } else if (typeof then === 'function') {
  12082. doResolve(bind(then, newValue), self);
  12083. return;
  12084. }
  12085. }
  12086. self._state = 1;
  12087. self._value = newValue;
  12088. finale(self);
  12089. } catch (e) {
  12090. reject(self, e);
  12091. }
  12092. }
  12093. function reject(self, newValue) {
  12094. self._state = 2;
  12095. self._value = newValue;
  12096. finale(self);
  12097. }
  12098. function finale(self) {
  12099. if (self._state === 2 && self._deferreds.length === 0) {
  12100. Promise._immediateFn(function () {
  12101. if (!self._handled) {
  12102. Promise._unhandledRejectionFn(self._value);
  12103. }
  12104. });
  12105. }
  12106. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  12107. handle(self, self._deferreds[i]);
  12108. }
  12109. self._deferreds = null;
  12110. }
  12111. function Handler(onFulfilled, onRejected, promise) {
  12112. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  12113. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  12114. this.promise = promise;
  12115. }
  12116. function doResolve(fn, self) {
  12117. var done = false;
  12118. try {
  12119. fn(function (value) {
  12120. if (done)
  12121. return;
  12122. done = true;
  12123. resolve(self, value);
  12124. }, function (reason) {
  12125. if (done)
  12126. return;
  12127. done = true;
  12128. reject(self, reason);
  12129. });
  12130. } catch (ex) {
  12131. if (done)
  12132. return;
  12133. done = true;
  12134. reject(self, ex);
  12135. }
  12136. }
  12137. Promise.prototype['catch'] = function (onRejected) {
  12138. return this.then(null, onRejected);
  12139. };
  12140. Promise.prototype.then = function (onFulfilled, onRejected) {
  12141. var prom = new this.constructor(noop);
  12142. handle(this, new Handler(onFulfilled, onRejected, prom));
  12143. return prom;
  12144. };
  12145. Promise.all = function (arr) {
  12146. var args = Array.prototype.slice.call(arr);
  12147. return new Promise(function (resolve, reject) {
  12148. if (args.length === 0)
  12149. return resolve([]);
  12150. var remaining = args.length;
  12151. function res(i, val) {
  12152. try {
  12153. if (val && (typeof val === 'object' || typeof val === 'function')) {
  12154. var then = val.then;
  12155. if (typeof then === 'function') {
  12156. then.call(val, function (val) {
  12157. res(i, val);
  12158. }, reject);
  12159. return;
  12160. }
  12161. }
  12162. args[i] = val;
  12163. if (--remaining === 0) {
  12164. resolve(args);
  12165. }
  12166. } catch (ex) {
  12167. reject(ex);
  12168. }
  12169. }
  12170. for (var i = 0; i < args.length; i++) {
  12171. res(i, args[i]);
  12172. }
  12173. });
  12174. };
  12175. Promise.resolve = function (value) {
  12176. if (value && typeof value === 'object' && value.constructor === Promise) {
  12177. return value;
  12178. }
  12179. return new Promise(function (resolve) {
  12180. resolve(value);
  12181. });
  12182. };
  12183. Promise.reject = function (value) {
  12184. return new Promise(function (resolve, reject) {
  12185. reject(value);
  12186. });
  12187. };
  12188. Promise.race = function (values) {
  12189. return new Promise(function (resolve, reject) {
  12190. for (var i = 0, len = values.length; i < len; i++) {
  12191. values[i].then(resolve, reject);
  12192. }
  12193. });
  12194. };
  12195. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  12196. setImmediate(fn);
  12197. } : function (fn) {
  12198. setTimeoutFunc(fn, 0);
  12199. };
  12200. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  12201. if (typeof console !== 'undefined' && console) {
  12202. console.warn('Possible Unhandled Promise Rejection:', err);
  12203. }
  12204. };
  12205. Promise._setImmediateFn = function _setImmediateFn(fn) {
  12206. Promise._immediateFn = fn;
  12207. };
  12208. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  12209. Promise._unhandledRejectionFn = fn;
  12210. };
  12211. if (typeof module !== 'undefined' && module.exports) {
  12212. module.exports = Promise;
  12213. } else if (!root.Promise) {
  12214. root.Promise = Promise;
  12215. }
  12216. }(this));
  12217. }.call(this, require('timers').setImmediate));
  12218. },
  12219. { 'timers': 3 }
  12220. ],
  12221. 3: [
  12222. function (require, module, exports) {
  12223. (function (setImmediate, clearImmediate) {
  12224. var nextTick = require('process/browser.js').nextTick;
  12225. var apply = Function.prototype.apply;
  12226. var slice = Array.prototype.slice;
  12227. var immediateIds = {};
  12228. var nextImmediateId = 0;
  12229. exports.setTimeout = function () {
  12230. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  12231. };
  12232. exports.setInterval = function () {
  12233. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12234. };
  12235. exports.clearTimeout = exports.clearInterval = function (timeout) {
  12236. timeout.close();
  12237. };
  12238. function Timeout(id, clearFn) {
  12239. this._id = id;
  12240. this._clearFn = clearFn;
  12241. }
  12242. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  12243. };
  12244. Timeout.prototype.close = function () {
  12245. this._clearFn.call(window, this._id);
  12246. };
  12247. exports.enroll = function (item, msecs) {
  12248. clearTimeout(item._idleTimeoutId);
  12249. item._idleTimeout = msecs;
  12250. };
  12251. exports.unenroll = function (item) {
  12252. clearTimeout(item._idleTimeoutId);
  12253. item._idleTimeout = -1;
  12254. };
  12255. exports._unrefActive = exports.active = function (item) {
  12256. clearTimeout(item._idleTimeoutId);
  12257. var msecs = item._idleTimeout;
  12258. if (msecs >= 0) {
  12259. item._idleTimeoutId = setTimeout(function onTimeout() {
  12260. if (item._onTimeout)
  12261. item._onTimeout();
  12262. }, msecs);
  12263. }
  12264. };
  12265. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  12266. var id = nextImmediateId++;
  12267. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  12268. immediateIds[id] = true;
  12269. nextTick(function onNextTick() {
  12270. if (immediateIds[id]) {
  12271. if (args) {
  12272. fn.apply(null, args);
  12273. } else {
  12274. fn.call(null);
  12275. }
  12276. exports.clearImmediate(id);
  12277. }
  12278. });
  12279. return id;
  12280. };
  12281. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  12282. delete immediateIds[id];
  12283. };
  12284. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  12285. },
  12286. {
  12287. 'process/browser.js': 1,
  12288. 'timers': 3
  12289. }
  12290. ],
  12291. 4: [
  12292. function (require, module, exports) {
  12293. var promisePolyfill = require('promise-polyfill');
  12294. var Global = function () {
  12295. if (typeof window !== 'undefined') {
  12296. return window;
  12297. } else {
  12298. return Function('return this;')();
  12299. }
  12300. }();
  12301. module.exports = { boltExport: Global.Promise || promisePolyfill };
  12302. },
  12303. { 'promise-polyfill': 2 }
  12304. ]
  12305. }, {}, [4])(4);
  12306. }));
  12307. }(undefined, exports$1, module, undefined));
  12308. var Promise$1 = module.exports.boltExport;
  12309. var nu$7 = function (baseFn) {
  12310. var data = Option.none();
  12311. var callbacks = [];
  12312. var map = function (f) {
  12313. return nu$7(function (nCallback) {
  12314. get(function (data) {
  12315. nCallback(f(data));
  12316. });
  12317. });
  12318. };
  12319. var get = function (nCallback) {
  12320. if (isReady()) {
  12321. call(nCallback);
  12322. } else {
  12323. callbacks.push(nCallback);
  12324. }
  12325. };
  12326. var set = function (x) {
  12327. data = Option.some(x);
  12328. run(callbacks);
  12329. callbacks = [];
  12330. };
  12331. var isReady = function () {
  12332. return data.isSome();
  12333. };
  12334. var run = function (cbs) {
  12335. each$1(cbs, call);
  12336. };
  12337. var call = function (cb) {
  12338. data.each(function (x) {
  12339. domGlobals.setTimeout(function () {
  12340. cb(x);
  12341. }, 0);
  12342. });
  12343. };
  12344. baseFn(set);
  12345. return {
  12346. get: get,
  12347. map: map,
  12348. isReady: isReady
  12349. };
  12350. };
  12351. var pure$1 = function (a) {
  12352. return nu$7(function (callback) {
  12353. callback(a);
  12354. });
  12355. };
  12356. var LazyValue = {
  12357. nu: nu$7,
  12358. pure: pure$1
  12359. };
  12360. var errorReporter = function (err) {
  12361. domGlobals.setTimeout(function () {
  12362. throw err;
  12363. }, 0);
  12364. };
  12365. var make$4 = function (run) {
  12366. var get = function (callback) {
  12367. run().then(callback, errorReporter);
  12368. };
  12369. var map = function (fab) {
  12370. return make$4(function () {
  12371. return run().then(fab);
  12372. });
  12373. };
  12374. var bind = function (aFutureB) {
  12375. return make$4(function () {
  12376. return run().then(function (v) {
  12377. return aFutureB(v).toPromise();
  12378. });
  12379. });
  12380. };
  12381. var anonBind = function (futureB) {
  12382. return make$4(function () {
  12383. return run().then(function () {
  12384. return futureB.toPromise();
  12385. });
  12386. });
  12387. };
  12388. var toLazy = function () {
  12389. return LazyValue.nu(get);
  12390. };
  12391. var toCached = function () {
  12392. var cache = null;
  12393. return make$4(function () {
  12394. if (cache === null) {
  12395. cache = run();
  12396. }
  12397. return cache;
  12398. });
  12399. };
  12400. var toPromise = run;
  12401. return {
  12402. map: map,
  12403. bind: bind,
  12404. anonBind: anonBind,
  12405. toLazy: toLazy,
  12406. toCached: toCached,
  12407. toPromise: toPromise,
  12408. get: get
  12409. };
  12410. };
  12411. var nu$8 = function (baseFn) {
  12412. return make$4(function () {
  12413. return new Promise$1(baseFn);
  12414. });
  12415. };
  12416. var pure$2 = function (a) {
  12417. return make$4(function () {
  12418. return Promise$1.resolve(a);
  12419. });
  12420. };
  12421. var Future = {
  12422. nu: nu$8,
  12423. pure: pure$2
  12424. };
  12425. var adjust = function (value, destination, amount) {
  12426. if (Math.abs(value - destination) <= amount) {
  12427. return Option.none();
  12428. } else if (value < destination) {
  12429. return Option.some(value + amount);
  12430. } else {
  12431. return Option.some(value - amount);
  12432. }
  12433. };
  12434. var create$5 = function () {
  12435. var interval = null;
  12436. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  12437. var finished = false;
  12438. var finish = function (v) {
  12439. finished = true;
  12440. doFinish(v);
  12441. };
  12442. global$4.clearInterval(interval);
  12443. var abort = function (v) {
  12444. global$4.clearInterval(interval);
  12445. finish(v);
  12446. };
  12447. interval = global$4.setInterval(function () {
  12448. var value = getCurrent();
  12449. adjust(value, destination, amount).fold(function () {
  12450. global$4.clearInterval(interval);
  12451. finish(destination);
  12452. }, function (s) {
  12453. increment(s, abort);
  12454. if (!finished) {
  12455. var newValue = getCurrent();
  12456. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  12457. global$4.clearInterval(interval);
  12458. finish(destination);
  12459. }
  12460. }
  12461. });
  12462. }, rate);
  12463. };
  12464. return { animate: animate };
  12465. };
  12466. var SmoothAnimation = {
  12467. create: create$5,
  12468. adjust: adjust
  12469. };
  12470. var findDevice = function (deviceWidth, deviceHeight) {
  12471. var devices = [
  12472. {
  12473. width: 320,
  12474. height: 480,
  12475. keyboard: {
  12476. portrait: 300,
  12477. landscape: 240
  12478. }
  12479. },
  12480. {
  12481. width: 320,
  12482. height: 568,
  12483. keyboard: {
  12484. portrait: 300,
  12485. landscape: 240
  12486. }
  12487. },
  12488. {
  12489. width: 375,
  12490. height: 667,
  12491. keyboard: {
  12492. portrait: 305,
  12493. landscape: 240
  12494. }
  12495. },
  12496. {
  12497. width: 414,
  12498. height: 736,
  12499. keyboard: {
  12500. portrait: 320,
  12501. landscape: 240
  12502. }
  12503. },
  12504. {
  12505. width: 768,
  12506. height: 1024,
  12507. keyboard: {
  12508. portrait: 320,
  12509. landscape: 400
  12510. }
  12511. },
  12512. {
  12513. width: 1024,
  12514. height: 1366,
  12515. keyboard: {
  12516. portrait: 380,
  12517. landscape: 460
  12518. }
  12519. }
  12520. ];
  12521. return findMap(devices, function (device) {
  12522. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  12523. }).getOr({
  12524. portrait: deviceHeight / 5,
  12525. landscape: deviceWidth / 4
  12526. });
  12527. };
  12528. var softKeyboardLimits = function (outerWindow) {
  12529. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  12530. };
  12531. var accountableKeyboardHeight = function (outerWindow) {
  12532. var portrait = Orientation.get(outerWindow).isPortrait();
  12533. var limits = softKeyboardLimits(outerWindow);
  12534. var keyboard = portrait ? limits.portrait : limits.landscape;
  12535. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  12536. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  12537. };
  12538. var getGreenzone = function (socket, dropup) {
  12539. var outerWindow = owner(socket).dom().defaultView;
  12540. var viewportHeight = get$5(socket) + get$5(dropup);
  12541. var acc = accountableKeyboardHeight(outerWindow);
  12542. return viewportHeight - acc;
  12543. };
  12544. var updatePadding = function (contentBody, socket, dropup) {
  12545. var greenzoneHeight = getGreenzone(socket, dropup);
  12546. var deltaHeight = get$5(socket) + get$5(dropup) - greenzoneHeight;
  12547. set$3(contentBody, 'padding-bottom', deltaHeight + 'px');
  12548. };
  12549. var DeviceZones = {
  12550. getGreenzone: getGreenzone,
  12551. updatePadding: updatePadding
  12552. };
  12553. var fixture = Adt.generate([
  12554. {
  12555. fixed: [
  12556. 'element',
  12557. 'property',
  12558. 'offsetY'
  12559. ]
  12560. },
  12561. {
  12562. scroller: [
  12563. 'element',
  12564. 'offsetY'
  12565. ]
  12566. }
  12567. ]);
  12568. var yFixedData = 'data-' + Styles.resolve('position-y-fixed');
  12569. var yFixedProperty = 'data-' + Styles.resolve('y-property');
  12570. var yScrollingData = 'data-' + Styles.resolve('scrolling');
  12571. var windowSizeData = 'data-' + Styles.resolve('last-window-height');
  12572. var getYFixedData = function (element) {
  12573. return DataAttributes.safeParse(element, yFixedData);
  12574. };
  12575. var getYFixedProperty = function (element) {
  12576. return get$1(element, yFixedProperty);
  12577. };
  12578. var getLastWindowSize = function (element) {
  12579. return DataAttributes.safeParse(element, windowSizeData);
  12580. };
  12581. var classifyFixed = function (element, offsetY) {
  12582. var prop = getYFixedProperty(element);
  12583. return fixture.fixed(element, prop, offsetY);
  12584. };
  12585. var classifyScrolling = function (element, offsetY) {
  12586. return fixture.scroller(element, offsetY);
  12587. };
  12588. var classify = function (element) {
  12589. var offsetY = getYFixedData(element);
  12590. var classifier = get$1(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  12591. return classifier(element, offsetY);
  12592. };
  12593. var findFixtures = function (container) {
  12594. var candidates = descendants(container, '[' + yFixedData + ']');
  12595. return map$1(candidates, classify);
  12596. };
  12597. var takeoverToolbar = function (toolbar) {
  12598. var oldToolbarStyle = get$1(toolbar, 'style');
  12599. setAll$1(toolbar, {
  12600. position: 'absolute',
  12601. top: '0px'
  12602. });
  12603. set(toolbar, yFixedData, '0px');
  12604. set(toolbar, yFixedProperty, 'top');
  12605. var restore = function () {
  12606. set(toolbar, 'style', oldToolbarStyle || '');
  12607. remove$1(toolbar, yFixedData);
  12608. remove$1(toolbar, yFixedProperty);
  12609. };
  12610. return { restore: restore };
  12611. };
  12612. var takeoverViewport = function (toolbarHeight, height, viewport) {
  12613. var oldViewportStyle = get$1(viewport, 'style');
  12614. Scrollable.register(viewport);
  12615. setAll$1(viewport, {
  12616. position: 'absolute',
  12617. height: height + 'px',
  12618. width: '100%',
  12619. top: toolbarHeight + 'px'
  12620. });
  12621. set(viewport, yFixedData, toolbarHeight + 'px');
  12622. set(viewport, yScrollingData, 'true');
  12623. set(viewport, yFixedProperty, 'top');
  12624. var restore = function () {
  12625. Scrollable.deregister(viewport);
  12626. set(viewport, 'style', oldViewportStyle || '');
  12627. remove$1(viewport, yFixedData);
  12628. remove$1(viewport, yScrollingData);
  12629. remove$1(viewport, yFixedProperty);
  12630. };
  12631. return { restore: restore };
  12632. };
  12633. var takeoverDropup = function (dropup, toolbarHeight, viewportHeight) {
  12634. var oldDropupStyle = get$1(dropup, 'style');
  12635. setAll$1(dropup, {
  12636. position: 'absolute',
  12637. bottom: '0px'
  12638. });
  12639. set(dropup, yFixedData, '0px');
  12640. set(dropup, yFixedProperty, 'bottom');
  12641. var restore = function () {
  12642. set(dropup, 'style', oldDropupStyle || '');
  12643. remove$1(dropup, yFixedData);
  12644. remove$1(dropup, yFixedProperty);
  12645. };
  12646. return { restore: restore };
  12647. };
  12648. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12649. var outerWindow = owner(viewport).dom().defaultView;
  12650. var winH = outerWindow.innerHeight;
  12651. set(viewport, windowSizeData, winH + 'px');
  12652. return winH - toolbarHeight - dropupHeight;
  12653. };
  12654. var takeover$1 = function (viewport, contentBody, toolbar, dropup) {
  12655. var outerWindow = owner(viewport).dom().defaultView;
  12656. var toolbarSetup = takeoverToolbar(toolbar);
  12657. var toolbarHeight = get$5(toolbar);
  12658. var dropupHeight = get$5(dropup);
  12659. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12660. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12661. var dropupSetup = takeoverDropup(dropup);
  12662. var isActive = true;
  12663. var restore = function () {
  12664. isActive = false;
  12665. toolbarSetup.restore();
  12666. viewportSetup.restore();
  12667. dropupSetup.restore();
  12668. };
  12669. var isExpanding = function () {
  12670. var currentWinHeight = outerWindow.innerHeight;
  12671. var lastWinHeight = getLastWindowSize(viewport);
  12672. return currentWinHeight > lastWinHeight;
  12673. };
  12674. var refresh = function () {
  12675. if (isActive) {
  12676. var newToolbarHeight = get$5(toolbar);
  12677. var dropupHeight_1 = get$5(dropup);
  12678. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12679. set(viewport, yFixedData, newToolbarHeight + 'px');
  12680. set$3(viewport, 'height', newHeight + 'px');
  12681. DeviceZones.updatePadding(contentBody, viewport, dropup);
  12682. }
  12683. };
  12684. var setViewportOffset = function (newYOffset) {
  12685. var offsetPx = newYOffset + 'px';
  12686. set(viewport, yFixedData, offsetPx);
  12687. refresh();
  12688. };
  12689. DeviceZones.updatePadding(contentBody, viewport, dropup);
  12690. return {
  12691. setViewportOffset: setViewportOffset,
  12692. isExpanding: isExpanding,
  12693. isShrinking: not(isExpanding),
  12694. refresh: refresh,
  12695. restore: restore
  12696. };
  12697. };
  12698. var IosViewport = {
  12699. findFixtures: findFixtures,
  12700. takeover: takeover$1,
  12701. getYFixedData: getYFixedData
  12702. };
  12703. var animator = SmoothAnimation.create();
  12704. var ANIMATION_STEP = 15;
  12705. var NUM_TOP_ANIMATION_FRAMES = 10;
  12706. var ANIMATION_RATE = 10;
  12707. var lastScroll = 'data-' + Styles.resolve('last-scroll-top');
  12708. var getTop = function (element) {
  12709. var raw = getRaw(element, 'top').getOr('0');
  12710. return parseInt(raw, 10);
  12711. };
  12712. var getScrollTop = function (element) {
  12713. return parseInt(element.dom().scrollTop, 10);
  12714. };
  12715. var moveScrollAndTop = function (element, destination, finalTop) {
  12716. return Future.nu(function (callback) {
  12717. var getCurrent = curry(getScrollTop, element);
  12718. var update = function (newScroll) {
  12719. element.dom().scrollTop = newScroll;
  12720. set$3(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12721. };
  12722. var finish = function () {
  12723. element.dom().scrollTop = destination;
  12724. set$3(element, 'top', finalTop + 'px');
  12725. callback(destination);
  12726. };
  12727. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12728. });
  12729. };
  12730. var moveOnlyScroll = function (element, destination) {
  12731. return Future.nu(function (callback) {
  12732. var getCurrent = curry(getScrollTop, element);
  12733. set(element, lastScroll, getCurrent());
  12734. var update = function (newScroll, abort) {
  12735. var previous = DataAttributes.safeParse(element, lastScroll);
  12736. if (previous !== element.dom().scrollTop) {
  12737. abort(element.dom().scrollTop);
  12738. } else {
  12739. element.dom().scrollTop = newScroll;
  12740. set(element, lastScroll, newScroll);
  12741. }
  12742. };
  12743. var finish = function () {
  12744. element.dom().scrollTop = destination;
  12745. set(element, lastScroll, destination);
  12746. callback(destination);
  12747. };
  12748. var distance = Math.abs(destination - getCurrent());
  12749. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12750. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12751. });
  12752. };
  12753. var moveOnlyTop = function (element, destination) {
  12754. return Future.nu(function (callback) {
  12755. var getCurrent = curry(getTop, element);
  12756. var update = function (newTop) {
  12757. set$3(element, 'top', newTop + 'px');
  12758. };
  12759. var finish = function () {
  12760. update(destination);
  12761. callback(destination);
  12762. };
  12763. var distance = Math.abs(destination - getCurrent());
  12764. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12765. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12766. });
  12767. };
  12768. var updateTop = function (element, amount) {
  12769. var newTop = amount + IosViewport.getYFixedData(element) + 'px';
  12770. set$3(element, 'top', newTop);
  12771. };
  12772. var moveWindowScroll = function (toolbar, viewport, destY) {
  12773. var outerWindow = owner(toolbar).dom().defaultView;
  12774. return Future.nu(function (callback) {
  12775. updateTop(toolbar, destY);
  12776. updateTop(viewport, destY);
  12777. outerWindow.scrollTo(0, destY);
  12778. callback(destY);
  12779. });
  12780. };
  12781. var IosScrolling = {
  12782. moveScrollAndTop: moveScrollAndTop,
  12783. moveOnlyScroll: moveOnlyScroll,
  12784. moveOnlyTop: moveOnlyTop,
  12785. moveWindowScroll: moveWindowScroll
  12786. };
  12787. function BackgroundActivity (doAction) {
  12788. var action = Cell(LazyValue.pure({}));
  12789. var start = function (value) {
  12790. var future = LazyValue.nu(function (callback) {
  12791. return doAction(value).get(callback);
  12792. });
  12793. action.set(future);
  12794. };
  12795. var idle = function (g) {
  12796. action.get().get(function () {
  12797. g();
  12798. });
  12799. };
  12800. return {
  12801. start: start,
  12802. idle: idle
  12803. };
  12804. }
  12805. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12806. var greenzone = DeviceZones.getGreenzone(socket, dropup);
  12807. var refreshCursor = curry(CursorRefresh.refresh, cWin);
  12808. if (top > greenzone || bottom > greenzone) {
  12809. IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop - greenzone + bottom).get(refreshCursor);
  12810. } else if (top < 0) {
  12811. IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop + top).get(refreshCursor);
  12812. }
  12813. };
  12814. var Greenzone = { scrollIntoView: scrollIntoView };
  12815. var par = function (asyncValues, nu) {
  12816. return nu(function (callback) {
  12817. var r = [];
  12818. var count = 0;
  12819. var cb = function (i) {
  12820. return function (value) {
  12821. r[i] = value;
  12822. count++;
  12823. if (count >= asyncValues.length) {
  12824. callback(r);
  12825. }
  12826. };
  12827. };
  12828. if (asyncValues.length === 0) {
  12829. callback([]);
  12830. } else {
  12831. each$1(asyncValues, function (asyncValue, i) {
  12832. asyncValue.get(cb(i));
  12833. });
  12834. }
  12835. });
  12836. };
  12837. var par$1 = function (futures) {
  12838. return par(futures, Future.nu);
  12839. };
  12840. var updateFixed = function (element, property, winY, offsetY) {
  12841. var destination = winY + offsetY;
  12842. set$3(element, property, destination + 'px');
  12843. return Future.pure(offsetY);
  12844. };
  12845. var updateScrollingFixed = function (element, winY, offsetY) {
  12846. var destTop = winY + offsetY;
  12847. var oldProp = getRaw(element, 'top').getOr(offsetY);
  12848. var delta = destTop - parseInt(oldProp, 10);
  12849. var destScroll = element.dom().scrollTop + delta;
  12850. return IosScrolling.moveScrollAndTop(element, destScroll, destTop);
  12851. };
  12852. var updateFixture = function (fixture, winY) {
  12853. return fixture.fold(function (element, property, offsetY) {
  12854. return updateFixed(element, property, winY, offsetY);
  12855. }, function (element, offsetY) {
  12856. return updateScrollingFixed(element, winY, offsetY);
  12857. });
  12858. };
  12859. var updatePositions = function (container, winY) {
  12860. var fixtures = IosViewport.findFixtures(container);
  12861. var updates = map$1(fixtures, function (fixture) {
  12862. return updateFixture(fixture, winY);
  12863. });
  12864. return par$1(updates);
  12865. };
  12866. var IosUpdates = { updatePositions: updatePositions };
  12867. var VIEW_MARGIN = 5;
  12868. var register$2 = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  12869. var scroller = BackgroundActivity(function (y) {
  12870. return IosScrolling.moveWindowScroll(toolstrip, socket, y);
  12871. });
  12872. var scrollBounds = function () {
  12873. var rects = Rectangles.getRectangles(cWin);
  12874. return Option.from(rects[0]).bind(function (rect) {
  12875. var viewTop = rect.top() - socket.dom().scrollTop;
  12876. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  12877. return outside ? Option.some({
  12878. top: constant(viewTop),
  12879. bottom: constant(viewTop + rect.height())
  12880. }) : Option.none();
  12881. });
  12882. };
  12883. var scrollThrottle = last(function () {
  12884. scroller.idle(function () {
  12885. IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(function () {
  12886. var extraScroll = scrollBounds();
  12887. extraScroll.each(function (extra) {
  12888. socket.dom().scrollTop = socket.dom().scrollTop + extra.top();
  12889. });
  12890. scroller.start(0);
  12891. structure.refresh();
  12892. });
  12893. });
  12894. }, 1000);
  12895. var onScroll = bind$3(Element.fromDom(outerWindow), 'scroll', function () {
  12896. if (outerWindow.pageYOffset < 0) {
  12897. return;
  12898. }
  12899. scrollThrottle.throttle();
  12900. });
  12901. IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(identity);
  12902. return { unbind: onScroll.unbind };
  12903. };
  12904. var setup$3 = function (bag) {
  12905. var cWin = bag.cWin();
  12906. var ceBody = bag.ceBody();
  12907. var socket = bag.socket();
  12908. var toolstrip = bag.toolstrip();
  12909. var toolbar = bag.toolbar();
  12910. var contentElement = bag.contentElement();
  12911. var keyboardType = bag.keyboardType();
  12912. var outerWindow = bag.outerWindow();
  12913. var dropup = bag.dropup();
  12914. var structure = IosViewport.takeover(socket, ceBody, toolstrip, dropup);
  12915. var keyboardModel = keyboardType(bag.outerBody(), cWin, body(), contentElement, toolstrip, toolbar);
  12916. var toEditing = function () {
  12917. keyboardModel.toEditing();
  12918. clearSelection();
  12919. };
  12920. var toReading = function () {
  12921. keyboardModel.toReading();
  12922. };
  12923. var onToolbarTouch = function (event) {
  12924. keyboardModel.onToolbarTouch(event);
  12925. };
  12926. var onOrientation = Orientation.onChange(outerWindow, {
  12927. onChange: noop,
  12928. onReady: structure.refresh
  12929. });
  12930. onOrientation.onAdjustment(function () {
  12931. structure.refresh();
  12932. });
  12933. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  12934. if (structure.isExpanding()) {
  12935. structure.refresh();
  12936. }
  12937. });
  12938. var onScroll = register$2(toolstrip, socket, bag.outerBody(), outerWindow, structure, cWin);
  12939. var unfocusedSelection = FakeSelection(cWin, contentElement);
  12940. var refreshSelection = function () {
  12941. if (unfocusedSelection.isActive()) {
  12942. unfocusedSelection.update();
  12943. }
  12944. };
  12945. var highlightSelection = function () {
  12946. unfocusedSelection.update();
  12947. };
  12948. var clearSelection = function () {
  12949. unfocusedSelection.clear();
  12950. };
  12951. var scrollIntoView = function (top, bottom) {
  12952. Greenzone.scrollIntoView(cWin, socket, dropup, top, bottom);
  12953. };
  12954. var syncHeight = function () {
  12955. set$3(contentElement, 'height', contentElement.dom().contentWindow.document.body.scrollHeight + 'px');
  12956. };
  12957. var setViewportOffset = function (newYOffset) {
  12958. structure.setViewportOffset(newYOffset);
  12959. IosScrolling.moveOnlyTop(socket, newYOffset).get(identity);
  12960. };
  12961. var destroy = function () {
  12962. structure.restore();
  12963. onOrientation.destroy();
  12964. onScroll.unbind();
  12965. onResize.unbind();
  12966. keyboardModel.destroy();
  12967. unfocusedSelection.destroy();
  12968. CaptureBin.input(body(), blur);
  12969. };
  12970. return {
  12971. toEditing: toEditing,
  12972. toReading: toReading,
  12973. onToolbarTouch: onToolbarTouch,
  12974. refreshSelection: refreshSelection,
  12975. clearSelection: clearSelection,
  12976. highlightSelection: highlightSelection,
  12977. scrollIntoView: scrollIntoView,
  12978. updateToolbarPadding: noop,
  12979. setViewportOffset: setViewportOffset,
  12980. syncHeight: syncHeight,
  12981. refreshStructure: structure.refresh,
  12982. destroy: destroy
  12983. };
  12984. };
  12985. var IosSetup = { setup: setup$3 };
  12986. var create$6 = function (platform, mask) {
  12987. var meta = MetaViewport.tag();
  12988. var priorState = value$2();
  12989. var scrollEvents = value$2();
  12990. var iosApi = api$2();
  12991. var iosEvents = api$2();
  12992. var enter = function () {
  12993. mask.hide();
  12994. var doc = Element.fromDom(domGlobals.document);
  12995. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  12996. priorState.set({
  12997. socketHeight: getRaw(platform.socket, 'height'),
  12998. iframeHeight: getRaw(editorApi.frame(), 'height'),
  12999. outerScroll: domGlobals.document.body.scrollTop
  13000. });
  13001. scrollEvents.set({ exclusives: Scrollables.exclusive(doc, '.' + Scrollable.scrollable()) });
  13002. add$2(platform.container, Styles.resolve('fullscreen-maximized'));
  13003. Thor.clobberStyles(platform.container, editorApi.body());
  13004. meta.maximize();
  13005. set$3(platform.socket, 'overflow', 'scroll');
  13006. set$3(platform.socket, '-webkit-overflow-scrolling', 'touch');
  13007. focus$1(editorApi.body());
  13008. var setupBag = MixedBag([
  13009. 'cWin',
  13010. 'ceBody',
  13011. 'socket',
  13012. 'toolstrip',
  13013. 'toolbar',
  13014. 'dropup',
  13015. 'contentElement',
  13016. 'cursor',
  13017. 'keyboardType',
  13018. 'isScrolling',
  13019. 'outerWindow',
  13020. 'outerBody'
  13021. ], []);
  13022. iosApi.set(IosSetup.setup(setupBag({
  13023. cWin: editorApi.win(),
  13024. ceBody: editorApi.body(),
  13025. socket: platform.socket,
  13026. toolstrip: platform.toolstrip,
  13027. toolbar: platform.toolbar,
  13028. dropup: platform.dropup.element(),
  13029. contentElement: editorApi.frame(),
  13030. cursor: noop,
  13031. outerBody: platform.body,
  13032. outerWindow: platform.win,
  13033. keyboardType: IosKeyboard.stubborn,
  13034. isScrolling: function () {
  13035. var scrollValue = scrollEvents;
  13036. return scrollValue.get().exists(function (s) {
  13037. return s.socket.isScrolling();
  13038. });
  13039. }
  13040. })));
  13041. iosApi.run(function (api) {
  13042. api.syncHeight();
  13043. });
  13044. iosEvents.set(IosEvents.initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  13045. });
  13046. };
  13047. var exit = function () {
  13048. meta.restore();
  13049. iosEvents.clear();
  13050. iosApi.clear();
  13051. mask.show();
  13052. priorState.on(function (s) {
  13053. s.socketHeight.each(function (h) {
  13054. set$3(platform.socket, 'height', h);
  13055. });
  13056. s.iframeHeight.each(function (h) {
  13057. set$3(platform.editor.getFrame(), 'height', h);
  13058. });
  13059. domGlobals.document.body.scrollTop = s.scrollTop;
  13060. });
  13061. priorState.clear();
  13062. scrollEvents.on(function (s) {
  13063. s.exclusives.unbind();
  13064. });
  13065. scrollEvents.clear();
  13066. remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
  13067. Thor.restoreStyles();
  13068. Scrollable.deregister(platform.toolbar);
  13069. remove$5(platform.socket, 'overflow');
  13070. remove$5(platform.socket, '-webkit-overflow-scrolling');
  13071. blur(platform.editor.getFrame());
  13072. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  13073. editorApi.clearSelection();
  13074. });
  13075. };
  13076. var refreshStructure = function () {
  13077. iosApi.run(function (api) {
  13078. api.refreshStructure();
  13079. });
  13080. };
  13081. return {
  13082. enter: enter,
  13083. refreshStructure: refreshStructure,
  13084. exit: exit
  13085. };
  13086. };
  13087. var IosMode = { create: create$6 };
  13088. var produce$1 = function (raw) {
  13089. var mobile = asRawOrDie('Getting IosWebapp schema', MobileSchema, raw);
  13090. set$3(mobile.toolstrip, 'width', '100%');
  13091. set$3(mobile.container, 'position', 'relative');
  13092. var onView = function () {
  13093. mobile.setReadOnly(mobile.readOnlyOnInit());
  13094. mode.enter();
  13095. };
  13096. var mask = build$1(TapToEditMask.sketch(onView, mobile.translate));
  13097. mobile.alloy.add(mask);
  13098. var maskApi = {
  13099. show: function () {
  13100. mobile.alloy.add(mask);
  13101. },
  13102. hide: function () {
  13103. mobile.alloy.remove(mask);
  13104. }
  13105. };
  13106. var mode = IosMode.create(mobile, maskApi);
  13107. return {
  13108. setReadOnly: mobile.setReadOnly,
  13109. refreshStructure: mode.refreshStructure,
  13110. enter: mode.enter,
  13111. exit: mode.exit,
  13112. destroy: noop
  13113. };
  13114. };
  13115. var IosWebapp = { produce: produce$1 };
  13116. function IosRealm (scrollIntoView) {
  13117. var alloy = OuterContainer({ classes: [Styles.resolve('ios-container')] });
  13118. var toolbar = ScrollingToolbar();
  13119. var webapp = api$2();
  13120. var switchToEdit = CommonRealm.makeEditSwitch(webapp);
  13121. var socket = CommonRealm.makeSocket();
  13122. var dropup = build$2(function () {
  13123. webapp.run(function (w) {
  13124. w.refreshStructure();
  13125. });
  13126. }, scrollIntoView);
  13127. alloy.add(toolbar.wrapper());
  13128. alloy.add(socket);
  13129. alloy.add(dropup.component());
  13130. var setToolbarGroups = function (rawGroups) {
  13131. var groups = toolbar.createGroups(rawGroups);
  13132. toolbar.setGroups(groups);
  13133. };
  13134. var setContextToolbar = function (rawGroups) {
  13135. var groups = toolbar.createGroups(rawGroups);
  13136. toolbar.setContextToolbar(groups);
  13137. };
  13138. var focusToolbar = function () {
  13139. toolbar.focus();
  13140. };
  13141. var restoreToolbar = function () {
  13142. toolbar.restoreToolbar();
  13143. };
  13144. var init = function (spec) {
  13145. webapp.set(IosWebapp.produce(spec));
  13146. };
  13147. var exit = function () {
  13148. webapp.run(function (w) {
  13149. Replacing.remove(socket, switchToEdit);
  13150. w.exit();
  13151. });
  13152. };
  13153. var updateMode = function (readOnly) {
  13154. CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
  13155. };
  13156. return {
  13157. system: constant(alloy),
  13158. element: alloy.element,
  13159. init: init,
  13160. exit: exit,
  13161. setToolbarGroups: setToolbarGroups,
  13162. setContextToolbar: setContextToolbar,
  13163. focusToolbar: focusToolbar,
  13164. restoreToolbar: restoreToolbar,
  13165. updateMode: updateMode,
  13166. socket: constant(socket),
  13167. dropup: constant(dropup)
  13168. };
  13169. }
  13170. var global$5 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  13171. var derive$3 = function (editor) {
  13172. var base = get(editor.settings, 'skin_url').fold(function () {
  13173. return global$5.baseURL + '/skins/ui/oxide';
  13174. }, function (url) {
  13175. return url;
  13176. });
  13177. return {
  13178. content: base + '/content.mobile.min.css',
  13179. ui: base + '/skin.mobile.min.css'
  13180. };
  13181. };
  13182. var CssUrls = { derive: derive$3 };
  13183. var fontSizes = [
  13184. 'x-small',
  13185. 'small',
  13186. 'medium',
  13187. 'large',
  13188. 'x-large'
  13189. ];
  13190. var fireChange = function (realm, command, state) {
  13191. realm.system().broadcastOn([TinyChannels.formatChanged()], {
  13192. command: command,
  13193. state: state
  13194. });
  13195. };
  13196. var init$5 = function (realm, editor) {
  13197. var allFormats = keys(editor.formatter.get());
  13198. each$1(allFormats, function (command) {
  13199. editor.formatter.formatChanged(command, function (state) {
  13200. fireChange(realm, command, state);
  13201. });
  13202. });
  13203. each$1([
  13204. 'ul',
  13205. 'ol'
  13206. ], function (command) {
  13207. editor.selection.selectorChanged(command, function (state, data) {
  13208. fireChange(realm, command, state);
  13209. });
  13210. });
  13211. };
  13212. var FormatChangers = {
  13213. init: init$5,
  13214. fontSizes: constant(fontSizes)
  13215. };
  13216. var fireSkinLoaded = function (editor) {
  13217. var done = function () {
  13218. editor._skinLoaded = true;
  13219. editor.fire('SkinLoaded');
  13220. };
  13221. return function () {
  13222. if (editor.initialized) {
  13223. done();
  13224. } else {
  13225. editor.on('init', done);
  13226. }
  13227. };
  13228. };
  13229. var SkinLoaded = { fireSkinLoaded: fireSkinLoaded };
  13230. var READING = constant('toReading');
  13231. var EDITING = constant('toEditing');
  13232. var renderMobileTheme = function (editor) {
  13233. var renderUI = function () {
  13234. var targetNode = editor.getElement();
  13235. var cssUrls = CssUrls.derive(editor);
  13236. if (isSkinDisabled(editor) === false) {
  13237. editor.contentCSS.push(cssUrls.content);
  13238. global$1.DOM.styleSheetLoader.load(cssUrls.ui, SkinLoaded.fireSkinLoaded(editor));
  13239. } else {
  13240. SkinLoaded.fireSkinLoaded(editor)();
  13241. }
  13242. var doScrollIntoView = function () {
  13243. editor.fire('ScrollIntoView');
  13244. };
  13245. var realm = detect$3().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  13246. var original = Element.fromDom(targetNode);
  13247. attachSystemAfter(original, realm.system());
  13248. var findFocusIn = function (elem) {
  13249. return search(elem).bind(function (focused) {
  13250. return realm.system().getByDom(focused).toOption();
  13251. });
  13252. };
  13253. var outerWindow = targetNode.ownerDocument.defaultView;
  13254. var orientation = Orientation.onChange(outerWindow, {
  13255. onChange: function () {
  13256. var alloy = realm.system();
  13257. alloy.broadcastOn([TinyChannels.orientationChanged()], { width: Orientation.getActualWidth(outerWindow) });
  13258. },
  13259. onReady: noop
  13260. });
  13261. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  13262. if (ro === false) {
  13263. editor.selection.collapse();
  13264. }
  13265. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  13266. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  13267. editor.setMode(ro === true ? 'readonly' : 'design');
  13268. editor.fire(ro === true ? READING() : EDITING());
  13269. realm.updateMode(ro);
  13270. };
  13271. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  13272. var dynamic = dynamicGroup.get();
  13273. var toolbars = {
  13274. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  13275. main: dynamic.backToMask.concat(mainGroups.get())
  13276. };
  13277. return toolbars;
  13278. };
  13279. var bindHandler = function (label, handler) {
  13280. editor.on(label, handler);
  13281. return {
  13282. unbind: function () {
  13283. editor.off(label);
  13284. }
  13285. };
  13286. };
  13287. editor.on('init', function () {
  13288. realm.init({
  13289. editor: {
  13290. getFrame: function () {
  13291. return Element.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  13292. },
  13293. onDomChanged: function () {
  13294. return { unbind: noop };
  13295. },
  13296. onToReading: function (handler) {
  13297. return bindHandler(READING(), handler);
  13298. },
  13299. onToEditing: function (handler) {
  13300. return bindHandler(EDITING(), handler);
  13301. },
  13302. onScrollToCursor: function (handler) {
  13303. editor.on('ScrollIntoView', function (tinyEvent) {
  13304. handler(tinyEvent);
  13305. });
  13306. var unbind = function () {
  13307. editor.off('ScrollIntoView');
  13308. orientation.destroy();
  13309. };
  13310. return { unbind: unbind };
  13311. },
  13312. onTouchToolstrip: function () {
  13313. hideDropup();
  13314. },
  13315. onTouchContent: function () {
  13316. var toolbar = Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar')));
  13317. findFocusIn(toolbar).each(emitExecute);
  13318. realm.restoreToolbar();
  13319. hideDropup();
  13320. },
  13321. onTapContent: function (evt) {
  13322. var target = evt.target();
  13323. if (name(target) === 'img') {
  13324. editor.selection.select(target.dom());
  13325. evt.kill();
  13326. } else if (name(target) === 'a') {
  13327. var component = realm.system().getByDom(Element.fromDom(editor.editorContainer));
  13328. component.each(function (container) {
  13329. if (Swapping.isAlpha(container)) {
  13330. TinyCodeDupe.openLink(target.dom());
  13331. }
  13332. });
  13333. }
  13334. }
  13335. },
  13336. container: Element.fromDom(editor.editorContainer),
  13337. socket: Element.fromDom(editor.contentAreaContainer),
  13338. toolstrip: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolstrip'))),
  13339. toolbar: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar'))),
  13340. dropup: realm.dropup(),
  13341. alloy: realm.system(),
  13342. translate: noop,
  13343. setReadOnly: function (ro) {
  13344. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  13345. },
  13346. readOnlyOnInit: function () {
  13347. return readOnlyOnInit();
  13348. }
  13349. });
  13350. var hideDropup = function () {
  13351. realm.dropup().disappear(function () {
  13352. realm.system().broadcastOn([TinyChannels.dropupDismissed()], {});
  13353. });
  13354. };
  13355. var backToMaskGroup = {
  13356. label: 'The first group',
  13357. scrollable: false,
  13358. items: [Buttons.forToolbar('back', function () {
  13359. editor.selection.collapse();
  13360. realm.exit();
  13361. }, {}, editor)]
  13362. };
  13363. var backToReadOnlyGroup = {
  13364. label: 'Back to read only',
  13365. scrollable: false,
  13366. items: [Buttons.forToolbar('readonly-back', function () {
  13367. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  13368. }, {}, editor)]
  13369. };
  13370. var readOnlyGroup = {
  13371. label: 'The read only mode group',
  13372. scrollable: true,
  13373. items: []
  13374. };
  13375. var features = Features.setup(realm, editor);
  13376. var items = Features.detect(editor.settings, features);
  13377. var actionGroup = {
  13378. label: 'the action group',
  13379. scrollable: true,
  13380. items: items
  13381. };
  13382. var extraGroup = {
  13383. label: 'The extra group',
  13384. scrollable: false,
  13385. items: []
  13386. };
  13387. var mainGroups = Cell([
  13388. actionGroup,
  13389. extraGroup
  13390. ]);
  13391. var readOnlyGroups = Cell([
  13392. readOnlyGroup,
  13393. extraGroup
  13394. ]);
  13395. var dynamicGroup = Cell({
  13396. backToMask: [backToMaskGroup],
  13397. backToReadOnly: [backToReadOnlyGroup]
  13398. });
  13399. FormatChangers.init(realm, editor);
  13400. });
  13401. editor.on('remove', function () {
  13402. realm.exit();
  13403. });
  13404. editor.on('detach', function () {
  13405. detachSystem(realm.system());
  13406. realm.system().destroy();
  13407. });
  13408. return {
  13409. iframeContainer: realm.socket().element().dom(),
  13410. editorContainer: realm.element().dom()
  13411. };
  13412. };
  13413. return {
  13414. getNotificationManagerImpl: function () {
  13415. return {
  13416. open: constant({
  13417. progressBar: { value: noop },
  13418. close: noop,
  13419. text: noop,
  13420. getEl: constant(null),
  13421. moveTo: noop,
  13422. moveRel: noop,
  13423. settings: {}
  13424. }),
  13425. close: noop,
  13426. reposition: noop,
  13427. getArgs: constant({})
  13428. };
  13429. },
  13430. renderUI: renderUI
  13431. };
  13432. };
  13433. function Theme () {
  13434. global$2.add('mobile', renderMobileTheme);
  13435. }
  13436. Theme();
  13437. }(window));