theme.js 444 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539
  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.3.0 (2020-05-21)
  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 (t) {
  78. return !f(t);
  79. };
  80. };
  81. var die = function (msg) {
  82. return function () {
  83. throw new Error(msg);
  84. };
  85. };
  86. var apply = function (f) {
  87. return f();
  88. };
  89. var never = constant(false);
  90. var always = constant(true);
  91. var none = function () {
  92. return NONE;
  93. };
  94. var NONE = function () {
  95. var eq = function (o) {
  96. return o.isNone();
  97. };
  98. var call = function (thunk) {
  99. return thunk();
  100. };
  101. var id = function (n) {
  102. return n;
  103. };
  104. var me = {
  105. fold: function (n, _s) {
  106. return n();
  107. },
  108. is: never,
  109. isSome: never,
  110. isNone: always,
  111. getOr: id,
  112. getOrThunk: call,
  113. getOrDie: function (msg) {
  114. throw new Error(msg || 'error: getOrDie called on none.');
  115. },
  116. getOrNull: constant(null),
  117. getOrUndefined: constant(undefined),
  118. or: id,
  119. orThunk: call,
  120. map: none,
  121. each: noop,
  122. bind: none,
  123. exists: never,
  124. forall: always,
  125. filter: none,
  126. equals: eq,
  127. equals_: eq,
  128. toArray: function () {
  129. return [];
  130. },
  131. toString: constant('none()')
  132. };
  133. return me;
  134. }();
  135. var some = function (a) {
  136. var constant_a = constant(a);
  137. var self = function () {
  138. return me;
  139. };
  140. var bind = function (f) {
  141. return f(a);
  142. };
  143. var me = {
  144. fold: function (n, s) {
  145. return s(a);
  146. },
  147. is: function (v) {
  148. return a === v;
  149. },
  150. isSome: always,
  151. isNone: never,
  152. getOr: constant_a,
  153. getOrThunk: constant_a,
  154. getOrDie: constant_a,
  155. getOrNull: constant_a,
  156. getOrUndefined: constant_a,
  157. or: self,
  158. orThunk: self,
  159. map: function (f) {
  160. return some(f(a));
  161. },
  162. each: function (f) {
  163. f(a);
  164. },
  165. bind: bind,
  166. exists: bind,
  167. forall: bind,
  168. filter: function (f) {
  169. return f(a) ? me : NONE;
  170. },
  171. toArray: function () {
  172. return [a];
  173. },
  174. toString: function () {
  175. return 'some(' + a + ')';
  176. },
  177. equals: function (o) {
  178. return o.is(a);
  179. },
  180. equals_: function (o, elementEq) {
  181. return o.fold(never, function (b) {
  182. return elementEq(a, b);
  183. });
  184. }
  185. };
  186. return me;
  187. };
  188. var from = function (value) {
  189. return value === null || value === undefined ? NONE : some(value);
  190. };
  191. var Option = {
  192. some: some,
  193. none: none,
  194. from: from
  195. };
  196. var keys = Object.keys;
  197. var hasOwnProperty = Object.hasOwnProperty;
  198. var each = function (obj, f) {
  199. var props = keys(obj);
  200. for (var k = 0, len = props.length; k < len; k++) {
  201. var i = props[k];
  202. var x = obj[i];
  203. f(x, i);
  204. }
  205. };
  206. var map = function (obj, f) {
  207. return tupleMap(obj, function (x, i) {
  208. return {
  209. k: i,
  210. v: f(x, i)
  211. };
  212. });
  213. };
  214. var tupleMap = function (obj, f) {
  215. var r = {};
  216. each(obj, function (x, i) {
  217. var tuple = f(x, i);
  218. r[tuple.k] = tuple.v;
  219. });
  220. return r;
  221. };
  222. var objAcc = function (r) {
  223. return function (x, i) {
  224. r[i] = x;
  225. };
  226. };
  227. var internalFilter = function (obj, pred, onTrue, onFalse) {
  228. var r = {};
  229. each(obj, function (x, i) {
  230. (pred(x, i) ? onTrue : onFalse)(x, i);
  231. });
  232. return r;
  233. };
  234. var filter = function (obj, pred) {
  235. var t = {};
  236. internalFilter(obj, pred, objAcc(t), noop);
  237. return t;
  238. };
  239. var mapToArray = function (obj, f) {
  240. var r = [];
  241. each(obj, function (value, name) {
  242. r.push(f(value, name));
  243. });
  244. return r;
  245. };
  246. var find = function (obj, pred) {
  247. var props = keys(obj);
  248. for (var k = 0, len = props.length; k < len; k++) {
  249. var i = props[k];
  250. var x = obj[i];
  251. if (pred(x, i, obj)) {
  252. return Option.some(x);
  253. }
  254. }
  255. return Option.none();
  256. };
  257. var values = function (obj) {
  258. return mapToArray(obj, function (v) {
  259. return v;
  260. });
  261. };
  262. var get = function (obj, key) {
  263. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  264. };
  265. var has = function (obj, key) {
  266. return hasOwnProperty.call(obj, key);
  267. };
  268. var hasNonNullableKey = function (obj, key) {
  269. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  270. };
  271. var cached = function (f) {
  272. var called = false;
  273. var r;
  274. return function () {
  275. var args = [];
  276. for (var _i = 0; _i < arguments.length; _i++) {
  277. args[_i] = arguments[_i];
  278. }
  279. if (!called) {
  280. called = true;
  281. r = f.apply(null, args);
  282. }
  283. return r;
  284. };
  285. };
  286. var firstMatch = function (regexes, s) {
  287. for (var i = 0; i < regexes.length; i++) {
  288. var x = regexes[i];
  289. if (x.test(s)) {
  290. return x;
  291. }
  292. }
  293. return undefined;
  294. };
  295. var find$1 = function (regexes, agent) {
  296. var r = firstMatch(regexes, agent);
  297. if (!r) {
  298. return {
  299. major: 0,
  300. minor: 0
  301. };
  302. }
  303. var group = function (i) {
  304. return Number(agent.replace(r, '$' + i));
  305. };
  306. return nu(group(1), group(2));
  307. };
  308. var detect = function (versionRegexes, agent) {
  309. var cleanedAgent = String(agent).toLowerCase();
  310. if (versionRegexes.length === 0) {
  311. return unknown();
  312. }
  313. return find$1(versionRegexes, cleanedAgent);
  314. };
  315. var unknown = function () {
  316. return nu(0, 0);
  317. };
  318. var nu = function (major, minor) {
  319. return {
  320. major: major,
  321. minor: minor
  322. };
  323. };
  324. var Version = {
  325. nu: nu,
  326. detect: detect,
  327. unknown: unknown
  328. };
  329. var edge = 'Edge';
  330. var chrome = 'Chrome';
  331. var ie = 'IE';
  332. var opera = 'Opera';
  333. var firefox = 'Firefox';
  334. var safari = 'Safari';
  335. var unknown$1 = function () {
  336. return nu$1({
  337. current: undefined,
  338. version: Version.unknown()
  339. });
  340. };
  341. var nu$1 = function (info) {
  342. var current = info.current;
  343. var version = info.version;
  344. var isBrowser = function (name) {
  345. return function () {
  346. return current === name;
  347. };
  348. };
  349. return {
  350. current: current,
  351. version: version,
  352. isEdge: isBrowser(edge),
  353. isChrome: isBrowser(chrome),
  354. isIE: isBrowser(ie),
  355. isOpera: isBrowser(opera),
  356. isFirefox: isBrowser(firefox),
  357. isSafari: isBrowser(safari)
  358. };
  359. };
  360. var Browser = {
  361. unknown: unknown$1,
  362. nu: nu$1,
  363. edge: constant(edge),
  364. chrome: constant(chrome),
  365. ie: constant(ie),
  366. opera: constant(opera),
  367. firefox: constant(firefox),
  368. safari: constant(safari)
  369. };
  370. var windows = 'Windows';
  371. var ios = 'iOS';
  372. var android = 'Android';
  373. var linux = 'Linux';
  374. var osx = 'OSX';
  375. var solaris = 'Solaris';
  376. var freebsd = 'FreeBSD';
  377. var chromeos = 'ChromeOS';
  378. var unknown$2 = function () {
  379. return nu$2({
  380. current: undefined,
  381. version: Version.unknown()
  382. });
  383. };
  384. var nu$2 = function (info) {
  385. var current = info.current;
  386. var version = info.version;
  387. var isOS = function (name) {
  388. return function () {
  389. return current === name;
  390. };
  391. };
  392. return {
  393. current: current,
  394. version: version,
  395. isWindows: isOS(windows),
  396. isiOS: isOS(ios),
  397. isAndroid: isOS(android),
  398. isOSX: isOS(osx),
  399. isLinux: isOS(linux),
  400. isSolaris: isOS(solaris),
  401. isFreeBSD: isOS(freebsd),
  402. isChromeOS: isOS(chromeos)
  403. };
  404. };
  405. var OperatingSystem = {
  406. unknown: unknown$2,
  407. nu: nu$2,
  408. windows: constant(windows),
  409. ios: constant(ios),
  410. android: constant(android),
  411. linux: constant(linux),
  412. osx: constant(osx),
  413. solaris: constant(solaris),
  414. freebsd: constant(freebsd),
  415. chromeos: constant(chromeos)
  416. };
  417. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  418. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  419. var isiPhone = os.isiOS() && !isiPad;
  420. var isMobile = os.isiOS() || os.isAndroid();
  421. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  422. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  423. var isPhone = isiPhone || isMobile && !isTablet;
  424. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  425. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  426. return {
  427. isiPad: constant(isiPad),
  428. isiPhone: constant(isiPhone),
  429. isTablet: constant(isTablet),
  430. isPhone: constant(isPhone),
  431. isTouch: constant(isTouch),
  432. isAndroid: os.isAndroid,
  433. isiOS: os.isiOS,
  434. isWebView: constant(iOSwebview),
  435. isDesktop: constant(isDesktop)
  436. };
  437. };
  438. var typeOf = function (x) {
  439. var t = typeof x;
  440. if (x === null) {
  441. return 'null';
  442. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  443. return 'array';
  444. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  445. return 'string';
  446. } else {
  447. return t;
  448. }
  449. };
  450. var isType = function (type) {
  451. return function (value) {
  452. return typeOf(value) === type;
  453. };
  454. };
  455. var isSimpleType = function (type) {
  456. return function (value) {
  457. return typeof value === type;
  458. };
  459. };
  460. var isString = isType('string');
  461. var isObject = isType('object');
  462. var isArray = isType('array');
  463. var isBoolean = isSimpleType('boolean');
  464. var isFunction = isSimpleType('function');
  465. var isNumber = isSimpleType('number');
  466. var nativeSlice = Array.prototype.slice;
  467. var nativeIndexOf = Array.prototype.indexOf;
  468. var nativePush = Array.prototype.push;
  469. var rawIndexOf = function (ts, t) {
  470. return nativeIndexOf.call(ts, t);
  471. };
  472. var contains = function (xs, x) {
  473. return rawIndexOf(xs, x) > -1;
  474. };
  475. var exists = function (xs, pred) {
  476. for (var i = 0, len = xs.length; i < len; i++) {
  477. var x = xs[i];
  478. if (pred(x, i)) {
  479. return true;
  480. }
  481. }
  482. return false;
  483. };
  484. var map$1 = function (xs, f) {
  485. var len = xs.length;
  486. var r = new Array(len);
  487. for (var i = 0; i < len; i++) {
  488. var x = xs[i];
  489. r[i] = f(x, i);
  490. }
  491. return r;
  492. };
  493. var each$1 = function (xs, f) {
  494. for (var i = 0, len = xs.length; i < len; i++) {
  495. var x = xs[i];
  496. f(x, i);
  497. }
  498. };
  499. var eachr = function (xs, f) {
  500. for (var i = xs.length - 1; i >= 0; i--) {
  501. var x = xs[i];
  502. f(x, i);
  503. }
  504. };
  505. var filter$1 = function (xs, pred) {
  506. var r = [];
  507. for (var i = 0, len = xs.length; i < len; i++) {
  508. var x = xs[i];
  509. if (pred(x, i)) {
  510. r.push(x);
  511. }
  512. }
  513. return r;
  514. };
  515. var foldr = function (xs, f, acc) {
  516. eachr(xs, function (x) {
  517. acc = f(acc, x);
  518. });
  519. return acc;
  520. };
  521. var foldl = function (xs, f, acc) {
  522. each$1(xs, function (x) {
  523. acc = f(acc, x);
  524. });
  525. return acc;
  526. };
  527. var findUntil = function (xs, pred, until) {
  528. for (var i = 0, len = xs.length; i < len; i++) {
  529. var x = xs[i];
  530. if (pred(x, i)) {
  531. return Option.some(x);
  532. } else if (until(x, i)) {
  533. break;
  534. }
  535. }
  536. return Option.none();
  537. };
  538. var find$2 = function (xs, pred) {
  539. return findUntil(xs, pred, never);
  540. };
  541. var findIndex = function (xs, pred) {
  542. for (var i = 0, len = xs.length; i < len; i++) {
  543. var x = xs[i];
  544. if (pred(x, i)) {
  545. return Option.some(i);
  546. }
  547. }
  548. return Option.none();
  549. };
  550. var flatten = function (xs) {
  551. var r = [];
  552. for (var i = 0, len = xs.length; i < len; ++i) {
  553. if (!isArray(xs[i])) {
  554. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  555. }
  556. nativePush.apply(r, xs[i]);
  557. }
  558. return r;
  559. };
  560. var bind = function (xs, f) {
  561. return flatten(map$1(xs, f));
  562. };
  563. var forall = function (xs, pred) {
  564. for (var i = 0, len = xs.length; i < len; ++i) {
  565. var x = xs[i];
  566. if (pred(x, i) !== true) {
  567. return false;
  568. }
  569. }
  570. return true;
  571. };
  572. var reverse = function (xs) {
  573. var r = nativeSlice.call(xs, 0);
  574. r.reverse();
  575. return r;
  576. };
  577. var difference = function (a1, a2) {
  578. return filter$1(a1, function (x) {
  579. return !contains(a2, x);
  580. });
  581. };
  582. var pure = function (x) {
  583. return [x];
  584. };
  585. var sort = function (xs, comparator) {
  586. var copy = nativeSlice.call(xs, 0);
  587. copy.sort(comparator);
  588. return copy;
  589. };
  590. var findMap = function (arr, f) {
  591. for (var i = 0; i < arr.length; i++) {
  592. var r = f(arr[i], i);
  593. if (r.isSome()) {
  594. return r;
  595. }
  596. }
  597. return Option.none();
  598. };
  599. var detect$1 = function (candidates, userAgent) {
  600. var agent = String(userAgent).toLowerCase();
  601. return find$2(candidates, function (candidate) {
  602. return candidate.search(agent);
  603. });
  604. };
  605. var detectBrowser = function (browsers, userAgent) {
  606. return detect$1(browsers, userAgent).map(function (browser) {
  607. var version = Version.detect(browser.versionRegexes, userAgent);
  608. return {
  609. current: browser.name,
  610. version: version
  611. };
  612. });
  613. };
  614. var detectOs = function (oses, userAgent) {
  615. return detect$1(oses, userAgent).map(function (os) {
  616. var version = Version.detect(os.versionRegexes, userAgent);
  617. return {
  618. current: os.name,
  619. version: version
  620. };
  621. });
  622. };
  623. var UaString = {
  624. detectBrowser: detectBrowser,
  625. detectOs: detectOs
  626. };
  627. var checkRange = function (str, substr, start) {
  628. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  629. };
  630. var supplant = function (str, obj) {
  631. var isStringOrNumber = function (a) {
  632. var t = typeof a;
  633. return t === 'string' || t === 'number';
  634. };
  635. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  636. var value = obj[key];
  637. return isStringOrNumber(value) ? value.toString() : fullMatch;
  638. });
  639. };
  640. var contains$1 = function (str, substr) {
  641. return str.indexOf(substr) !== -1;
  642. };
  643. var endsWith = function (str, suffix) {
  644. return checkRange(str, suffix, str.length - suffix.length);
  645. };
  646. var blank = function (r) {
  647. return function (s) {
  648. return s.replace(r, '');
  649. };
  650. };
  651. var trim = blank(/^\s+|\s+$/g);
  652. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  653. var checkContains = function (target) {
  654. return function (uastring) {
  655. return contains$1(uastring, target);
  656. };
  657. };
  658. var browsers = [
  659. {
  660. name: 'Edge',
  661. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  662. search: function (uastring) {
  663. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  664. }
  665. },
  666. {
  667. name: 'Chrome',
  668. versionRegexes: [
  669. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  670. normalVersionRegex
  671. ],
  672. search: function (uastring) {
  673. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  674. }
  675. },
  676. {
  677. name: 'IE',
  678. versionRegexes: [
  679. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  680. /.*?rv:([0-9]+)\.([0-9]+).*/
  681. ],
  682. search: function (uastring) {
  683. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  684. }
  685. },
  686. {
  687. name: 'Opera',
  688. versionRegexes: [
  689. normalVersionRegex,
  690. /.*?opera\/([0-9]+)\.([0-9]+).*/
  691. ],
  692. search: checkContains('opera')
  693. },
  694. {
  695. name: 'Firefox',
  696. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  697. search: checkContains('firefox')
  698. },
  699. {
  700. name: 'Safari',
  701. versionRegexes: [
  702. normalVersionRegex,
  703. /.*?cpu os ([0-9]+)_([0-9]+).*/
  704. ],
  705. search: function (uastring) {
  706. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  707. }
  708. }
  709. ];
  710. var oses = [
  711. {
  712. name: 'Windows',
  713. search: checkContains('win'),
  714. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  715. },
  716. {
  717. name: 'iOS',
  718. search: function (uastring) {
  719. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  720. },
  721. versionRegexes: [
  722. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  723. /.*cpu os ([0-9]+)_([0-9]+).*/,
  724. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  725. ]
  726. },
  727. {
  728. name: 'Android',
  729. search: checkContains('android'),
  730. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  731. },
  732. {
  733. name: 'OSX',
  734. search: checkContains('mac os x'),
  735. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  736. },
  737. {
  738. name: 'Linux',
  739. search: checkContains('linux'),
  740. versionRegexes: []
  741. },
  742. {
  743. name: 'Solaris',
  744. search: checkContains('sunos'),
  745. versionRegexes: []
  746. },
  747. {
  748. name: 'FreeBSD',
  749. search: checkContains('freebsd'),
  750. versionRegexes: []
  751. },
  752. {
  753. name: 'ChromeOS',
  754. search: checkContains('cros'),
  755. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  756. }
  757. ];
  758. var PlatformInfo = {
  759. browsers: constant(browsers),
  760. oses: constant(oses)
  761. };
  762. var detect$2 = function (userAgent, mediaMatch) {
  763. var browsers = PlatformInfo.browsers();
  764. var oses = PlatformInfo.oses();
  765. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  766. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  767. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  768. return {
  769. browser: browser,
  770. os: os,
  771. deviceType: deviceType
  772. };
  773. };
  774. var PlatformDetection = { detect: detect$2 };
  775. var mediaMatch = function (query) {
  776. return domGlobals.window.matchMedia(query).matches;
  777. };
  778. var platform = cached(function () {
  779. return PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch);
  780. });
  781. var detect$3 = function () {
  782. return platform();
  783. };
  784. var touchstart = constant('touchstart');
  785. var touchmove = constant('touchmove');
  786. var touchend = constant('touchend');
  787. var mousedown = constant('mousedown');
  788. var mousemove = constant('mousemove');
  789. var mouseup = constant('mouseup');
  790. var mouseover = constant('mouseover');
  791. var keydown = constant('keydown');
  792. var keyup = constant('keyup');
  793. var input = constant('input');
  794. var change = constant('change');
  795. var click = constant('click');
  796. var transitionend = constant('transitionend');
  797. var selectstart = constant('selectstart');
  798. var alloy = { tap: constant('alloy.tap') };
  799. var focus = constant('alloy.focus');
  800. var postBlur = constant('alloy.blur.post');
  801. var postPaste = constant('alloy.paste.post');
  802. var receive = constant('alloy.receive');
  803. var execute = constant('alloy.execute');
  804. var focusItem = constant('alloy.focus.item');
  805. var tap = alloy.tap;
  806. var longpress = constant('alloy.longpress');
  807. var systemInit = constant('alloy.system.init');
  808. var attachedToDom = constant('alloy.system.attached');
  809. var detachedFromDom = constant('alloy.system.detached');
  810. var focusShifted = constant('alloy.focusmanager.shifted');
  811. var highlight = constant('alloy.highlight');
  812. var dehighlight = constant('alloy.dehighlight');
  813. var emit = function (component, event) {
  814. dispatchWith(component, component.element(), event, {});
  815. };
  816. var emitWith = function (component, event, properties) {
  817. dispatchWith(component, component.element(), event, properties);
  818. };
  819. var emitExecute = function (component) {
  820. emit(component, execute());
  821. };
  822. var dispatch = function (component, target, event) {
  823. dispatchWith(component, target, event, {});
  824. };
  825. var dispatchWith = function (component, target, event, properties) {
  826. var data = __assign({ target: target }, properties);
  827. component.getSystem().triggerEvent(event, target, map(data, constant));
  828. };
  829. var dispatchEvent = function (component, target, event, simulatedEvent) {
  830. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  831. };
  832. var dispatchFocus = function (component, target) {
  833. component.getSystem().triggerFocus(target, component.element());
  834. };
  835. var fromHtml = function (html, scope) {
  836. var doc = scope || domGlobals.document;
  837. var div = doc.createElement('div');
  838. div.innerHTML = html;
  839. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  840. domGlobals.console.error('HTML does not have a single root node', html);
  841. throw new Error('HTML must have a single root node');
  842. }
  843. return fromDom(div.childNodes[0]);
  844. };
  845. var fromTag = function (tag, scope) {
  846. var doc = scope || domGlobals.document;
  847. var node = doc.createElement(tag);
  848. return fromDom(node);
  849. };
  850. var fromText = function (text, scope) {
  851. var doc = scope || domGlobals.document;
  852. var node = doc.createTextNode(text);
  853. return fromDom(node);
  854. };
  855. var fromDom = function (node) {
  856. if (node === null || node === undefined) {
  857. throw new Error('Node cannot be null or undefined');
  858. }
  859. return { dom: constant(node) };
  860. };
  861. var fromPoint = function (docElm, x, y) {
  862. var doc = docElm.dom();
  863. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  864. };
  865. var Element = {
  866. fromHtml: fromHtml,
  867. fromTag: fromTag,
  868. fromText: fromText,
  869. fromDom: fromDom,
  870. fromPoint: fromPoint
  871. };
  872. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  873. var DOCUMENT = 9;
  874. var ELEMENT = 1;
  875. var TEXT = 3;
  876. var name = function (element) {
  877. var r = element.dom().nodeName;
  878. return r.toLowerCase();
  879. };
  880. var type = function (element) {
  881. return element.dom().nodeType;
  882. };
  883. var isType$1 = function (t) {
  884. return function (element) {
  885. return type(element) === t;
  886. };
  887. };
  888. var isElement = isType$1(ELEMENT);
  889. var isText = isType$1(TEXT);
  890. var inBody = function (element) {
  891. var dom = isText(element) ? element.dom().parentNode : element.dom();
  892. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  893. };
  894. var body = function () {
  895. return getBody(Element.fromDom(domGlobals.document));
  896. };
  897. var getBody = function (doc) {
  898. var b = doc.dom().body;
  899. if (b === null || b === undefined) {
  900. throw new Error('Body is not available yet');
  901. }
  902. return Element.fromDom(b);
  903. };
  904. var ELEMENT$1 = ELEMENT;
  905. var DOCUMENT$1 = DOCUMENT;
  906. var is = function (element, selector) {
  907. var dom = element.dom();
  908. if (dom.nodeType !== ELEMENT$1) {
  909. return false;
  910. } else {
  911. var elem = dom;
  912. if (elem.matches !== undefined) {
  913. return elem.matches(selector);
  914. } else if (elem.msMatchesSelector !== undefined) {
  915. return elem.msMatchesSelector(selector);
  916. } else if (elem.webkitMatchesSelector !== undefined) {
  917. return elem.webkitMatchesSelector(selector);
  918. } else if (elem.mozMatchesSelector !== undefined) {
  919. return elem.mozMatchesSelector(selector);
  920. } else {
  921. throw new Error('Browser lacks native selectors');
  922. }
  923. }
  924. };
  925. var bypassSelector = function (dom) {
  926. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  927. };
  928. var all = function (selector, scope) {
  929. var base = scope === undefined ? domGlobals.document : scope.dom();
  930. return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), Element.fromDom);
  931. };
  932. var one = function (selector, scope) {
  933. var base = scope === undefined ? domGlobals.document : scope.dom();
  934. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  935. };
  936. var eq = function (e1, e2) {
  937. return e1.dom() === e2.dom();
  938. };
  939. var owner = function (element) {
  940. return Element.fromDom(element.dom().ownerDocument);
  941. };
  942. var defaultView = function (element) {
  943. return Element.fromDom(element.dom().ownerDocument.defaultView);
  944. };
  945. var parent = function (element) {
  946. return Option.from(element.dom().parentNode).map(Element.fromDom);
  947. };
  948. var parents = function (element, isRoot) {
  949. var stop = isFunction(isRoot) ? isRoot : never;
  950. var dom = element.dom();
  951. var ret = [];
  952. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  953. var rawParent = dom.parentNode;
  954. var p = Element.fromDom(rawParent);
  955. ret.push(p);
  956. if (stop(p) === true) {
  957. break;
  958. } else {
  959. dom = rawParent;
  960. }
  961. }
  962. return ret;
  963. };
  964. var siblings = function (element) {
  965. var filterSelf = function (elements) {
  966. return filter$1(elements, function (x) {
  967. return !eq(element, x);
  968. });
  969. };
  970. return parent(element).map(children).map(filterSelf).getOr([]);
  971. };
  972. var nextSibling = function (element) {
  973. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  974. };
  975. var children = function (element) {
  976. return map$1(element.dom().childNodes, Element.fromDom);
  977. };
  978. var child = function (element, index) {
  979. var cs = element.dom().childNodes;
  980. return Option.from(cs[index]).map(Element.fromDom);
  981. };
  982. var firstChild = function (element) {
  983. return child(element, 0);
  984. };
  985. var before = function (marker, element) {
  986. var parent$1 = parent(marker);
  987. parent$1.each(function (v) {
  988. v.dom().insertBefore(element.dom(), marker.dom());
  989. });
  990. };
  991. var after = function (marker, element) {
  992. var sibling = nextSibling(marker);
  993. sibling.fold(function () {
  994. var parent$1 = parent(marker);
  995. parent$1.each(function (v) {
  996. append(v, element);
  997. });
  998. }, function (v) {
  999. before(v, element);
  1000. });
  1001. };
  1002. var prepend = function (parent, element) {
  1003. var firstChild$1 = firstChild(parent);
  1004. firstChild$1.fold(function () {
  1005. append(parent, element);
  1006. }, function (v) {
  1007. parent.dom().insertBefore(element.dom(), v.dom());
  1008. });
  1009. };
  1010. var append = function (parent, element) {
  1011. parent.dom().appendChild(element.dom());
  1012. };
  1013. var appendAt = function (parent, element, index) {
  1014. child(parent, index).fold(function () {
  1015. append(parent, element);
  1016. }, function (v) {
  1017. before(v, element);
  1018. });
  1019. };
  1020. var append$1 = function (parent, elements) {
  1021. each$1(elements, function (x) {
  1022. append(parent, x);
  1023. });
  1024. };
  1025. var empty = function (element) {
  1026. element.dom().textContent = '';
  1027. each$1(children(element), function (rogue) {
  1028. remove(rogue);
  1029. });
  1030. };
  1031. var remove = function (element) {
  1032. var dom = element.dom();
  1033. if (dom.parentNode !== null) {
  1034. dom.parentNode.removeChild(dom);
  1035. }
  1036. };
  1037. var fireDetaching = function (component) {
  1038. emit(component, detachedFromDom());
  1039. var children = component.components();
  1040. each$1(children, fireDetaching);
  1041. };
  1042. var fireAttaching = function (component) {
  1043. var children = component.components();
  1044. each$1(children, fireAttaching);
  1045. emit(component, attachedToDom());
  1046. };
  1047. var attach = function (parent, child) {
  1048. append(parent.element(), child.element());
  1049. };
  1050. var detachChildren = function (component) {
  1051. each$1(component.components(), function (childComp) {
  1052. return remove(childComp.element());
  1053. });
  1054. empty(component.element());
  1055. component.syncComponents();
  1056. };
  1057. var replaceChildren = function (component, newChildren) {
  1058. var subs = component.components();
  1059. detachChildren(component);
  1060. var deleted = difference(subs, newChildren);
  1061. each$1(deleted, function (comp) {
  1062. fireDetaching(comp);
  1063. component.getSystem().removeFromWorld(comp);
  1064. });
  1065. each$1(newChildren, function (childComp) {
  1066. if (!childComp.getSystem().isConnected()) {
  1067. component.getSystem().addToWorld(childComp);
  1068. attach(component, childComp);
  1069. if (inBody(component.element())) {
  1070. fireAttaching(childComp);
  1071. }
  1072. } else {
  1073. attach(component, childComp);
  1074. }
  1075. component.syncComponents();
  1076. });
  1077. };
  1078. var attach$1 = function (parent, child) {
  1079. attachWith(parent, child, append);
  1080. };
  1081. var attachWith = function (parent, child, insertion) {
  1082. parent.getSystem().addToWorld(child);
  1083. insertion(parent.element(), child.element());
  1084. if (inBody(parent.element())) {
  1085. fireAttaching(child);
  1086. }
  1087. parent.syncComponents();
  1088. };
  1089. var doDetach = function (component) {
  1090. fireDetaching(component);
  1091. remove(component.element());
  1092. component.getSystem().removeFromWorld(component);
  1093. };
  1094. var detach = function (component) {
  1095. var parent$1 = parent(component.element()).bind(function (p) {
  1096. return component.getSystem().getByDom(p).toOption();
  1097. });
  1098. doDetach(component);
  1099. parent$1.each(function (p) {
  1100. p.syncComponents();
  1101. });
  1102. };
  1103. var attachSystemAfter = function (element, guiSystem) {
  1104. attachSystemWith(element, guiSystem, after);
  1105. };
  1106. var attachSystemWith = function (element, guiSystem, inserter) {
  1107. inserter(element, guiSystem.element());
  1108. var children$1 = children(guiSystem.element());
  1109. each$1(children$1, function (child) {
  1110. guiSystem.getByDom(child).each(fireAttaching);
  1111. });
  1112. };
  1113. var detachSystem = function (guiSystem) {
  1114. var children$1 = children(guiSystem.element());
  1115. each$1(children$1, function (child) {
  1116. guiSystem.getByDom(child).each(fireDetaching);
  1117. });
  1118. remove(guiSystem.element());
  1119. };
  1120. var value = function (o) {
  1121. var is = function (v) {
  1122. return o === v;
  1123. };
  1124. var or = function (_opt) {
  1125. return value(o);
  1126. };
  1127. var orThunk = function (_f) {
  1128. return value(o);
  1129. };
  1130. var map = function (f) {
  1131. return value(f(o));
  1132. };
  1133. var mapError = function (_f) {
  1134. return value(o);
  1135. };
  1136. var each = function (f) {
  1137. f(o);
  1138. };
  1139. var bind = function (f) {
  1140. return f(o);
  1141. };
  1142. var fold = function (_, onValue) {
  1143. return onValue(o);
  1144. };
  1145. var exists = function (f) {
  1146. return f(o);
  1147. };
  1148. var forall = function (f) {
  1149. return f(o);
  1150. };
  1151. var toOption = function () {
  1152. return Option.some(o);
  1153. };
  1154. return {
  1155. is: is,
  1156. isValue: always,
  1157. isError: never,
  1158. getOr: constant(o),
  1159. getOrThunk: constant(o),
  1160. getOrDie: constant(o),
  1161. or: or,
  1162. orThunk: orThunk,
  1163. fold: fold,
  1164. map: map,
  1165. mapError: mapError,
  1166. each: each,
  1167. bind: bind,
  1168. exists: exists,
  1169. forall: forall,
  1170. toOption: toOption
  1171. };
  1172. };
  1173. var error = function (message) {
  1174. var getOrThunk = function (f) {
  1175. return f();
  1176. };
  1177. var getOrDie = function () {
  1178. return die(String(message))();
  1179. };
  1180. var or = function (opt) {
  1181. return opt;
  1182. };
  1183. var orThunk = function (f) {
  1184. return f();
  1185. };
  1186. var map = function (_f) {
  1187. return error(message);
  1188. };
  1189. var mapError = function (f) {
  1190. return error(f(message));
  1191. };
  1192. var bind = function (_f) {
  1193. return error(message);
  1194. };
  1195. var fold = function (onError, _) {
  1196. return onError(message);
  1197. };
  1198. return {
  1199. is: never,
  1200. isValue: never,
  1201. isError: always,
  1202. getOr: identity,
  1203. getOrThunk: getOrThunk,
  1204. getOrDie: getOrDie,
  1205. or: or,
  1206. orThunk: orThunk,
  1207. fold: fold,
  1208. map: map,
  1209. mapError: mapError,
  1210. each: noop,
  1211. bind: bind,
  1212. exists: never,
  1213. forall: always,
  1214. toOption: Option.none
  1215. };
  1216. };
  1217. var fromOption = function (opt, err) {
  1218. return opt.fold(function () {
  1219. return error(err);
  1220. }, value);
  1221. };
  1222. var Result = {
  1223. value: value,
  1224. error: error,
  1225. fromOption: fromOption
  1226. };
  1227. var generate = function (cases) {
  1228. if (!isArray(cases)) {
  1229. throw new Error('cases must be an array');
  1230. }
  1231. if (cases.length === 0) {
  1232. throw new Error('there must be at least one case');
  1233. }
  1234. var constructors = [];
  1235. var adt = {};
  1236. each$1(cases, function (acase, count) {
  1237. var keys$1 = keys(acase);
  1238. if (keys$1.length !== 1) {
  1239. throw new Error('one and only one name per case');
  1240. }
  1241. var key = keys$1[0];
  1242. var value = acase[key];
  1243. if (adt[key] !== undefined) {
  1244. throw new Error('duplicate key detected:' + key);
  1245. } else if (key === 'cata') {
  1246. throw new Error('cannot have a case named cata (sorry)');
  1247. } else if (!isArray(value)) {
  1248. throw new Error('case arguments must be an array');
  1249. }
  1250. constructors.push(key);
  1251. adt[key] = function () {
  1252. var argLength = arguments.length;
  1253. if (argLength !== value.length) {
  1254. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1255. }
  1256. var args = new Array(argLength);
  1257. for (var i = 0; i < args.length; i++) {
  1258. args[i] = arguments[i];
  1259. }
  1260. var match = function (branches) {
  1261. var branchKeys = keys(branches);
  1262. if (constructors.length !== branchKeys.length) {
  1263. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1264. }
  1265. var allReqd = forall(constructors, function (reqKey) {
  1266. return contains(branchKeys, reqKey);
  1267. });
  1268. if (!allReqd) {
  1269. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1270. }
  1271. return branches[key].apply(null, args);
  1272. };
  1273. return {
  1274. fold: function () {
  1275. if (arguments.length !== cases.length) {
  1276. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  1277. }
  1278. var target = arguments[count];
  1279. return target.apply(null, args);
  1280. },
  1281. match: match,
  1282. log: function (label) {
  1283. domGlobals.console.log(label, {
  1284. constructors: constructors,
  1285. constructor: key,
  1286. params: args
  1287. });
  1288. }
  1289. };
  1290. };
  1291. });
  1292. return adt;
  1293. };
  1294. var Adt = { generate: generate };
  1295. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  1296. var shallow = function (old, nu) {
  1297. return nu;
  1298. };
  1299. var deep = function (old, nu) {
  1300. var bothObjects = isObject(old) && isObject(nu);
  1301. return bothObjects ? deepMerge(old, nu) : nu;
  1302. };
  1303. var baseMerge = function (merger) {
  1304. return function () {
  1305. var objects = new Array(arguments.length);
  1306. for (var i = 0; i < objects.length; i++) {
  1307. objects[i] = arguments[i];
  1308. }
  1309. if (objects.length === 0) {
  1310. throw new Error('Can\'t merge zero objects');
  1311. }
  1312. var ret = {};
  1313. for (var j = 0; j < objects.length; j++) {
  1314. var curObject = objects[j];
  1315. for (var key in curObject) {
  1316. if (hasOwnProperty$1.call(curObject, key)) {
  1317. ret[key] = merger(ret[key], curObject[key]);
  1318. }
  1319. }
  1320. }
  1321. return ret;
  1322. };
  1323. };
  1324. var deepMerge = baseMerge(deep);
  1325. var merge = baseMerge(shallow);
  1326. var SimpleResultType;
  1327. (function (SimpleResultType) {
  1328. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1329. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1330. }(SimpleResultType || (SimpleResultType = {})));
  1331. var fold = function (res, onError, onValue) {
  1332. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1333. };
  1334. var partition = function (results) {
  1335. var values = [];
  1336. var errors = [];
  1337. each$1(results, function (obj) {
  1338. fold(obj, function (err) {
  1339. return errors.push(err);
  1340. }, function (val) {
  1341. return values.push(val);
  1342. });
  1343. });
  1344. return {
  1345. values: values,
  1346. errors: errors
  1347. };
  1348. };
  1349. var mapError = function (res, f) {
  1350. if (res.stype === SimpleResultType.Error) {
  1351. return {
  1352. stype: SimpleResultType.Error,
  1353. serror: f(res.serror)
  1354. };
  1355. } else {
  1356. return res;
  1357. }
  1358. };
  1359. var map$2 = function (res, f) {
  1360. if (res.stype === SimpleResultType.Value) {
  1361. return {
  1362. stype: SimpleResultType.Value,
  1363. svalue: f(res.svalue)
  1364. };
  1365. } else {
  1366. return res;
  1367. }
  1368. };
  1369. var bind$1 = function (res, f) {
  1370. if (res.stype === SimpleResultType.Value) {
  1371. return f(res.svalue);
  1372. } else {
  1373. return res;
  1374. }
  1375. };
  1376. var bindError = function (res, f) {
  1377. if (res.stype === SimpleResultType.Error) {
  1378. return f(res.serror);
  1379. } else {
  1380. return res;
  1381. }
  1382. };
  1383. var svalue = function (v) {
  1384. return {
  1385. stype: SimpleResultType.Value,
  1386. svalue: v
  1387. };
  1388. };
  1389. var serror = function (e) {
  1390. return {
  1391. stype: SimpleResultType.Error,
  1392. serror: e
  1393. };
  1394. };
  1395. var toResult = function (res) {
  1396. return fold(res, Result.error, Result.value);
  1397. };
  1398. var fromResult = function (res) {
  1399. return res.fold(serror, svalue);
  1400. };
  1401. var SimpleResult = {
  1402. fromResult: fromResult,
  1403. toResult: toResult,
  1404. svalue: svalue,
  1405. partition: partition,
  1406. serror: serror,
  1407. bind: bind$1,
  1408. bindError: bindError,
  1409. map: map$2,
  1410. mapError: mapError,
  1411. fold: fold
  1412. };
  1413. var adt = Adt.generate([
  1414. { strict: [] },
  1415. { defaultedThunk: ['fallbackThunk'] },
  1416. { asOption: [] },
  1417. { asDefaultedOptionThunk: ['fallbackThunk'] },
  1418. { mergeWithThunk: ['baseThunk'] }
  1419. ]);
  1420. var defaulted = function (fallback) {
  1421. return adt.defaultedThunk(constant(fallback));
  1422. };
  1423. var mergeWith = function (base) {
  1424. return adt.mergeWithThunk(constant(base));
  1425. };
  1426. var strict = adt.strict;
  1427. var asOption = adt.asOption;
  1428. var defaultedThunk = adt.defaultedThunk;
  1429. var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
  1430. var mergeWithThunk = adt.mergeWithThunk;
  1431. var exclude = function (obj, fields) {
  1432. var r = {};
  1433. each(obj, function (v, k) {
  1434. if (!contains(fields, k)) {
  1435. r[k] = v;
  1436. }
  1437. });
  1438. return r;
  1439. };
  1440. var wrap = function (key, value) {
  1441. var _a;
  1442. return _a = {}, _a[key] = value, _a;
  1443. };
  1444. var wrapAll = function (keyvalues) {
  1445. var r = {};
  1446. each$1(keyvalues, function (kv) {
  1447. r[kv.key] = kv.value;
  1448. });
  1449. return r;
  1450. };
  1451. var comparison = Adt.generate([
  1452. {
  1453. bothErrors: [
  1454. 'error1',
  1455. 'error2'
  1456. ]
  1457. },
  1458. {
  1459. firstError: [
  1460. 'error1',
  1461. 'value2'
  1462. ]
  1463. },
  1464. {
  1465. secondError: [
  1466. 'value1',
  1467. 'error2'
  1468. ]
  1469. },
  1470. {
  1471. bothValues: [
  1472. 'value1',
  1473. 'value2'
  1474. ]
  1475. }
  1476. ]);
  1477. var partition$1 = function (results) {
  1478. var errors = [];
  1479. var values = [];
  1480. each$1(results, function (result) {
  1481. result.fold(function (err) {
  1482. errors.push(err);
  1483. }, function (value) {
  1484. values.push(value);
  1485. });
  1486. });
  1487. return {
  1488. errors: errors,
  1489. values: values
  1490. };
  1491. };
  1492. var exclude$1 = function (obj, fields) {
  1493. return exclude(obj, fields);
  1494. };
  1495. var wrap$1 = function (key, value) {
  1496. return wrap(key, value);
  1497. };
  1498. var wrapAll$1 = function (keyvalues) {
  1499. return wrapAll(keyvalues);
  1500. };
  1501. var mergeValues = function (values, base) {
  1502. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  1503. };
  1504. var mergeErrors = function (errors) {
  1505. return Result.error(flatten(errors));
  1506. };
  1507. var consolidate = function (objs, base) {
  1508. var partitions = partition$1(objs);
  1509. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  1510. };
  1511. var mergeValues$1 = function (values, base) {
  1512. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  1513. };
  1514. var mergeErrors$1 = function (errors) {
  1515. return compose(SimpleResult.serror, flatten)(errors);
  1516. };
  1517. var consolidateObj = function (objects, base) {
  1518. var partition = SimpleResult.partition(objects);
  1519. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1520. };
  1521. var consolidateArr = function (objects) {
  1522. var partitions = SimpleResult.partition(objects);
  1523. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1524. };
  1525. var ResultCombine = {
  1526. consolidateObj: consolidateObj,
  1527. consolidateArr: consolidateArr
  1528. };
  1529. var formatObj = function (input) {
  1530. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1531. };
  1532. var formatErrors = function (errors) {
  1533. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1534. path: [],
  1535. getErrorInfo: function () {
  1536. return '... (only showing first ten failures)';
  1537. }
  1538. }]) : errors;
  1539. return map$1(es, function (e) {
  1540. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1541. });
  1542. };
  1543. var nu$3 = function (path, getErrorInfo) {
  1544. return SimpleResult.serror([{
  1545. path: path,
  1546. getErrorInfo: getErrorInfo
  1547. }]);
  1548. };
  1549. var missingStrict = function (path, key, obj) {
  1550. return nu$3(path, function () {
  1551. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  1552. });
  1553. };
  1554. var missingKey = function (path, key) {
  1555. return nu$3(path, function () {
  1556. return 'Choice schema did not contain choice key: "' + key + '"';
  1557. });
  1558. };
  1559. var missingBranch = function (path, branches, branch) {
  1560. return nu$3(path, function () {
  1561. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1562. });
  1563. };
  1564. var unsupportedFields = function (path, unsupported) {
  1565. return nu$3(path, function () {
  1566. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1567. });
  1568. };
  1569. var custom = function (path, err) {
  1570. return nu$3(path, function () {
  1571. return err;
  1572. });
  1573. };
  1574. var adt$1 = Adt.generate([
  1575. {
  1576. field: [
  1577. 'key',
  1578. 'okey',
  1579. 'presence',
  1580. 'prop'
  1581. ]
  1582. },
  1583. {
  1584. state: [
  1585. 'okey',
  1586. 'instantiator'
  1587. ]
  1588. }
  1589. ]);
  1590. var strictAccess = function (path, obj, key) {
  1591. return get(obj, key).fold(function () {
  1592. return missingStrict(path, key, obj);
  1593. }, SimpleResult.svalue);
  1594. };
  1595. var fallbackAccess = function (obj, key, fallbackThunk) {
  1596. var v = get(obj, key).fold(function () {
  1597. return fallbackThunk(obj);
  1598. }, identity);
  1599. return SimpleResult.svalue(v);
  1600. };
  1601. var optionAccess = function (obj, key) {
  1602. return SimpleResult.svalue(get(obj, key));
  1603. };
  1604. var optionDefaultedAccess = function (obj, key, fallback) {
  1605. var opt = get(obj, key).map(function (val) {
  1606. return val === true ? fallback(obj) : val;
  1607. });
  1608. return SimpleResult.svalue(opt);
  1609. };
  1610. var cExtractOne = function (path, obj, field, strength) {
  1611. return field.fold(function (key, okey, presence, prop) {
  1612. var bundle = function (av) {
  1613. var result = prop.extract(path.concat([key]), strength, av);
  1614. return SimpleResult.map(result, function (res) {
  1615. return wrap(okey, strength(res));
  1616. });
  1617. };
  1618. var bundleAsOption = function (optValue) {
  1619. return optValue.fold(function () {
  1620. var outcome = wrap(okey, strength(Option.none()));
  1621. return SimpleResult.svalue(outcome);
  1622. }, function (ov) {
  1623. var result = prop.extract(path.concat([key]), strength, ov);
  1624. return SimpleResult.map(result, function (res) {
  1625. return wrap(okey, strength(Option.some(res)));
  1626. });
  1627. });
  1628. };
  1629. return function () {
  1630. return presence.fold(function () {
  1631. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1632. }, function (fallbackThunk) {
  1633. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1634. }, function () {
  1635. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1636. }, function (fallbackThunk) {
  1637. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1638. }, function (baseThunk) {
  1639. var base = baseThunk(obj);
  1640. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1641. return deepMerge(base, v);
  1642. });
  1643. return SimpleResult.bind(result, bundle);
  1644. });
  1645. }();
  1646. }, function (okey, instantiator) {
  1647. var state = instantiator(obj);
  1648. return SimpleResult.svalue(wrap(okey, strength(state)));
  1649. });
  1650. };
  1651. var cExtract = function (path, obj, fields, strength) {
  1652. var results = map$1(fields, function (field) {
  1653. return cExtractOne(path, obj, field, strength);
  1654. });
  1655. return ResultCombine.consolidateObj(results, {});
  1656. };
  1657. var value$1 = function (validator) {
  1658. var extract = function (path, strength, val) {
  1659. return SimpleResult.bindError(validator(val, strength), function (err) {
  1660. return custom(path, err);
  1661. });
  1662. };
  1663. var toString = function () {
  1664. return 'val';
  1665. };
  1666. return {
  1667. extract: extract,
  1668. toString: toString
  1669. };
  1670. };
  1671. var getSetKeys = function (obj) {
  1672. return keys(filter(obj, function (value) {
  1673. return value !== undefined && value !== null;
  1674. }));
  1675. };
  1676. var objOfOnly = function (fields) {
  1677. var delegate = objOf(fields);
  1678. var fieldNames = foldr(fields, function (acc, f) {
  1679. return f.fold(function (key) {
  1680. return deepMerge(acc, wrap$1(key, true));
  1681. }, constant(acc));
  1682. }, {});
  1683. var extract = function (path, strength, o) {
  1684. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1685. var extra = filter$1(keys, function (k) {
  1686. return !hasNonNullableKey(fieldNames, k);
  1687. });
  1688. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1689. };
  1690. return {
  1691. extract: extract,
  1692. toString: delegate.toString
  1693. };
  1694. };
  1695. var objOf = function (fields) {
  1696. var extract = function (path, strength, o) {
  1697. return cExtract(path, o, fields, strength);
  1698. };
  1699. var toString = function () {
  1700. var fieldStrings = map$1(fields, function (field) {
  1701. return field.fold(function (key, okey, presence, prop) {
  1702. return key + ' -> ' + prop.toString();
  1703. }, function (okey, _instantiator) {
  1704. return 'state(' + okey + ')';
  1705. });
  1706. });
  1707. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1708. };
  1709. return {
  1710. extract: extract,
  1711. toString: toString
  1712. };
  1713. };
  1714. var arrOf = function (prop) {
  1715. var extract = function (path, strength, array) {
  1716. var results = map$1(array, function (a, i) {
  1717. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1718. });
  1719. return ResultCombine.consolidateArr(results);
  1720. };
  1721. var toString = function () {
  1722. return 'array(' + prop.toString() + ')';
  1723. };
  1724. return {
  1725. extract: extract,
  1726. toString: toString
  1727. };
  1728. };
  1729. var setOf = function (validator, prop) {
  1730. var validateKeys = function (path, keys) {
  1731. return arrOf(value$1(validator)).extract(path, identity, keys);
  1732. };
  1733. var extract = function (path, strength, o) {
  1734. var keys$1 = keys(o);
  1735. var validatedKeys = validateKeys(path, keys$1);
  1736. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1737. var schema = map$1(validKeys, function (vk) {
  1738. return adt$1.field(vk, vk, strict(), prop);
  1739. });
  1740. return objOf(schema).extract(path, strength, o);
  1741. });
  1742. };
  1743. var toString = function () {
  1744. return 'setOf(' + prop.toString() + ')';
  1745. };
  1746. return {
  1747. extract: extract,
  1748. toString: toString
  1749. };
  1750. };
  1751. var anyValue = constant(value$1(SimpleResult.svalue));
  1752. var state = adt$1.state;
  1753. var field = adt$1.field;
  1754. var chooseFrom = function (path, strength, input, branches, ch) {
  1755. var fields = get(branches, ch);
  1756. return fields.fold(function () {
  1757. return missingBranch(path, branches, ch);
  1758. }, function (vp) {
  1759. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1760. });
  1761. };
  1762. var choose = function (key, branches) {
  1763. var extract = function (path, strength, input) {
  1764. var choice = get(input, key);
  1765. return choice.fold(function () {
  1766. return missingKey(path, key);
  1767. }, function (chosen) {
  1768. return chooseFrom(path, strength, input, branches, chosen);
  1769. });
  1770. };
  1771. var toString = function () {
  1772. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1773. };
  1774. return {
  1775. extract: extract,
  1776. toString: toString
  1777. };
  1778. };
  1779. var _anyValue = value$1(SimpleResult.svalue);
  1780. var valueOf = function (validator) {
  1781. return value$1(function (v) {
  1782. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1783. });
  1784. };
  1785. var setOf$1 = function (validator, prop) {
  1786. return setOf(function (v) {
  1787. return SimpleResult.fromResult(validator(v));
  1788. }, prop);
  1789. };
  1790. var extract = function (label, prop, strength, obj) {
  1791. var res = prop.extract([label], strength, obj);
  1792. return SimpleResult.mapError(res, function (errs) {
  1793. return {
  1794. input: obj,
  1795. errors: errs
  1796. };
  1797. });
  1798. };
  1799. var asRaw = function (label, prop, obj) {
  1800. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1801. };
  1802. var getOrDie = function (extraction) {
  1803. return extraction.fold(function (errInfo) {
  1804. throw new Error(formatError(errInfo));
  1805. }, identity);
  1806. };
  1807. var asRawOrDie = function (label, prop, obj) {
  1808. return getOrDie(asRaw(label, prop, obj));
  1809. };
  1810. var formatError = function (errInfo) {
  1811. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1812. };
  1813. var choose$1 = function (key, branches) {
  1814. return choose(key, map(branches, objOf));
  1815. };
  1816. var anyValue$1 = constant(_anyValue);
  1817. var typedValue = function (validator, expectedType) {
  1818. return value$1(function (a) {
  1819. var actualType = typeof a;
  1820. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1821. });
  1822. };
  1823. var functionProcessor = typedValue(isFunction, 'function');
  1824. var strict$1 = function (key) {
  1825. return field(key, key, strict(), anyValue());
  1826. };
  1827. var strictOf = function (key, schema) {
  1828. return field(key, key, strict(), schema);
  1829. };
  1830. var strictFunction = function (key) {
  1831. return strictOf(key, functionProcessor);
  1832. };
  1833. var forbid = function (key, message) {
  1834. return field(key, key, asOption(), value$1(function (_v) {
  1835. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1836. }));
  1837. };
  1838. var strictObjOf = function (key, objSchema) {
  1839. return field(key, key, strict(), objOf(objSchema));
  1840. };
  1841. var option = function (key) {
  1842. return field(key, key, asOption(), anyValue());
  1843. };
  1844. var optionOf = function (key, schema) {
  1845. return field(key, key, asOption(), schema);
  1846. };
  1847. var optionObjOf = function (key, objSchema) {
  1848. return optionOf(key, objOf(objSchema));
  1849. };
  1850. var optionObjOfOnly = function (key, objSchema) {
  1851. return optionOf(key, objOfOnly(objSchema));
  1852. };
  1853. var defaulted$1 = function (key, fallback) {
  1854. return field(key, key, defaulted(fallback), anyValue());
  1855. };
  1856. var defaultedOf = function (key, fallback, schema) {
  1857. return field(key, key, defaulted(fallback), schema);
  1858. };
  1859. var defaultedFunction = function (key, fallback) {
  1860. return defaultedOf(key, fallback, functionProcessor);
  1861. };
  1862. var defaultedObjOf = function (key, fallback, objSchema) {
  1863. return defaultedOf(key, fallback, objOf(objSchema));
  1864. };
  1865. var state$1 = function (okey, instantiator) {
  1866. return state(okey, instantiator);
  1867. };
  1868. var ensureIsRoot = function (isRoot) {
  1869. return isFunction(isRoot) ? isRoot : constant(false);
  1870. };
  1871. var ancestor = function (scope, transform, isRoot) {
  1872. var element = scope.dom();
  1873. var stop = ensureIsRoot(isRoot);
  1874. while (element.parentNode) {
  1875. element = element.parentNode;
  1876. var el = Element.fromDom(element);
  1877. var transformed = transform(el);
  1878. if (transformed.isSome()) {
  1879. return transformed;
  1880. } else if (stop(el)) {
  1881. break;
  1882. }
  1883. }
  1884. return Option.none();
  1885. };
  1886. var closest = function (scope, transform, isRoot) {
  1887. var current = transform(scope);
  1888. var stop = ensureIsRoot(isRoot);
  1889. return current.orThunk(function () {
  1890. return stop(scope) ? Option.none() : ancestor(scope, transform, stop);
  1891. });
  1892. };
  1893. var isSource = function (component, simulatedEvent) {
  1894. return eq(component.element(), simulatedEvent.event().target());
  1895. };
  1896. var nu$4 = function (parts) {
  1897. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  1898. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  1899. }
  1900. return asRawOrDie('Extracting event.handler', objOfOnly([
  1901. defaulted$1('can', constant(true)),
  1902. defaulted$1('abort', constant(false)),
  1903. defaulted$1('run', noop)
  1904. ]), parts);
  1905. };
  1906. var all$1 = function (handlers, f) {
  1907. return function () {
  1908. var args = [];
  1909. for (var _i = 0; _i < arguments.length; _i++) {
  1910. args[_i] = arguments[_i];
  1911. }
  1912. return foldl(handlers, function (acc, handler) {
  1913. return acc && f(handler).apply(undefined, args);
  1914. }, true);
  1915. };
  1916. };
  1917. var any = function (handlers, f) {
  1918. return function () {
  1919. var args = [];
  1920. for (var _i = 0; _i < arguments.length; _i++) {
  1921. args[_i] = arguments[_i];
  1922. }
  1923. return foldl(handlers, function (acc, handler) {
  1924. return acc || f(handler).apply(undefined, args);
  1925. }, false);
  1926. };
  1927. };
  1928. var read = function (handler) {
  1929. return isFunction(handler) ? {
  1930. can: constant(true),
  1931. abort: constant(false),
  1932. run: handler
  1933. } : handler;
  1934. };
  1935. var fuse = function (handlers) {
  1936. var can = all$1(handlers, function (handler) {
  1937. return handler.can;
  1938. });
  1939. var abort = any(handlers, function (handler) {
  1940. return handler.abort;
  1941. });
  1942. var run = function () {
  1943. var args = [];
  1944. for (var _i = 0; _i < arguments.length; _i++) {
  1945. args[_i] = arguments[_i];
  1946. }
  1947. each$1(handlers, function (handler) {
  1948. handler.run.apply(undefined, args);
  1949. });
  1950. };
  1951. return nu$4({
  1952. can: can,
  1953. abort: abort,
  1954. run: run
  1955. });
  1956. };
  1957. var derive = function (configs) {
  1958. return wrapAll$1(configs);
  1959. };
  1960. var abort = function (name, predicate) {
  1961. return {
  1962. key: name,
  1963. value: nu$4({ abort: predicate })
  1964. };
  1965. };
  1966. var can = function (name, predicate) {
  1967. return {
  1968. key: name,
  1969. value: nu$4({ can: predicate })
  1970. };
  1971. };
  1972. var run = function (name, handler) {
  1973. return {
  1974. key: name,
  1975. value: nu$4({ run: handler })
  1976. };
  1977. };
  1978. var runActionExtra = function (name, action, extra) {
  1979. return {
  1980. key: name,
  1981. value: nu$4({
  1982. run: function (component, simulatedEvent) {
  1983. action.apply(undefined, [
  1984. component,
  1985. simulatedEvent
  1986. ].concat(extra));
  1987. }
  1988. })
  1989. };
  1990. };
  1991. var runOnName = function (name) {
  1992. return function (handler) {
  1993. return run(name, handler);
  1994. };
  1995. };
  1996. var runOnSourceName = function (name) {
  1997. return function (handler) {
  1998. return {
  1999. key: name,
  2000. value: nu$4({
  2001. run: function (component, simulatedEvent) {
  2002. if (isSource(component, simulatedEvent)) {
  2003. handler(component, simulatedEvent);
  2004. }
  2005. }
  2006. })
  2007. };
  2008. };
  2009. };
  2010. var redirectToUid = function (name, uid) {
  2011. return run(name, function (component, simulatedEvent) {
  2012. component.getSystem().getByUid(uid).each(function (redirectee) {
  2013. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2014. });
  2015. });
  2016. };
  2017. var redirectToPart = function (name, detail, partName) {
  2018. var uid = detail.partUids[partName];
  2019. return redirectToUid(name, uid);
  2020. };
  2021. var cutter = function (name) {
  2022. return run(name, function (component, simulatedEvent) {
  2023. simulatedEvent.cut();
  2024. });
  2025. };
  2026. var stopper = function (name) {
  2027. return run(name, function (component, simulatedEvent) {
  2028. simulatedEvent.stop();
  2029. });
  2030. };
  2031. var runOnSource = function (name, f) {
  2032. return runOnSourceName(name)(f);
  2033. };
  2034. var runOnAttached = runOnSourceName(attachedToDom());
  2035. var runOnDetached = runOnSourceName(detachedFromDom());
  2036. var runOnInit = runOnSourceName(systemInit());
  2037. var runOnExecute = runOnName(execute());
  2038. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2039. var delegate = apiFunction.toString();
  2040. var endIndex = delegate.indexOf(')') + 1;
  2041. var openBracketIndex = delegate.indexOf('(');
  2042. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2043. f.toFunctionAnnotation = function () {
  2044. return {
  2045. name: apiName,
  2046. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2047. };
  2048. };
  2049. return f;
  2050. };
  2051. var cleanParameters = function (parameters) {
  2052. return map$1(parameters, function (p) {
  2053. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2054. });
  2055. };
  2056. var markAsExtraApi = function (f, extraName) {
  2057. var delegate = f.toString();
  2058. var endIndex = delegate.indexOf(')') + 1;
  2059. var openBracketIndex = delegate.indexOf('(');
  2060. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2061. f.toFunctionAnnotation = function () {
  2062. return {
  2063. name: extraName,
  2064. parameters: cleanParameters(parameters)
  2065. };
  2066. };
  2067. return f;
  2068. };
  2069. var markAsSketchApi = function (f, apiFunction) {
  2070. var delegate = apiFunction.toString();
  2071. var endIndex = delegate.indexOf(')') + 1;
  2072. var openBracketIndex = delegate.indexOf('(');
  2073. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2074. f.toFunctionAnnotation = function () {
  2075. return {
  2076. name: 'OVERRIDE',
  2077. parameters: cleanParameters(parameters.slice(1))
  2078. };
  2079. };
  2080. return f;
  2081. };
  2082. var nu$5 = function (s) {
  2083. return {
  2084. classes: s.classes !== undefined ? s.classes : [],
  2085. attributes: s.attributes !== undefined ? s.attributes : {},
  2086. styles: s.styles !== undefined ? s.styles : {}
  2087. };
  2088. };
  2089. var merge$1 = function (defnA, mod) {
  2090. return __assign(__assign({}, defnA), {
  2091. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2092. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2093. classes: defnA.classes.concat(mod.classes)
  2094. });
  2095. };
  2096. var executeEvent = function (bConfig, bState, executor) {
  2097. return runOnExecute(function (component) {
  2098. executor(component, bConfig, bState);
  2099. });
  2100. };
  2101. var loadEvent = function (bConfig, bState, f) {
  2102. return runOnInit(function (component, _simulatedEvent) {
  2103. f(component, bConfig, bState);
  2104. });
  2105. };
  2106. var create = function (schema, name, active, apis, extra, state) {
  2107. var configSchema = objOfOnly(schema);
  2108. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2109. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2110. };
  2111. var createModes = function (modes, name, active, apis, extra, state) {
  2112. var configSchema = modes;
  2113. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2114. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2115. };
  2116. var wrapApi = function (bName, apiFunction, apiName) {
  2117. var f = function (component) {
  2118. var rest = [];
  2119. for (var _i = 1; _i < arguments.length; _i++) {
  2120. rest[_i - 1] = arguments[_i];
  2121. }
  2122. var args = [component].concat(rest);
  2123. return component.config({ name: constant(bName) }).fold(function () {
  2124. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2125. }, function (info) {
  2126. var rest = Array.prototype.slice.call(args, 1);
  2127. return apiFunction.apply(undefined, [
  2128. component,
  2129. info.config,
  2130. info.state
  2131. ].concat(rest));
  2132. });
  2133. };
  2134. return markAsBehaviourApi(f, apiName, apiFunction);
  2135. };
  2136. var revokeBehaviour = function (name) {
  2137. return {
  2138. key: name,
  2139. value: undefined
  2140. };
  2141. };
  2142. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2143. var getConfig = function (info) {
  2144. return hasNonNullableKey(info, name) ? info[name]() : Option.none();
  2145. };
  2146. var wrappedApis = map(apis, function (apiF, apiName) {
  2147. return wrapApi(name, apiF, apiName);
  2148. });
  2149. var wrappedExtra = map(extra, function (extraF, extraName) {
  2150. return markAsExtraApi(extraF, extraName);
  2151. });
  2152. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2153. revoke: curry(revokeBehaviour, name),
  2154. config: function (spec) {
  2155. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  2156. return {
  2157. key: name,
  2158. value: {
  2159. config: prepared,
  2160. me: me,
  2161. configAsRaw: cached(function () {
  2162. return asRawOrDie(name + '-config', configSchema, spec);
  2163. }),
  2164. initialConfig: spec,
  2165. state: state
  2166. }
  2167. };
  2168. },
  2169. schema: function () {
  2170. return schemaSchema;
  2171. },
  2172. exhibit: function (info, base) {
  2173. return getConfig(info).bind(function (behaviourInfo) {
  2174. return get(active, 'exhibit').map(function (exhibitor) {
  2175. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2176. });
  2177. }).getOr(nu$5({}));
  2178. },
  2179. name: function () {
  2180. return name;
  2181. },
  2182. handlers: function (info) {
  2183. return getConfig(info).map(function (behaviourInfo) {
  2184. var getEvents = get(active, 'events').getOr(function () {
  2185. return {};
  2186. });
  2187. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2188. }).getOr({});
  2189. }
  2190. });
  2191. return me;
  2192. };
  2193. var NoState = {
  2194. init: function () {
  2195. return nu$6({
  2196. readState: function () {
  2197. return 'No State required';
  2198. }
  2199. });
  2200. }
  2201. };
  2202. var nu$6 = function (spec) {
  2203. return spec;
  2204. };
  2205. var derive$1 = function (capabilities) {
  2206. return wrapAll$1(capabilities);
  2207. };
  2208. var simpleSchema = objOfOnly([
  2209. strict$1('fields'),
  2210. strict$1('name'),
  2211. defaulted$1('active', {}),
  2212. defaulted$1('apis', {}),
  2213. defaulted$1('state', NoState),
  2214. defaulted$1('extra', {})
  2215. ]);
  2216. var create$1 = function (data) {
  2217. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  2218. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2219. };
  2220. var modeSchema = objOfOnly([
  2221. strict$1('branchKey'),
  2222. strict$1('branches'),
  2223. strict$1('name'),
  2224. defaulted$1('active', {}),
  2225. defaulted$1('apis', {}),
  2226. defaulted$1('state', NoState),
  2227. defaulted$1('extra', {})
  2228. ]);
  2229. var createModes$1 = function (data) {
  2230. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  2231. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2232. };
  2233. var revoke = constant(undefined);
  2234. var rawSet = function (dom, key, value) {
  2235. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2236. dom.setAttribute(key, value + '');
  2237. } else {
  2238. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2239. throw new Error('Attribute value was not simple');
  2240. }
  2241. };
  2242. var set = function (element, key, value) {
  2243. rawSet(element.dom(), key, value);
  2244. };
  2245. var setAll = function (element, attrs) {
  2246. var dom = element.dom();
  2247. each(attrs, function (v, k) {
  2248. rawSet(dom, k, v);
  2249. });
  2250. };
  2251. var get$1 = function (element, key) {
  2252. var v = element.dom().getAttribute(key);
  2253. return v === null ? undefined : v;
  2254. };
  2255. var getOpt = function (element, key) {
  2256. return Option.from(get$1(element, key));
  2257. };
  2258. var has$1 = function (element, key) {
  2259. var dom = element.dom();
  2260. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2261. };
  2262. var remove$1 = function (element, key) {
  2263. element.dom().removeAttribute(key);
  2264. };
  2265. var read$1 = function (element, attr) {
  2266. var value = get$1(element, attr);
  2267. return value === undefined || value === '' ? [] : value.split(' ');
  2268. };
  2269. var add = function (element, attr, id) {
  2270. var old = read$1(element, attr);
  2271. var nu = old.concat([id]);
  2272. set(element, attr, nu.join(' '));
  2273. return true;
  2274. };
  2275. var remove$2 = function (element, attr, id) {
  2276. var nu = filter$1(read$1(element, attr), function (v) {
  2277. return v !== id;
  2278. });
  2279. if (nu.length > 0) {
  2280. set(element, attr, nu.join(' '));
  2281. } else {
  2282. remove$1(element, attr);
  2283. }
  2284. return false;
  2285. };
  2286. var supports = function (element) {
  2287. return element.dom().classList !== undefined;
  2288. };
  2289. var get$2 = function (element) {
  2290. return read$1(element, 'class');
  2291. };
  2292. var add$1 = function (element, clazz) {
  2293. return add(element, 'class', clazz);
  2294. };
  2295. var remove$3 = function (element, clazz) {
  2296. return remove$2(element, 'class', clazz);
  2297. };
  2298. var add$2 = function (element, clazz) {
  2299. if (supports(element)) {
  2300. element.dom().classList.add(clazz);
  2301. } else {
  2302. add$1(element, clazz);
  2303. }
  2304. };
  2305. var cleanClass = function (element) {
  2306. var classList = supports(element) ? element.dom().classList : get$2(element);
  2307. if (classList.length === 0) {
  2308. remove$1(element, 'class');
  2309. }
  2310. };
  2311. var remove$4 = function (element, clazz) {
  2312. if (supports(element)) {
  2313. var classList = element.dom().classList;
  2314. classList.remove(clazz);
  2315. } else {
  2316. remove$3(element, clazz);
  2317. }
  2318. cleanClass(element);
  2319. };
  2320. var has$2 = function (element, clazz) {
  2321. return supports(element) && element.dom().classList.contains(clazz);
  2322. };
  2323. var swap = function (element, addCls, removeCls) {
  2324. remove$4(element, removeCls);
  2325. add$2(element, addCls);
  2326. };
  2327. var toAlpha = function (component, swapConfig, _swapState) {
  2328. swap(component.element(), swapConfig.alpha, swapConfig.omega);
  2329. };
  2330. var toOmega = function (component, swapConfig, _swapState) {
  2331. swap(component.element(), swapConfig.omega, swapConfig.alpha);
  2332. };
  2333. var clear = function (component, swapConfig, _swapState) {
  2334. remove$4(component.element(), swapConfig.alpha);
  2335. remove$4(component.element(), swapConfig.omega);
  2336. };
  2337. var isAlpha = function (component, swapConfig, _swapState) {
  2338. return has$2(component.element(), swapConfig.alpha);
  2339. };
  2340. var isOmega = function (component, swapConfig, _swapState) {
  2341. return has$2(component.element(), swapConfig.omega);
  2342. };
  2343. var SwapApis = /*#__PURE__*/Object.freeze({
  2344. __proto__: null,
  2345. toAlpha: toAlpha,
  2346. toOmega: toOmega,
  2347. isAlpha: isAlpha,
  2348. isOmega: isOmega,
  2349. clear: clear
  2350. });
  2351. var SwapSchema = [
  2352. strict$1('alpha'),
  2353. strict$1('omega')
  2354. ];
  2355. var Swapping = create$1({
  2356. fields: SwapSchema,
  2357. name: 'swapping',
  2358. apis: SwapApis
  2359. });
  2360. var Cell = function (initial) {
  2361. var value = initial;
  2362. var get = function () {
  2363. return value;
  2364. };
  2365. var set = function (v) {
  2366. value = v;
  2367. };
  2368. return {
  2369. get: get,
  2370. set: set
  2371. };
  2372. };
  2373. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2374. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  2375. }
  2376. var ancestor$1 = function (scope, predicate, isRoot) {
  2377. var element = scope.dom();
  2378. var stop = isFunction(isRoot) ? isRoot : constant(false);
  2379. while (element.parentNode) {
  2380. element = element.parentNode;
  2381. var el = Element.fromDom(element);
  2382. if (predicate(el)) {
  2383. return Option.some(el);
  2384. } else if (stop(el)) {
  2385. break;
  2386. }
  2387. }
  2388. return Option.none();
  2389. };
  2390. var closest$1 = function (scope, predicate, isRoot) {
  2391. var is = function (s, test) {
  2392. return test(s);
  2393. };
  2394. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  2395. };
  2396. var descendant = function (scope, predicate) {
  2397. var descend = function (node) {
  2398. for (var i = 0; i < node.childNodes.length; i++) {
  2399. var child_1 = Element.fromDom(node.childNodes[i]);
  2400. if (predicate(child_1)) {
  2401. return Option.some(child_1);
  2402. }
  2403. var res = descend(node.childNodes[i]);
  2404. if (res.isSome()) {
  2405. return res;
  2406. }
  2407. }
  2408. return Option.none();
  2409. };
  2410. return descend(scope.dom());
  2411. };
  2412. var focus$1 = function (element) {
  2413. return element.dom().focus();
  2414. };
  2415. var blur = function (element) {
  2416. return element.dom().blur();
  2417. };
  2418. var hasFocus = function (element) {
  2419. var doc = owner(element).dom();
  2420. return element.dom() === doc.activeElement;
  2421. };
  2422. var active = function (_doc) {
  2423. var doc = _doc !== undefined ? _doc.dom() : domGlobals.document;
  2424. return Option.from(doc.activeElement).map(Element.fromDom);
  2425. };
  2426. var search = function (element) {
  2427. return active(owner(element)).filter(function (e) {
  2428. return element.dom().contains(e.dom());
  2429. });
  2430. };
  2431. var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2432. var global$2 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2433. var openLink = function (target) {
  2434. var link = domGlobals.document.createElement('a');
  2435. link.target = '_blank';
  2436. link.href = target.href;
  2437. link.rel = 'noreferrer noopener';
  2438. var nuEvt = domGlobals.document.createEvent('MouseEvents');
  2439. nuEvt.initMouseEvent('click', true, true, domGlobals.window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2440. domGlobals.document.body.appendChild(link);
  2441. link.dispatchEvent(nuEvt);
  2442. domGlobals.document.body.removeChild(link);
  2443. };
  2444. var isSkinDisabled = function (editor) {
  2445. return editor.settings.skin === false;
  2446. };
  2447. var readOnlyOnInit = function (_editor) {
  2448. return false;
  2449. };
  2450. var formatChanged = 'formatChanged';
  2451. var orientationChanged = 'orientationChanged';
  2452. var dropupDismissed = 'dropupDismissed';
  2453. var fromHtml$1 = function (html, scope) {
  2454. var doc = scope || domGlobals.document;
  2455. var div = doc.createElement('div');
  2456. div.innerHTML = html;
  2457. return children(Element.fromDom(div));
  2458. };
  2459. var get$3 = function (element) {
  2460. return element.dom().innerHTML;
  2461. };
  2462. var set$1 = function (element, content) {
  2463. var owner$1 = owner(element);
  2464. var docDom = owner$1.dom();
  2465. var fragment = Element.fromDom(docDom.createDocumentFragment());
  2466. var contentElements = fromHtml$1(content, docDom);
  2467. append$1(fragment, contentElements);
  2468. empty(element);
  2469. append(element, fragment);
  2470. };
  2471. var getOuter = function (element) {
  2472. var container = Element.fromTag('div');
  2473. var clone = Element.fromDom(element.dom().cloneNode(true));
  2474. append(container, clone);
  2475. return get$3(container);
  2476. };
  2477. var clone = function (original, isDeep) {
  2478. return Element.fromDom(original.dom().cloneNode(isDeep));
  2479. };
  2480. var shallow$1 = function (original) {
  2481. return clone(original, false);
  2482. };
  2483. var getHtml = function (element) {
  2484. var clone = shallow$1(element);
  2485. return getOuter(clone);
  2486. };
  2487. var element = function (elem) {
  2488. return getHtml(elem);
  2489. };
  2490. var chooseChannels = function (channels, message) {
  2491. return message.universal() ? channels : filter$1(channels, function (ch) {
  2492. return contains(message.channels(), ch);
  2493. });
  2494. };
  2495. var events = function (receiveConfig) {
  2496. return derive([run(receive(), function (component, message) {
  2497. var channelMap = receiveConfig.channels;
  2498. var channels = keys(channelMap);
  2499. var receivingData = message;
  2500. var targetChannels = chooseChannels(channels, receivingData);
  2501. each$1(targetChannels, function (ch) {
  2502. var channelInfo = channelMap[ch];
  2503. var channelSchema = channelInfo.schema;
  2504. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, receivingData.data());
  2505. channelInfo.onReceive(component, data);
  2506. });
  2507. })]);
  2508. };
  2509. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2510. __proto__: null,
  2511. events: events
  2512. });
  2513. var unknown$3 = 'unknown';
  2514. var EventConfiguration;
  2515. (function (EventConfiguration) {
  2516. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2517. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2518. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2519. }(EventConfiguration || (EventConfiguration = {})));
  2520. var eventConfig = Cell({});
  2521. var makeEventLogger = function (eventName, initialTarget) {
  2522. var sequence = [];
  2523. var startTime = new Date().getTime();
  2524. return {
  2525. logEventCut: function (_name, target, purpose) {
  2526. sequence.push({
  2527. outcome: 'cut',
  2528. target: target,
  2529. purpose: purpose
  2530. });
  2531. },
  2532. logEventStopped: function (_name, target, purpose) {
  2533. sequence.push({
  2534. outcome: 'stopped',
  2535. target: target,
  2536. purpose: purpose
  2537. });
  2538. },
  2539. logNoParent: function (_name, target, purpose) {
  2540. sequence.push({
  2541. outcome: 'no-parent',
  2542. target: target,
  2543. purpose: purpose
  2544. });
  2545. },
  2546. logEventNoHandlers: function (_name, target) {
  2547. sequence.push({
  2548. outcome: 'no-handlers-left',
  2549. target: target
  2550. });
  2551. },
  2552. logEventResponse: function (_name, target, purpose) {
  2553. sequence.push({
  2554. outcome: 'response',
  2555. purpose: purpose,
  2556. target: target
  2557. });
  2558. },
  2559. write: function () {
  2560. var finishTime = new Date().getTime();
  2561. if (contains([
  2562. 'mousemove',
  2563. 'mouseover',
  2564. 'mouseout',
  2565. systemInit()
  2566. ], eventName)) {
  2567. return;
  2568. }
  2569. domGlobals.console.log(eventName, {
  2570. event: eventName,
  2571. time: finishTime - startTime,
  2572. target: initialTarget.dom(),
  2573. sequence: map$1(sequence, function (s) {
  2574. if (!contains([
  2575. 'cut',
  2576. 'stopped',
  2577. 'response'
  2578. ], s.outcome)) {
  2579. return s.outcome;
  2580. } else {
  2581. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2582. }
  2583. })
  2584. });
  2585. }
  2586. };
  2587. };
  2588. var processEvent = function (eventName, initialTarget, f) {
  2589. var status = get(eventConfig.get(), eventName).orThunk(function () {
  2590. var patterns = keys(eventConfig.get());
  2591. return findMap(patterns, function (p) {
  2592. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  2593. });
  2594. }).getOr(EventConfiguration.NORMAL);
  2595. switch (status) {
  2596. case EventConfiguration.NORMAL:
  2597. return f(noLogger());
  2598. case EventConfiguration.LOGGING: {
  2599. var logger = makeEventLogger(eventName, initialTarget);
  2600. var output = f(logger);
  2601. logger.write();
  2602. return output;
  2603. }
  2604. case EventConfiguration.STOP:
  2605. return true;
  2606. }
  2607. };
  2608. var path = [
  2609. 'alloy/data/Fields',
  2610. 'alloy/debugging/Debugging'
  2611. ];
  2612. var getTrace = function () {
  2613. var err = new Error();
  2614. if (err.stack !== undefined) {
  2615. var lines = err.stack.split('\n');
  2616. return find$2(lines, function (line) {
  2617. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2618. return line.indexOf(p) > -1;
  2619. });
  2620. }).getOr(unknown$3);
  2621. } else {
  2622. return unknown$3;
  2623. }
  2624. };
  2625. var ignoreEvent = {
  2626. logEventCut: noop,
  2627. logEventStopped: noop,
  2628. logNoParent: noop,
  2629. logEventNoHandlers: noop,
  2630. logEventResponse: noop,
  2631. write: noop
  2632. };
  2633. var monitorEvent = function (eventName, initialTarget, f) {
  2634. return processEvent(eventName, initialTarget, f);
  2635. };
  2636. var noLogger = constant(ignoreEvent);
  2637. var menuFields = constant([
  2638. strict$1('menu'),
  2639. strict$1('selectedMenu')
  2640. ]);
  2641. var itemFields = constant([
  2642. strict$1('item'),
  2643. strict$1('selectedItem')
  2644. ]);
  2645. var schema = constant(objOf(itemFields().concat(menuFields())));
  2646. var itemSchema = constant(objOf(itemFields()));
  2647. var _initSize = strictObjOf('initSize', [
  2648. strict$1('numColumns'),
  2649. strict$1('numRows')
  2650. ]);
  2651. var itemMarkers = function () {
  2652. return strictOf('markers', itemSchema());
  2653. };
  2654. var tieredMenuMarkers = function () {
  2655. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2656. };
  2657. var markers = function (required) {
  2658. return strictObjOf('markers', map$1(required, strict$1));
  2659. };
  2660. var onPresenceHandler = function (label, fieldName, presence) {
  2661. var trace = getTrace();
  2662. return field(fieldName, fieldName, presence, valueOf(function (f) {
  2663. return Result.value(function () {
  2664. var args = [];
  2665. for (var _i = 0; _i < arguments.length; _i++) {
  2666. args[_i] = arguments[_i];
  2667. }
  2668. return f.apply(undefined, args);
  2669. });
  2670. }));
  2671. };
  2672. var onHandler = function (fieldName) {
  2673. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  2674. };
  2675. var onKeyboardHandler = function (fieldName) {
  2676. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  2677. };
  2678. var onStrictHandler = function (fieldName) {
  2679. return onPresenceHandler('onHandler', fieldName, strict());
  2680. };
  2681. var onStrictKeyboardHandler = function (fieldName) {
  2682. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  2683. };
  2684. var output = function (name, value) {
  2685. return state$1(name, constant(value));
  2686. };
  2687. var snapshot = function (name) {
  2688. return state$1(name, identity);
  2689. };
  2690. var initSize = constant(_initSize);
  2691. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  2692. onStrictHandler('onReceive'),
  2693. defaulted$1('schema', anyValue$1())
  2694. ])))];
  2695. var Receiving = create$1({
  2696. fields: ReceivingSchema,
  2697. name: 'receiving',
  2698. active: ActiveReceiving
  2699. });
  2700. var updateAriaState = function (component, toggleConfig, toggleState) {
  2701. var ariaInfo = toggleConfig.aria;
  2702. ariaInfo.update(component, ariaInfo, toggleState.get());
  2703. };
  2704. var updateClass = function (component, toggleConfig, toggleState) {
  2705. toggleConfig.toggleClass.each(function (toggleClass) {
  2706. if (toggleState.get()) {
  2707. add$2(component.element(), toggleClass);
  2708. } else {
  2709. remove$4(component.element(), toggleClass);
  2710. }
  2711. });
  2712. };
  2713. var toggle = function (component, toggleConfig, toggleState) {
  2714. set$2(component, toggleConfig, toggleState, !toggleState.get());
  2715. };
  2716. var on = function (component, toggleConfig, toggleState) {
  2717. toggleState.set(true);
  2718. updateClass(component, toggleConfig, toggleState);
  2719. updateAriaState(component, toggleConfig, toggleState);
  2720. };
  2721. var off = function (component, toggleConfig, toggleState) {
  2722. toggleState.set(false);
  2723. updateClass(component, toggleConfig, toggleState);
  2724. updateAriaState(component, toggleConfig, toggleState);
  2725. };
  2726. var set$2 = function (component, toggleConfig, toggleState, state) {
  2727. var action = state ? on : off;
  2728. action(component, toggleConfig, toggleState);
  2729. };
  2730. var isOn = function (component, toggleConfig, toggleState) {
  2731. return toggleState.get();
  2732. };
  2733. var onLoad = function (component, toggleConfig, toggleState) {
  2734. set$2(component, toggleConfig, toggleState, toggleConfig.selected);
  2735. };
  2736. var ToggleApis = /*#__PURE__*/Object.freeze({
  2737. __proto__: null,
  2738. onLoad: onLoad,
  2739. toggle: toggle,
  2740. isOn: isOn,
  2741. on: on,
  2742. off: off,
  2743. set: set$2
  2744. });
  2745. var exhibit = function () {
  2746. return nu$5({});
  2747. };
  2748. var events$1 = function (toggleConfig, toggleState) {
  2749. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2750. var load = loadEvent(toggleConfig, toggleState, onLoad);
  2751. return derive(flatten([
  2752. toggleConfig.toggleOnExecute ? [execute] : [],
  2753. [load]
  2754. ]));
  2755. };
  2756. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2757. __proto__: null,
  2758. exhibit: exhibit,
  2759. events: events$1
  2760. });
  2761. var SetupBehaviourCellState = function (initialState) {
  2762. var init = function () {
  2763. var cell = Cell(initialState);
  2764. var get = function () {
  2765. return cell.get();
  2766. };
  2767. var set = function (newState) {
  2768. return cell.set(newState);
  2769. };
  2770. var clear = function () {
  2771. return cell.set(initialState);
  2772. };
  2773. var readState = function () {
  2774. return cell.get();
  2775. };
  2776. return {
  2777. get: get,
  2778. set: set,
  2779. clear: clear,
  2780. readState: readState
  2781. };
  2782. };
  2783. return { init: init };
  2784. };
  2785. var updatePressed = function (component, ariaInfo, status) {
  2786. set(component.element(), 'aria-pressed', status);
  2787. if (ariaInfo.syncWithExpanded) {
  2788. updateExpanded(component, ariaInfo, status);
  2789. }
  2790. };
  2791. var updateSelected = function (component, ariaInfo, status) {
  2792. set(component.element(), 'aria-selected', status);
  2793. };
  2794. var updateChecked = function (component, ariaInfo, status) {
  2795. set(component.element(), 'aria-checked', status);
  2796. };
  2797. var updateExpanded = function (component, ariaInfo, status) {
  2798. set(component.element(), 'aria-expanded', status);
  2799. };
  2800. var ToggleSchema = [
  2801. defaulted$1('selected', false),
  2802. option('toggleClass'),
  2803. defaulted$1('toggleOnExecute', true),
  2804. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  2805. pressed: [
  2806. defaulted$1('syncWithExpanded', false),
  2807. output('update', updatePressed)
  2808. ],
  2809. checked: [output('update', updateChecked)],
  2810. expanded: [output('update', updateExpanded)],
  2811. selected: [output('update', updateSelected)],
  2812. none: [output('update', noop)]
  2813. }))
  2814. ];
  2815. var Toggling = create$1({
  2816. fields: ToggleSchema,
  2817. name: 'toggling',
  2818. active: ActiveToggle,
  2819. apis: ToggleApis,
  2820. state: SetupBehaviourCellState(false)
  2821. });
  2822. var format = function (command, update) {
  2823. return Receiving.config({
  2824. channels: wrap$1(formatChanged, {
  2825. onReceive: function (button, data) {
  2826. if (data.command === command) {
  2827. update(button, data.state);
  2828. }
  2829. }
  2830. })
  2831. });
  2832. };
  2833. var orientation = function (onReceive) {
  2834. return Receiving.config({ channels: wrap$1(orientationChanged, { onReceive: onReceive }) });
  2835. };
  2836. var receive$1 = function (channel, onReceive) {
  2837. return {
  2838. key: channel,
  2839. value: { onReceive: onReceive }
  2840. };
  2841. };
  2842. var prefix = 'tinymce-mobile';
  2843. var resolve = function (p) {
  2844. return prefix + '-' + p;
  2845. };
  2846. var pointerEvents = function () {
  2847. var onClick = function (component, simulatedEvent) {
  2848. simulatedEvent.stop();
  2849. emitExecute(component);
  2850. };
  2851. return [
  2852. run(click(), onClick),
  2853. run(tap(), onClick),
  2854. cutter(touchstart()),
  2855. cutter(mousedown())
  2856. ];
  2857. };
  2858. var events$2 = function (optAction) {
  2859. var executeHandler = function (action) {
  2860. return runOnExecute(function (component, simulatedEvent) {
  2861. action(component);
  2862. simulatedEvent.stop();
  2863. });
  2864. };
  2865. return derive(flatten([
  2866. optAction.map(executeHandler).toArray(),
  2867. pointerEvents()
  2868. ]));
  2869. };
  2870. var focus$2 = function (component, focusConfig) {
  2871. if (!focusConfig.ignore) {
  2872. focus$1(component.element());
  2873. focusConfig.onFocus(component);
  2874. }
  2875. };
  2876. var blur$1 = function (component, focusConfig) {
  2877. if (!focusConfig.ignore) {
  2878. blur(component.element());
  2879. }
  2880. };
  2881. var isFocused = function (component) {
  2882. return hasFocus(component.element());
  2883. };
  2884. var FocusApis = /*#__PURE__*/Object.freeze({
  2885. __proto__: null,
  2886. focus: focus$2,
  2887. blur: blur$1,
  2888. isFocused: isFocused
  2889. });
  2890. var exhibit$1 = function (base, focusConfig) {
  2891. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  2892. return nu$5(mod);
  2893. };
  2894. var events$3 = function (focusConfig) {
  2895. return derive([run(focus(), function (component, simulatedEvent) {
  2896. focus$2(component, focusConfig);
  2897. simulatedEvent.stop();
  2898. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  2899. simulatedEvent.event().prevent();
  2900. })] : []));
  2901. };
  2902. var ActiveFocus = /*#__PURE__*/Object.freeze({
  2903. __proto__: null,
  2904. exhibit: exhibit$1,
  2905. events: events$3
  2906. });
  2907. var FocusSchema = [
  2908. onHandler('onFocus'),
  2909. defaulted$1('stopMousedown', false),
  2910. defaulted$1('ignore', false)
  2911. ];
  2912. var Focusing = create$1({
  2913. fields: FocusSchema,
  2914. name: 'focusing',
  2915. active: ActiveFocus,
  2916. apis: FocusApis
  2917. });
  2918. var isSupported = function (dom) {
  2919. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  2920. };
  2921. var internalSet = function (dom, property, value) {
  2922. if (!isString(value)) {
  2923. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  2924. throw new Error('CSS value must be a string: ' + value);
  2925. }
  2926. if (isSupported(dom)) {
  2927. dom.style.setProperty(property, value);
  2928. }
  2929. };
  2930. var internalRemove = function (dom, property) {
  2931. if (isSupported(dom)) {
  2932. dom.style.removeProperty(property);
  2933. }
  2934. };
  2935. var set$3 = function (element, property, value) {
  2936. var dom = element.dom();
  2937. internalSet(dom, property, value);
  2938. };
  2939. var setAll$1 = function (element, css) {
  2940. var dom = element.dom();
  2941. each(css, function (v, k) {
  2942. internalSet(dom, k, v);
  2943. });
  2944. };
  2945. var get$4 = function (element, property) {
  2946. var dom = element.dom();
  2947. var styles = domGlobals.window.getComputedStyle(dom);
  2948. var r = styles.getPropertyValue(property);
  2949. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  2950. };
  2951. var getUnsafeProperty = function (dom, property) {
  2952. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  2953. };
  2954. var getRaw = function (element, property) {
  2955. var dom = element.dom();
  2956. var raw = getUnsafeProperty(dom, property);
  2957. return Option.from(raw).filter(function (r) {
  2958. return r.length > 0;
  2959. });
  2960. };
  2961. var remove$5 = function (element, property) {
  2962. var dom = element.dom();
  2963. internalRemove(dom, property);
  2964. if (getOpt(element, 'style').map(trim).is('')) {
  2965. remove$1(element, 'style');
  2966. }
  2967. };
  2968. var reflow = function (e) {
  2969. return e.dom().offsetWidth;
  2970. };
  2971. function Dimension (name, getOffset) {
  2972. var set = function (element, h) {
  2973. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  2974. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  2975. }
  2976. var dom = element.dom();
  2977. if (isSupported(dom)) {
  2978. dom.style[name] = h + 'px';
  2979. }
  2980. };
  2981. var get = function (element) {
  2982. var r = getOffset(element);
  2983. if (r <= 0 || r === null) {
  2984. var css = get$4(element, name);
  2985. return parseFloat(css) || 0;
  2986. }
  2987. return r;
  2988. };
  2989. var getOuter = get;
  2990. var aggregate = function (element, properties) {
  2991. return foldl(properties, function (acc, property) {
  2992. var val = get$4(element, property);
  2993. var value = val === undefined ? 0 : parseInt(val, 10);
  2994. return isNaN(value) ? acc : acc + value;
  2995. }, 0);
  2996. };
  2997. var max = function (element, value, properties) {
  2998. var cumulativeInclusions = aggregate(element, properties);
  2999. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3000. return absoluteMax;
  3001. };
  3002. return {
  3003. set: set,
  3004. get: get,
  3005. getOuter: getOuter,
  3006. aggregate: aggregate,
  3007. max: max
  3008. };
  3009. }
  3010. var api = Dimension('height', function (element) {
  3011. var dom = element.dom();
  3012. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3013. });
  3014. var get$5 = function (element) {
  3015. return api.get(element);
  3016. };
  3017. var ancestors = function (scope, predicate, isRoot) {
  3018. return filter$1(parents(scope, isRoot), predicate);
  3019. };
  3020. var siblings$1 = function (scope, predicate) {
  3021. return filter$1(siblings(scope), predicate);
  3022. };
  3023. var all$2 = function (selector) {
  3024. return all(selector);
  3025. };
  3026. var ancestors$1 = function (scope, selector, isRoot) {
  3027. return ancestors(scope, function (e) {
  3028. return is(e, selector);
  3029. }, isRoot);
  3030. };
  3031. var siblings$2 = function (scope, selector) {
  3032. return siblings$1(scope, function (e) {
  3033. return is(e, selector);
  3034. });
  3035. };
  3036. var descendants = function (scope, selector) {
  3037. return all(selector, scope);
  3038. };
  3039. var first = function (selector) {
  3040. return one(selector);
  3041. };
  3042. var ancestor$2 = function (scope, selector, isRoot) {
  3043. return ancestor$1(scope, function (e) {
  3044. return is(e, selector);
  3045. }, isRoot);
  3046. };
  3047. var descendant$1 = function (scope, selector) {
  3048. return one(selector, scope);
  3049. };
  3050. var closest$2 = function (scope, selector, isRoot) {
  3051. var is$1 = function (element, selector) {
  3052. return is(element, selector);
  3053. };
  3054. return ClosestOrAncestor(is$1, ancestor$2, scope, selector, isRoot);
  3055. };
  3056. var BACKSPACE = function () {
  3057. return [8];
  3058. };
  3059. var TAB = function () {
  3060. return [9];
  3061. };
  3062. var ENTER = function () {
  3063. return [13];
  3064. };
  3065. var ESCAPE = function () {
  3066. return [27];
  3067. };
  3068. var SPACE = function () {
  3069. return [32];
  3070. };
  3071. var LEFT = function () {
  3072. return [37];
  3073. };
  3074. var UP = function () {
  3075. return [38];
  3076. };
  3077. var RIGHT = function () {
  3078. return [39];
  3079. };
  3080. var DOWN = function () {
  3081. return [40];
  3082. };
  3083. var cyclePrev = function (values, index, predicate) {
  3084. var before = reverse(values.slice(0, index));
  3085. var after = reverse(values.slice(index + 1));
  3086. return find$2(before.concat(after), predicate);
  3087. };
  3088. var tryPrev = function (values, index, predicate) {
  3089. var before = reverse(values.slice(0, index));
  3090. return find$2(before, predicate);
  3091. };
  3092. var cycleNext = function (values, index, predicate) {
  3093. var before = values.slice(0, index);
  3094. var after = values.slice(index + 1);
  3095. return find$2(after.concat(before), predicate);
  3096. };
  3097. var tryNext = function (values, index, predicate) {
  3098. var after = values.slice(index + 1);
  3099. return find$2(after, predicate);
  3100. };
  3101. var inSet = function (keys) {
  3102. return function (event) {
  3103. var raw = event.raw();
  3104. return contains(keys, raw.which);
  3105. };
  3106. };
  3107. var and = function (preds) {
  3108. return function (event) {
  3109. return forall(preds, function (pred) {
  3110. return pred(event);
  3111. });
  3112. };
  3113. };
  3114. var isShift = function (event) {
  3115. var raw = event.raw();
  3116. return raw.shiftKey === true;
  3117. };
  3118. var isControl = function (event) {
  3119. var raw = event.raw();
  3120. return raw.ctrlKey === true;
  3121. };
  3122. var isNotShift = not(isShift);
  3123. var rule = function (matches, action) {
  3124. return {
  3125. matches: matches,
  3126. classification: action
  3127. };
  3128. };
  3129. var choose$2 = function (transitions, event) {
  3130. var transition = find$2(transitions, function (t) {
  3131. return t.matches(event);
  3132. });
  3133. return transition.map(function (t) {
  3134. return t.classification;
  3135. });
  3136. };
  3137. var cat = function (arr) {
  3138. var r = [];
  3139. var push = function (x) {
  3140. r.push(x);
  3141. };
  3142. for (var i = 0; i < arr.length; i++) {
  3143. arr[i].each(push);
  3144. }
  3145. return r;
  3146. };
  3147. var sequence = function (arr) {
  3148. var r = [];
  3149. for (var i = 0; i < arr.length; i++) {
  3150. var x = arr[i];
  3151. if (x.isSome()) {
  3152. r.push(x.getOrDie());
  3153. } else {
  3154. return Option.none();
  3155. }
  3156. }
  3157. return Option.some(r);
  3158. };
  3159. var someIf = function (b, a) {
  3160. return b ? Option.some(a) : Option.none();
  3161. };
  3162. var cycleBy = function (value, delta, min, max) {
  3163. var r = value + delta;
  3164. return r > max ? min : r < min ? max : r;
  3165. };
  3166. var clamp = function (value, min, max) {
  3167. return Math.min(Math.max(value, min), max);
  3168. };
  3169. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3170. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  3171. each$1(highlighted, function (h) {
  3172. if (!exists(skip, function (skipComp) {
  3173. return skipComp.element() === h;
  3174. })) {
  3175. remove$4(h, hConfig.highlightClass);
  3176. component.getSystem().getByDom(h).each(function (target) {
  3177. hConfig.onDehighlight(component, target);
  3178. emit(target, dehighlight());
  3179. });
  3180. }
  3181. });
  3182. };
  3183. var dehighlightAll = function (component, hConfig, hState) {
  3184. return dehighlightAllExcept(component, hConfig, hState, []);
  3185. };
  3186. var dehighlight$1 = function (component, hConfig, hState, target) {
  3187. if (isHighlighted(component, hConfig, hState, target)) {
  3188. remove$4(target.element(), hConfig.highlightClass);
  3189. hConfig.onDehighlight(component, target);
  3190. emit(target, dehighlight());
  3191. }
  3192. };
  3193. var highlight$1 = function (component, hConfig, hState, target) {
  3194. dehighlightAllExcept(component, hConfig, hState, [target]);
  3195. if (!isHighlighted(component, hConfig, hState, target)) {
  3196. add$2(target.element(), hConfig.highlightClass);
  3197. hConfig.onHighlight(component, target);
  3198. emit(target, highlight());
  3199. }
  3200. };
  3201. var highlightFirst = function (component, hConfig, hState) {
  3202. getFirst(component, hConfig).each(function (firstComp) {
  3203. highlight$1(component, hConfig, hState, firstComp);
  3204. });
  3205. };
  3206. var highlightLast = function (component, hConfig, hState) {
  3207. getLast(component, hConfig).each(function (lastComp) {
  3208. highlight$1(component, hConfig, hState, lastComp);
  3209. });
  3210. };
  3211. var highlightAt = function (component, hConfig, hState, index) {
  3212. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3213. throw new Error(err);
  3214. }, function (firstComp) {
  3215. highlight$1(component, hConfig, hState, firstComp);
  3216. });
  3217. };
  3218. var highlightBy = function (component, hConfig, hState, predicate) {
  3219. var candidates = getCandidates(component, hConfig);
  3220. var targetComp = find$2(candidates, predicate);
  3221. targetComp.each(function (c) {
  3222. highlight$1(component, hConfig, hState, c);
  3223. });
  3224. };
  3225. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3226. return has$2(queryTarget.element(), hConfig.highlightClass);
  3227. };
  3228. var getHighlighted = function (component, hConfig, _hState) {
  3229. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  3230. return component.getSystem().getByDom(e).toOption();
  3231. });
  3232. };
  3233. var getByIndex = function (component, hConfig, hState, index) {
  3234. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3235. return Option.from(items[index]).fold(function () {
  3236. return Result.error('No element found with index ' + index);
  3237. }, component.getSystem().getByDom);
  3238. };
  3239. var getFirst = function (component, hConfig, _hState) {
  3240. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  3241. return component.getSystem().getByDom(e).toOption();
  3242. });
  3243. };
  3244. var getLast = function (component, hConfig, _hState) {
  3245. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3246. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  3247. return last.bind(function (c) {
  3248. return component.getSystem().getByDom(c).toOption();
  3249. });
  3250. };
  3251. var getDelta = function (component, hConfig, hState, delta) {
  3252. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3253. var current = findIndex(items, function (item) {
  3254. return has$2(item, hConfig.highlightClass);
  3255. });
  3256. return current.bind(function (selected) {
  3257. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3258. return component.getSystem().getByDom(items[dest]).toOption();
  3259. });
  3260. };
  3261. var getPrevious = function (component, hConfig, hState) {
  3262. return getDelta(component, hConfig, hState, -1);
  3263. };
  3264. var getNext = function (component, hConfig, hState) {
  3265. return getDelta(component, hConfig, hState, +1);
  3266. };
  3267. var getCandidates = function (component, hConfig, _hState) {
  3268. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3269. return cat(map$1(items, function (i) {
  3270. return component.getSystem().getByDom(i).toOption();
  3271. }));
  3272. };
  3273. var HighlightApis = /*#__PURE__*/Object.freeze({
  3274. __proto__: null,
  3275. dehighlightAll: dehighlightAll,
  3276. dehighlight: dehighlight$1,
  3277. highlight: highlight$1,
  3278. highlightFirst: highlightFirst,
  3279. highlightLast: highlightLast,
  3280. highlightAt: highlightAt,
  3281. highlightBy: highlightBy,
  3282. isHighlighted: isHighlighted,
  3283. getHighlighted: getHighlighted,
  3284. getFirst: getFirst,
  3285. getLast: getLast,
  3286. getPrevious: getPrevious,
  3287. getNext: getNext,
  3288. getCandidates: getCandidates
  3289. });
  3290. var HighlightSchema = [
  3291. strict$1('highlightClass'),
  3292. strict$1('itemClass'),
  3293. onHandler('onHighlight'),
  3294. onHandler('onDehighlight')
  3295. ];
  3296. var Highlighting = create$1({
  3297. fields: HighlightSchema,
  3298. name: 'highlighting',
  3299. apis: HighlightApis
  3300. });
  3301. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3302. var noChange = prevFocus.exists(function (p) {
  3303. return newFocus.exists(function (n) {
  3304. return eq(n, p);
  3305. });
  3306. });
  3307. if (!noChange) {
  3308. emitWith(component, focusShifted(), {
  3309. prevFocus: prevFocus,
  3310. newFocus: newFocus
  3311. });
  3312. }
  3313. };
  3314. var dom = function () {
  3315. var get = function (component) {
  3316. return search(component.element());
  3317. };
  3318. var set = function (component, focusee) {
  3319. var prevFocus = get(component);
  3320. component.getSystem().triggerFocus(focusee, component.element());
  3321. var newFocus = get(component);
  3322. reportFocusShifting(component, prevFocus, newFocus);
  3323. };
  3324. return {
  3325. get: get,
  3326. set: set
  3327. };
  3328. };
  3329. var highlights = function () {
  3330. var get = function (component) {
  3331. return Highlighting.getHighlighted(component).map(function (item) {
  3332. return item.element();
  3333. });
  3334. };
  3335. var set = function (component, element) {
  3336. var prevFocus = get(component);
  3337. component.getSystem().getByDom(element).fold(noop, function (item) {
  3338. Highlighting.highlight(component, item);
  3339. });
  3340. var newFocus = get(component);
  3341. reportFocusShifting(component, prevFocus, newFocus);
  3342. };
  3343. return {
  3344. get: get,
  3345. set: set
  3346. };
  3347. };
  3348. var FocusInsideModes;
  3349. (function (FocusInsideModes) {
  3350. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3351. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3352. FocusInsideModes['OnApiMode'] = 'onApi';
  3353. }(FocusInsideModes || (FocusInsideModes = {})));
  3354. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3355. var schema = function () {
  3356. return infoSchema.concat([
  3357. defaulted$1('focusManager', dom()),
  3358. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3359. return contains([
  3360. 'onFocus',
  3361. 'onEnterOrSpace',
  3362. 'onApi'
  3363. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3364. })),
  3365. output('handler', me),
  3366. output('state', stateInit),
  3367. output('sendFocusIn', optFocusIn)
  3368. ]);
  3369. };
  3370. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3371. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3372. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  3373. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3374. });
  3375. };
  3376. var toEvents = function (keyingConfig, keyingState) {
  3377. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3378. return run(focus(), function (component, simulatedEvent) {
  3379. focusIn(component, keyingConfig, keyingState);
  3380. simulatedEvent.stop();
  3381. });
  3382. });
  3383. var tryGoInsideComponent = function (component, simulatedEvent) {
  3384. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  3385. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3386. optFocusIn(keyingConfig).each(function (focusIn) {
  3387. focusIn(component, keyingConfig, keyingState);
  3388. simulatedEvent.stop();
  3389. });
  3390. }
  3391. };
  3392. var keyboardEvents = [
  3393. run(keydown(), function (component, simulatedEvent) {
  3394. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3395. tryGoInsideComponent(component, simulatedEvent);
  3396. }, function (_) {
  3397. simulatedEvent.stop();
  3398. });
  3399. }),
  3400. run(keyup(), function (component, simulatedEvent) {
  3401. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3402. simulatedEvent.stop();
  3403. });
  3404. })
  3405. ];
  3406. return derive(onFocusHandler.toArray().concat(keyboardEvents));
  3407. };
  3408. var me = {
  3409. schema: schema,
  3410. processKey: processKey,
  3411. toEvents: toEvents
  3412. };
  3413. return me;
  3414. };
  3415. var create$2 = function (cyclicField) {
  3416. var schema = [
  3417. option('onEscape'),
  3418. option('onEnter'),
  3419. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3420. defaulted$1('firstTabstop', 0),
  3421. defaulted$1('useTabstopAt', constant(true)),
  3422. option('visibilitySelector')
  3423. ].concat([cyclicField]);
  3424. var isVisible = function (tabbingConfig, element) {
  3425. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3426. return closest$2(element, sel);
  3427. }).getOr(element);
  3428. return get$5(target) > 0;
  3429. };
  3430. var findInitial = function (component, tabbingConfig) {
  3431. var tabstops = descendants(component.element(), tabbingConfig.selector);
  3432. var visibles = filter$1(tabstops, function (elem) {
  3433. return isVisible(tabbingConfig, elem);
  3434. });
  3435. return Option.from(visibles[tabbingConfig.firstTabstop]);
  3436. };
  3437. var findCurrent = function (component, tabbingConfig) {
  3438. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3439. return closest$2(elem, tabbingConfig.selector);
  3440. });
  3441. };
  3442. var isTabstop = function (tabbingConfig, element) {
  3443. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3444. };
  3445. var focusIn = function (component, tabbingConfig, _tabbingState) {
  3446. findInitial(component, tabbingConfig).each(function (target) {
  3447. tabbingConfig.focusManager.set(component, target);
  3448. });
  3449. };
  3450. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3451. return cycle(tabstops, stopIndex, function (elem) {
  3452. return isTabstop(tabbingConfig, elem);
  3453. }).fold(function () {
  3454. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  3455. }, function (target) {
  3456. tabbingConfig.focusManager.set(component, target);
  3457. return Option.some(true);
  3458. });
  3459. };
  3460. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  3461. var tabstops = descendants(component.element(), tabbingConfig.selector);
  3462. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3463. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  3464. return optStopIndex.bind(function (stopIndex) {
  3465. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3466. });
  3467. });
  3468. };
  3469. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  3470. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3471. return go(component, simulatedEvent, tabbingConfig, navigate);
  3472. };
  3473. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  3474. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3475. return go(component, simulatedEvent, tabbingConfig, navigate);
  3476. };
  3477. var execute = function (component, simulatedEvent, tabbingConfig) {
  3478. return tabbingConfig.onEnter.bind(function (f) {
  3479. return f(component, simulatedEvent);
  3480. });
  3481. };
  3482. var exit = function (component, simulatedEvent, tabbingConfig) {
  3483. return tabbingConfig.onEscape.bind(function (f) {
  3484. return f(component, simulatedEvent);
  3485. });
  3486. };
  3487. var getKeydownRules = constant([
  3488. rule(and([
  3489. isShift,
  3490. inSet(TAB())
  3491. ]), goBackwards),
  3492. rule(inSet(TAB()), goForwards),
  3493. rule(inSet(ESCAPE()), exit),
  3494. rule(and([
  3495. isNotShift,
  3496. inSet(ENTER())
  3497. ]), execute)
  3498. ]);
  3499. var getKeyupRules = constant([]);
  3500. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3501. return Option.some(focusIn);
  3502. });
  3503. };
  3504. var AcyclicType = create$2(state$1('cyclic', constant(false)));
  3505. var CyclicType = create$2(state$1('cyclic', constant(true)));
  3506. var inside = function (target) {
  3507. return name(target) === 'input' && get$1(target, 'type') !== 'radio' || name(target) === 'textarea';
  3508. };
  3509. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  3510. dispatch(component, focused, execute());
  3511. return Option.some(true);
  3512. };
  3513. var defaultExecute = function (component, simulatedEvent, focused) {
  3514. var isComplex = inside(focused) && inSet(SPACE())(simulatedEvent.event());
  3515. return isComplex ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  3516. };
  3517. var stopEventForFirefox = function (_component, _simulatedEvent) {
  3518. return Option.some(true);
  3519. };
  3520. var schema$1 = [
  3521. defaulted$1('execute', defaultExecute),
  3522. defaulted$1('useSpace', false),
  3523. defaulted$1('useEnter', true),
  3524. defaulted$1('useControlEnter', false),
  3525. defaulted$1('useDown', false)
  3526. ];
  3527. var execute$1 = function (component, simulatedEvent, executeConfig) {
  3528. return executeConfig.execute(component, simulatedEvent, component.element());
  3529. };
  3530. var getKeydownRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  3531. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  3532. var enterExec = executeConfig.useEnter ? ENTER() : [];
  3533. var downExec = executeConfig.useDown ? DOWN() : [];
  3534. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3535. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  3536. isControl,
  3537. inSet(ENTER())
  3538. ]), execute$1)] : []);
  3539. };
  3540. var getKeyupRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  3541. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  3542. };
  3543. var ExecutionType = typical(schema$1, NoState.init, getKeydownRules, getKeyupRules, function () {
  3544. return Option.none();
  3545. });
  3546. var flatgrid = function () {
  3547. var dimensions = Cell(Option.none());
  3548. var setGridSize = function (numRows, numColumns) {
  3549. dimensions.set(Option.some({
  3550. numRows: numRows,
  3551. numColumns: numColumns
  3552. }));
  3553. };
  3554. var getNumRows = function () {
  3555. return dimensions.get().map(function (d) {
  3556. return d.numRows;
  3557. });
  3558. };
  3559. var getNumColumns = function () {
  3560. return dimensions.get().map(function (d) {
  3561. return d.numColumns;
  3562. });
  3563. };
  3564. return nu$6({
  3565. readState: function () {
  3566. return dimensions.get().map(function (d) {
  3567. return {
  3568. numRows: String(d.numRows),
  3569. numColumns: String(d.numColumns)
  3570. };
  3571. }).getOr({
  3572. numRows: '?',
  3573. numColumns: '?'
  3574. });
  3575. },
  3576. setGridSize: setGridSize,
  3577. getNumRows: getNumRows,
  3578. getNumColumns: getNumColumns
  3579. });
  3580. };
  3581. var init = function (spec) {
  3582. return spec.state(spec);
  3583. };
  3584. var KeyingState = /*#__PURE__*/Object.freeze({
  3585. __proto__: null,
  3586. flatgrid: flatgrid,
  3587. init: init
  3588. });
  3589. var onDirection = function (isLtr, isRtl) {
  3590. return function (element) {
  3591. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3592. };
  3593. };
  3594. var getDirection = function (element) {
  3595. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3596. };
  3597. var useH = function (movement) {
  3598. return function (component, simulatedEvent, config, state) {
  3599. var move = movement(component.element());
  3600. return use(move, component, simulatedEvent, config, state);
  3601. };
  3602. };
  3603. var west = function (moveLeft, moveRight) {
  3604. var movement = onDirection(moveLeft, moveRight);
  3605. return useH(movement);
  3606. };
  3607. var east = function (moveLeft, moveRight) {
  3608. var movement = onDirection(moveRight, moveLeft);
  3609. return useH(movement);
  3610. };
  3611. var useV = function (move) {
  3612. return function (component, simulatedEvent, config, state) {
  3613. return use(move, component, simulatedEvent, config, state);
  3614. };
  3615. };
  3616. var use = function (move, component, simulatedEvent, config, state) {
  3617. var outcome = config.focusManager.get(component).bind(function (focused) {
  3618. return move(component.element(), focused, config, state);
  3619. });
  3620. return outcome.map(function (newFocus) {
  3621. config.focusManager.set(component, newFocus);
  3622. return true;
  3623. });
  3624. };
  3625. var north = useV;
  3626. var south = useV;
  3627. var move = useV;
  3628. var isHidden = function (dom) {
  3629. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3630. };
  3631. var isVisible = function (element) {
  3632. return !isHidden(element.dom());
  3633. };
  3634. var locate = function (candidates, predicate) {
  3635. return findIndex(candidates, predicate).map(function (index) {
  3636. return {
  3637. index: constant(index),
  3638. candidates: constant(candidates)
  3639. };
  3640. });
  3641. };
  3642. var locateVisible = function (container, current, selector) {
  3643. var predicate = function (x) {
  3644. return eq(x, current);
  3645. };
  3646. var candidates = descendants(container, selector);
  3647. var visible = filter$1(candidates, isVisible);
  3648. return locate(visible, predicate);
  3649. };
  3650. var findIndex$1 = function (elements, target) {
  3651. return findIndex(elements, function (elem) {
  3652. return eq(target, elem);
  3653. });
  3654. };
  3655. var withGrid = function (values, index, numCols, f) {
  3656. var oldRow = Math.floor(index / numCols);
  3657. var oldColumn = index % numCols;
  3658. return f(oldRow, oldColumn).bind(function (address) {
  3659. var newIndex = address.row() * numCols + address.column();
  3660. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  3661. });
  3662. };
  3663. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  3664. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3665. var onLastRow = oldRow === numRows - 1;
  3666. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3667. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3668. return Option.some({
  3669. row: constant(oldRow),
  3670. column: constant(newColumn)
  3671. });
  3672. });
  3673. };
  3674. var cycleVertical = function (values, index, numRows, numCols, delta) {
  3675. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3676. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3677. var onLastRow = newRow === numRows - 1;
  3678. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3679. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  3680. return Option.some({
  3681. row: constant(newRow),
  3682. column: constant(newCol)
  3683. });
  3684. });
  3685. };
  3686. var cycleRight = function (values, index, numRows, numCols) {
  3687. return cycleHorizontal(values, index, numRows, numCols, +1);
  3688. };
  3689. var cycleLeft = function (values, index, numRows, numCols) {
  3690. return cycleHorizontal(values, index, numRows, numCols, -1);
  3691. };
  3692. var cycleUp = function (values, index, numRows, numCols) {
  3693. return cycleVertical(values, index, numRows, numCols, -1);
  3694. };
  3695. var cycleDown = function (values, index, numRows, numCols) {
  3696. return cycleVertical(values, index, numRows, numCols, +1);
  3697. };
  3698. var schema$2 = [
  3699. strict$1('selector'),
  3700. defaulted$1('execute', defaultExecute),
  3701. onKeyboardHandler('onEscape'),
  3702. defaulted$1('captureTab', false),
  3703. initSize()
  3704. ];
  3705. var focusIn = function (component, gridConfig, _gridState) {
  3706. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  3707. gridConfig.focusManager.set(component, first);
  3708. });
  3709. };
  3710. var findCurrent = function (component, gridConfig) {
  3711. return gridConfig.focusManager.get(component).bind(function (elem) {
  3712. return closest$2(elem, gridConfig.selector);
  3713. });
  3714. };
  3715. var execute$2 = function (component, simulatedEvent, gridConfig, _gridState) {
  3716. return findCurrent(component, gridConfig).bind(function (focused) {
  3717. return gridConfig.execute(component, simulatedEvent, focused);
  3718. });
  3719. };
  3720. var doMove = function (cycle) {
  3721. return function (element, focused, gridConfig, gridState) {
  3722. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3723. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3724. });
  3725. };
  3726. };
  3727. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  3728. return gridConfig.captureTab ? Option.some(true) : Option.none();
  3729. };
  3730. var doEscape = function (component, simulatedEvent, gridConfig) {
  3731. return gridConfig.onEscape(component, simulatedEvent);
  3732. };
  3733. var moveLeft = doMove(cycleLeft);
  3734. var moveRight = doMove(cycleRight);
  3735. var moveNorth = doMove(cycleUp);
  3736. var moveSouth = doMove(cycleDown);
  3737. var getKeydownRules$1 = constant([
  3738. rule(inSet(LEFT()), west(moveLeft, moveRight)),
  3739. rule(inSet(RIGHT()), east(moveLeft, moveRight)),
  3740. rule(inSet(UP()), north(moveNorth)),
  3741. rule(inSet(DOWN()), south(moveSouth)),
  3742. rule(and([
  3743. isShift,
  3744. inSet(TAB())
  3745. ]), handleTab),
  3746. rule(and([
  3747. isNotShift,
  3748. inSet(TAB())
  3749. ]), handleTab),
  3750. rule(inSet(ESCAPE()), doEscape),
  3751. rule(inSet(SPACE().concat(ENTER())), execute$2)
  3752. ]);
  3753. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3754. var FlatgridType = typical(schema$2, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  3755. return Option.some(focusIn);
  3756. });
  3757. var horizontal = function (container, selector, current, delta) {
  3758. var isDisabledButton = function (candidate) {
  3759. return name(candidate) === 'button' && get$1(candidate, 'disabled') === 'disabled';
  3760. };
  3761. var tryCycle = function (initial, index, candidates) {
  3762. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  3763. if (newIndex === initial) {
  3764. return Option.none();
  3765. } else {
  3766. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  3767. }
  3768. };
  3769. return locateVisible(container, current, selector).bind(function (identified) {
  3770. var index = identified.index();
  3771. var candidates = identified.candidates();
  3772. return tryCycle(index, index, candidates);
  3773. });
  3774. };
  3775. var schema$3 = [
  3776. strict$1('selector'),
  3777. defaulted$1('getInitial', Option.none),
  3778. defaulted$1('execute', defaultExecute),
  3779. onKeyboardHandler('onEscape'),
  3780. defaulted$1('executeOnMove', false),
  3781. defaulted$1('allowVertical', true)
  3782. ];
  3783. var findCurrent$1 = function (component, flowConfig) {
  3784. return flowConfig.focusManager.get(component).bind(function (elem) {
  3785. return closest$2(elem, flowConfig.selector);
  3786. });
  3787. };
  3788. var execute$3 = function (component, simulatedEvent, flowConfig) {
  3789. return findCurrent$1(component, flowConfig).bind(function (focused) {
  3790. return flowConfig.execute(component, simulatedEvent, focused);
  3791. });
  3792. };
  3793. var focusIn$1 = function (component, flowConfig, _state) {
  3794. flowConfig.getInitial(component).orThunk(function () {
  3795. return descendant$1(component.element(), flowConfig.selector);
  3796. }).each(function (first) {
  3797. flowConfig.focusManager.set(component, first);
  3798. });
  3799. };
  3800. var moveLeft$1 = function (element, focused, info) {
  3801. return horizontal(element, info.selector, focused, -1);
  3802. };
  3803. var moveRight$1 = function (element, focused, info) {
  3804. return horizontal(element, info.selector, focused, +1);
  3805. };
  3806. var doMove$1 = function (movement) {
  3807. return function (component, simulatedEvent, flowConfig, flowState) {
  3808. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  3809. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  3810. });
  3811. };
  3812. };
  3813. var doEscape$1 = function (component, simulatedEvent, flowConfig) {
  3814. return flowConfig.onEscape(component, simulatedEvent);
  3815. };
  3816. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  3817. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  3818. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  3819. return [
  3820. rule(inSet(westMovers), doMove$1(west(moveLeft$1, moveRight$1))),
  3821. rule(inSet(eastMovers), doMove$1(east(moveLeft$1, moveRight$1))),
  3822. rule(inSet(ENTER()), execute$3),
  3823. rule(inSet(SPACE()), execute$3),
  3824. rule(inSet(ESCAPE()), doEscape$1)
  3825. ];
  3826. };
  3827. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3828. var FlowType = typical(schema$3, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  3829. return Option.some(focusIn$1);
  3830. });
  3831. var toCell = function (matrix, rowIndex, columnIndex) {
  3832. return Option.from(matrix[rowIndex]).bind(function (row) {
  3833. return Option.from(row[columnIndex]).map(function (cell) {
  3834. return {
  3835. rowIndex: rowIndex,
  3836. columnIndex: columnIndex,
  3837. cell: cell
  3838. };
  3839. });
  3840. });
  3841. };
  3842. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  3843. var row = matrix[rowIndex];
  3844. var colsInRow = row.length;
  3845. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  3846. return toCell(matrix, rowIndex, newColIndex);
  3847. };
  3848. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  3849. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  3850. var colsInNextRow = matrix[nextRowIndex].length;
  3851. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  3852. return toCell(matrix, nextRowIndex, nextColIndex);
  3853. };
  3854. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  3855. var row = matrix[rowIndex];
  3856. var colsInRow = row.length;
  3857. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  3858. return toCell(matrix, rowIndex, newColIndex);
  3859. };
  3860. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  3861. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  3862. var colsInNextRow = matrix[nextRowIndex].length;
  3863. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  3864. return toCell(matrix, nextRowIndex, nextColIndex);
  3865. };
  3866. var cycleRight$1 = function (matrix, startRow, startCol) {
  3867. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  3868. };
  3869. var cycleLeft$1 = function (matrix, startRow, startCol) {
  3870. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  3871. };
  3872. var cycleUp$1 = function (matrix, startRow, startCol) {
  3873. return cycleVertical$1(matrix, startCol, startRow, -1);
  3874. };
  3875. var cycleDown$1 = function (matrix, startRow, startCol) {
  3876. return cycleVertical$1(matrix, startCol, startRow, +1);
  3877. };
  3878. var moveLeft$2 = function (matrix, startRow, startCol) {
  3879. return moveHorizontal(matrix, startRow, startCol, -1);
  3880. };
  3881. var moveRight$2 = function (matrix, startRow, startCol) {
  3882. return moveHorizontal(matrix, startRow, startCol, +1);
  3883. };
  3884. var moveUp = function (matrix, startRow, startCol) {
  3885. return moveVertical(matrix, startCol, startRow, -1);
  3886. };
  3887. var moveDown = function (matrix, startRow, startCol) {
  3888. return moveVertical(matrix, startCol, startRow, +1);
  3889. };
  3890. var schema$4 = [
  3891. strictObjOf('selectors', [
  3892. strict$1('row'),
  3893. strict$1('cell')
  3894. ]),
  3895. defaulted$1('cycles', true),
  3896. defaulted$1('previousSelector', Option.none),
  3897. defaulted$1('execute', defaultExecute)
  3898. ];
  3899. var focusIn$2 = function (component, matrixConfig, _state) {
  3900. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  3901. var selectors = matrixConfig.selectors;
  3902. return descendant$1(component.element(), selectors.cell);
  3903. });
  3904. focused.each(function (cell) {
  3905. matrixConfig.focusManager.set(component, cell);
  3906. });
  3907. };
  3908. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  3909. return search(component.element()).bind(function (focused) {
  3910. return matrixConfig.execute(component, simulatedEvent, focused);
  3911. });
  3912. };
  3913. var toMatrix = function (rows, matrixConfig) {
  3914. return map$1(rows, function (row) {
  3915. return descendants(row, matrixConfig.selectors.cell);
  3916. });
  3917. };
  3918. var doMove$2 = function (ifCycle, ifMove) {
  3919. return function (element, focused, matrixConfig) {
  3920. var move = matrixConfig.cycles ? ifCycle : ifMove;
  3921. return closest$2(focused, matrixConfig.selectors.row).bind(function (inRow) {
  3922. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  3923. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  3924. var allRows = descendants(element, matrixConfig.selectors.row);
  3925. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  3926. var matrix = toMatrix(allRows, matrixConfig);
  3927. return move(matrix, rowIndex, colIndex).map(function (next) {
  3928. return next.cell;
  3929. });
  3930. });
  3931. });
  3932. });
  3933. };
  3934. };
  3935. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  3936. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  3937. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  3938. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  3939. var getKeydownRules$3 = constant([
  3940. rule(inSet(LEFT()), west(moveLeft$3, moveRight$3)),
  3941. rule(inSet(RIGHT()), east(moveLeft$3, moveRight$3)),
  3942. rule(inSet(UP()), north(moveNorth$1)),
  3943. rule(inSet(DOWN()), south(moveSouth$1)),
  3944. rule(inSet(SPACE().concat(ENTER())), execute$4)
  3945. ]);
  3946. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3947. var MatrixType = typical(schema$4, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  3948. return Option.some(focusIn$2);
  3949. });
  3950. var schema$5 = [
  3951. strict$1('selector'),
  3952. defaulted$1('execute', defaultExecute),
  3953. defaulted$1('moveOnTab', false)
  3954. ];
  3955. var execute$5 = function (component, simulatedEvent, menuConfig) {
  3956. return menuConfig.focusManager.get(component).bind(function (focused) {
  3957. return menuConfig.execute(component, simulatedEvent, focused);
  3958. });
  3959. };
  3960. var focusIn$3 = function (component, menuConfig, _state) {
  3961. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  3962. menuConfig.focusManager.set(component, first);
  3963. });
  3964. };
  3965. var moveUp$1 = function (element, focused, info) {
  3966. return horizontal(element, info.selector, focused, -1);
  3967. };
  3968. var moveDown$1 = function (element, focused, info) {
  3969. return horizontal(element, info.selector, focused, +1);
  3970. };
  3971. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  3972. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  3973. };
  3974. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  3975. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  3976. };
  3977. var getKeydownRules$4 = constant([
  3978. rule(inSet(UP()), move(moveUp$1)),
  3979. rule(inSet(DOWN()), move(moveDown$1)),
  3980. rule(and([
  3981. isShift,
  3982. inSet(TAB())
  3983. ]), fireShiftTab),
  3984. rule(and([
  3985. isNotShift,
  3986. inSet(TAB())
  3987. ]), fireTab),
  3988. rule(inSet(ENTER()), execute$5),
  3989. rule(inSet(SPACE()), execute$5)
  3990. ]);
  3991. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3992. var MenuType = typical(schema$5, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  3993. return Option.some(focusIn$3);
  3994. });
  3995. var schema$6 = [
  3996. onKeyboardHandler('onSpace'),
  3997. onKeyboardHandler('onEnter'),
  3998. onKeyboardHandler('onShiftEnter'),
  3999. onKeyboardHandler('onLeft'),
  4000. onKeyboardHandler('onRight'),
  4001. onKeyboardHandler('onTab'),
  4002. onKeyboardHandler('onShiftTab'),
  4003. onKeyboardHandler('onUp'),
  4004. onKeyboardHandler('onDown'),
  4005. onKeyboardHandler('onEscape'),
  4006. defaulted$1('stopSpaceKeyup', false),
  4007. option('focusIn')
  4008. ];
  4009. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  4010. return [
  4011. rule(inSet(SPACE()), specialInfo.onSpace),
  4012. rule(and([
  4013. isNotShift,
  4014. inSet(ENTER())
  4015. ]), specialInfo.onEnter),
  4016. rule(and([
  4017. isShift,
  4018. inSet(ENTER())
  4019. ]), specialInfo.onShiftEnter),
  4020. rule(and([
  4021. isShift,
  4022. inSet(TAB())
  4023. ]), specialInfo.onShiftTab),
  4024. rule(and([
  4025. isNotShift,
  4026. inSet(TAB())
  4027. ]), specialInfo.onTab),
  4028. rule(inSet(UP()), specialInfo.onUp),
  4029. rule(inSet(DOWN()), specialInfo.onDown),
  4030. rule(inSet(LEFT()), specialInfo.onLeft),
  4031. rule(inSet(RIGHT()), specialInfo.onRight),
  4032. rule(inSet(SPACE()), specialInfo.onSpace),
  4033. rule(inSet(ESCAPE()), specialInfo.onEscape)
  4034. ];
  4035. };
  4036. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  4037. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  4038. };
  4039. var SpecialType = typical(schema$6, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  4040. return specialInfo.focusIn;
  4041. });
  4042. var acyclic = AcyclicType.schema();
  4043. var cyclic = CyclicType.schema();
  4044. var flow = FlowType.schema();
  4045. var flatgrid$1 = FlatgridType.schema();
  4046. var matrix = MatrixType.schema();
  4047. var execution = ExecutionType.schema();
  4048. var menu = MenuType.schema();
  4049. var special = SpecialType.schema();
  4050. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4051. __proto__: null,
  4052. acyclic: acyclic,
  4053. cyclic: cyclic,
  4054. flow: flow,
  4055. flatgrid: flatgrid$1,
  4056. matrix: matrix,
  4057. execution: execution,
  4058. menu: menu,
  4059. special: special
  4060. });
  4061. var isFlatgridState = function (keyState) {
  4062. return hasNonNullableKey(keyState, 'setGridSize');
  4063. };
  4064. var Keying = createModes$1({
  4065. branchKey: 'mode',
  4066. branches: KeyboardBranches,
  4067. name: 'keying',
  4068. active: {
  4069. events: function (keyingConfig, keyingState) {
  4070. var handler = keyingConfig.handler;
  4071. return handler.toEvents(keyingConfig, keyingState);
  4072. }
  4073. },
  4074. apis: {
  4075. focusIn: function (component, keyConfig, keyState) {
  4076. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4077. component.getSystem().triggerFocus(component.element(), component.element());
  4078. }, function (sendFocusIn) {
  4079. sendFocusIn(component, keyConfig, keyState);
  4080. });
  4081. },
  4082. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4083. if (!isFlatgridState(keyState)) {
  4084. domGlobals.console.error('Layout does not support setGridSize');
  4085. } else {
  4086. keyState.setGridSize(numRows, numColumns);
  4087. }
  4088. }
  4089. },
  4090. state: KeyingState
  4091. });
  4092. var field$1 = function (name, forbidden) {
  4093. return defaultedObjOf(name, {}, map$1(forbidden, function (f) {
  4094. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4095. }).concat([state$1('dump', identity)]));
  4096. };
  4097. var get$6 = function (data) {
  4098. return data.dump;
  4099. };
  4100. var augment = function (data, original) {
  4101. return __assign(__assign({}, data.dump), derive$1(original));
  4102. };
  4103. var SketchBehaviours = {
  4104. field: field$1,
  4105. augment: augment,
  4106. get: get$6
  4107. };
  4108. var _placeholder = 'placeholder';
  4109. var adt$2 = Adt.generate([
  4110. {
  4111. single: [
  4112. 'required',
  4113. 'valueThunk'
  4114. ]
  4115. },
  4116. {
  4117. multiple: [
  4118. 'required',
  4119. 'valueThunks'
  4120. ]
  4121. }
  4122. ]);
  4123. var isSubstituted = function (spec) {
  4124. return has(spec, 'uiType');
  4125. };
  4126. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4127. if (owner.exists(function (o) {
  4128. return o !== compSpec.owner;
  4129. })) {
  4130. return adt$2.single(true, constant(compSpec));
  4131. }
  4132. return get(placeholders, compSpec.name).fold(function () {
  4133. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4134. }, function (newSpec) {
  4135. return newSpec.replace();
  4136. });
  4137. };
  4138. var scan = function (owner, detail, compSpec, placeholders) {
  4139. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  4140. return subPlaceholder(owner, detail, compSpec, placeholders);
  4141. } else {
  4142. return adt$2.single(false, constant(compSpec));
  4143. }
  4144. };
  4145. var substitute = function (owner, detail, compSpec, placeholders) {
  4146. var base = scan(owner, detail, compSpec, placeholders);
  4147. return base.fold(function (req, valueThunk) {
  4148. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  4149. var childSpecs = get(value, 'components').getOr([]);
  4150. var substituted = bind(childSpecs, function (c) {
  4151. return substitute(owner, detail, c, placeholders);
  4152. });
  4153. return [__assign(__assign({}, value), { components: substituted })];
  4154. }, function (req, valuesThunk) {
  4155. if (isSubstituted(compSpec)) {
  4156. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4157. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4158. return preprocessor(values);
  4159. } else {
  4160. return valuesThunk(detail);
  4161. }
  4162. });
  4163. };
  4164. var substituteAll = function (owner, detail, components, placeholders) {
  4165. return bind(components, function (c) {
  4166. return substitute(owner, detail, c, placeholders);
  4167. });
  4168. };
  4169. var oneReplace = function (label, replacements) {
  4170. var called = false;
  4171. var used = function () {
  4172. return called;
  4173. };
  4174. var replace = function () {
  4175. if (called) {
  4176. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4177. }
  4178. called = true;
  4179. return replacements;
  4180. };
  4181. var required = function () {
  4182. return replacements.fold(function (req, _) {
  4183. return req;
  4184. }, function (req, _) {
  4185. return req;
  4186. });
  4187. };
  4188. return {
  4189. name: constant(label),
  4190. required: required,
  4191. used: used,
  4192. replace: replace
  4193. };
  4194. };
  4195. var substitutePlaces = function (owner, detail, components, placeholders) {
  4196. var ps = map(placeholders, function (ph, name) {
  4197. return oneReplace(name, ph);
  4198. });
  4199. var outcome = substituteAll(owner, detail, components, ps);
  4200. each(ps, function (p) {
  4201. if (p.used() === false && p.required()) {
  4202. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4203. }
  4204. });
  4205. return outcome;
  4206. };
  4207. var single = adt$2.single;
  4208. var multiple = adt$2.multiple;
  4209. var placeholder = constant(_placeholder);
  4210. var unique = 0;
  4211. var generate$1 = function (prefix) {
  4212. var date = new Date();
  4213. var time = date.getTime();
  4214. var random = Math.floor(Math.random() * 1000000000);
  4215. unique++;
  4216. return prefix + '_' + random + unique + String(time);
  4217. };
  4218. var adt$3 = Adt.generate([
  4219. { required: ['data'] },
  4220. { external: ['data'] },
  4221. { optional: ['data'] },
  4222. { group: ['data'] }
  4223. ]);
  4224. var fFactory = defaulted$1('factory', { sketch: identity });
  4225. var fSchema = defaulted$1('schema', []);
  4226. var fName = strict$1('name');
  4227. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  4228. return '<alloy.' + generate$1(typeSpec.name) + '>';
  4229. }), anyValue$1());
  4230. var fGroupSchema = state$1('schema', function () {
  4231. return [option('preprocess')];
  4232. });
  4233. var fDefaults = defaulted$1('defaults', constant({}));
  4234. var fOverrides = defaulted$1('overrides', constant({}));
  4235. var requiredSpec = objOf([
  4236. fFactory,
  4237. fSchema,
  4238. fName,
  4239. fPname,
  4240. fDefaults,
  4241. fOverrides
  4242. ]);
  4243. var externalSpec = objOf([
  4244. fFactory,
  4245. fSchema,
  4246. fName,
  4247. fDefaults,
  4248. fOverrides
  4249. ]);
  4250. var optionalSpec = objOf([
  4251. fFactory,
  4252. fSchema,
  4253. fName,
  4254. fPname,
  4255. fDefaults,
  4256. fOverrides
  4257. ]);
  4258. var groupSpec = objOf([
  4259. fFactory,
  4260. fGroupSchema,
  4261. fName,
  4262. strict$1('unit'),
  4263. fPname,
  4264. fDefaults,
  4265. fOverrides
  4266. ]);
  4267. var asNamedPart = function (part) {
  4268. return part.fold(Option.some, Option.none, Option.some, Option.some);
  4269. };
  4270. var name$1 = function (part) {
  4271. var get = function (data) {
  4272. return data.name;
  4273. };
  4274. return part.fold(get, get, get, get);
  4275. };
  4276. var convert = function (adtConstructor, partSchema) {
  4277. return function (spec) {
  4278. var data = asRawOrDie('Converting part type', partSchema, spec);
  4279. return adtConstructor(data);
  4280. };
  4281. };
  4282. var required = convert(adt$3.required, requiredSpec);
  4283. var external = convert(adt$3.external, externalSpec);
  4284. var optional = convert(adt$3.optional, optionalSpec);
  4285. var group = convert(adt$3.group, groupSpec);
  4286. var original = constant('entirety');
  4287. var combine = function (detail, data, partSpec, partValidated) {
  4288. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4289. };
  4290. var subs = function (owner, detail, parts) {
  4291. var internals = {};
  4292. var externals = {};
  4293. each$1(parts, function (part) {
  4294. part.fold(function (data) {
  4295. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  4296. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4297. });
  4298. }, function (data) {
  4299. var partSpec = detail.parts[data.name];
  4300. externals[data.name] = constant(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  4301. }, function (data) {
  4302. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  4303. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4304. });
  4305. }, function (data) {
  4306. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4307. var units = detail[data.name];
  4308. return map$1(units, function (u) {
  4309. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4310. });
  4311. });
  4312. });
  4313. });
  4314. return {
  4315. internals: constant(internals),
  4316. externals: constant(externals)
  4317. };
  4318. };
  4319. var generate$2 = function (owner, parts) {
  4320. var r = {};
  4321. each$1(parts, function (part) {
  4322. asNamedPart(part).each(function (np) {
  4323. var g = doGenerateOne(owner, np.pname);
  4324. r[np.name] = function (config) {
  4325. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4326. return __assign(__assign({}, g), {
  4327. config: config,
  4328. validated: validated
  4329. });
  4330. };
  4331. });
  4332. });
  4333. return r;
  4334. };
  4335. var doGenerateOne = function (owner, pname) {
  4336. return {
  4337. uiType: placeholder(),
  4338. owner: owner,
  4339. name: pname
  4340. };
  4341. };
  4342. var generateOne = function (owner, pname, config) {
  4343. return {
  4344. uiType: placeholder(),
  4345. owner: owner,
  4346. name: pname,
  4347. config: config,
  4348. validated: {}
  4349. };
  4350. };
  4351. var schemas = function (parts) {
  4352. return bind(parts, function (part) {
  4353. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  4354. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  4355. }).toArray();
  4356. });
  4357. };
  4358. var names = function (parts) {
  4359. return map$1(parts, name$1);
  4360. };
  4361. var substitutes = function (owner, detail, parts) {
  4362. return subs(owner, detail, parts);
  4363. };
  4364. var components = function (owner, detail, internals) {
  4365. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  4366. };
  4367. var getPart = function (component, detail, partKey) {
  4368. var uid = detail.partUids[partKey];
  4369. return component.getSystem().getByUid(uid).toOption();
  4370. };
  4371. var getPartOrDie = function (component, detail, partKey) {
  4372. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4373. };
  4374. var getAllParts = function (component, detail) {
  4375. var system = component.getSystem();
  4376. return map(detail.partUids, function (pUid, _k) {
  4377. return constant(system.getByUid(pUid));
  4378. });
  4379. };
  4380. var defaultUids = function (baseUid, partTypes) {
  4381. var partNames = names(partTypes);
  4382. return wrapAll$1(map$1(partNames, function (pn) {
  4383. return {
  4384. key: pn,
  4385. value: baseUid + '-' + pn
  4386. };
  4387. }));
  4388. };
  4389. var defaultUidsSchema = function (partTypes) {
  4390. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  4391. return defaultUids(spec.uid, partTypes);
  4392. }), anyValue$1());
  4393. };
  4394. var premadeTag = generate$1('alloy-premade');
  4395. var premade = function (comp) {
  4396. return wrap$1(premadeTag, comp);
  4397. };
  4398. var getPremade = function (spec) {
  4399. return get(spec, premadeTag);
  4400. };
  4401. var makeApi = function (f) {
  4402. return markAsSketchApi(function (component) {
  4403. var rest = [];
  4404. for (var _i = 1; _i < arguments.length; _i++) {
  4405. rest[_i - 1] = arguments[_i];
  4406. }
  4407. return f.apply(void 0, __spreadArrays([
  4408. component.getApis(),
  4409. component
  4410. ], rest));
  4411. }, f);
  4412. };
  4413. var prefix$1 = constant('alloy-id-');
  4414. var idAttr = constant('data-alloy-id');
  4415. var prefix$2 = prefix$1();
  4416. var idAttr$1 = idAttr();
  4417. var write = function (label, elem) {
  4418. var id = generate$1(prefix$2 + label);
  4419. writeOnly(elem, id);
  4420. return id;
  4421. };
  4422. var writeOnly = function (elem, uid) {
  4423. Object.defineProperty(elem.dom(), idAttr$1, {
  4424. value: uid,
  4425. writable: true
  4426. });
  4427. };
  4428. var read$2 = function (elem) {
  4429. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  4430. return Option.from(id);
  4431. };
  4432. var generate$3 = function (prefix) {
  4433. return generate$1(prefix);
  4434. };
  4435. var base = function (partSchemas, partUidsSchemas) {
  4436. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  4437. return ps.concat([
  4438. strict$1('uid'),
  4439. defaulted$1('dom', {}),
  4440. defaulted$1('components', []),
  4441. snapshot('originalSpec'),
  4442. defaulted$1('debug.sketcher', {})
  4443. ]).concat(partUidsSchemas);
  4444. };
  4445. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4446. var baseS = base(partSchemas, partUidsSchemas);
  4447. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4448. };
  4449. var single$1 = function (owner, schema, factory, spec) {
  4450. var specWithUid = supplyUid(spec);
  4451. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  4452. return factory(detail, specWithUid);
  4453. };
  4454. var composite = function (owner, schema, partTypes, factory, spec) {
  4455. var specWithUid = supplyUid(spec);
  4456. var partSchemas = schemas(partTypes);
  4457. var partUidsSchema = defaultUidsSchema(partTypes);
  4458. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4459. var subs = substitutes(owner, detail, partTypes);
  4460. var components$1 = components(owner, detail, subs.internals());
  4461. return factory(detail, components$1, specWithUid, subs.externals());
  4462. };
  4463. var hasUid = function (spec) {
  4464. return has(spec, 'uid');
  4465. };
  4466. var supplyUid = function (spec) {
  4467. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$3('uid') });
  4468. };
  4469. function isSketchSpec(spec) {
  4470. return spec.uid !== undefined;
  4471. }
  4472. var singleSchema = objOfOnly([
  4473. strict$1('name'),
  4474. strict$1('factory'),
  4475. strict$1('configFields'),
  4476. defaulted$1('apis', {}),
  4477. defaulted$1('extraApis', {})
  4478. ]);
  4479. var compositeSchema = objOfOnly([
  4480. strict$1('name'),
  4481. strict$1('factory'),
  4482. strict$1('configFields'),
  4483. strict$1('partFields'),
  4484. defaulted$1('apis', {}),
  4485. defaulted$1('extraApis', {})
  4486. ]);
  4487. var single$2 = function (rawConfig) {
  4488. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4489. var sketch = function (spec) {
  4490. return single$1(config.name, config.configFields, config.factory, spec);
  4491. };
  4492. var apis = map(config.apis, makeApi);
  4493. var extraApis = map(config.extraApis, function (f, k) {
  4494. return markAsExtraApi(f, k);
  4495. });
  4496. return __assign(__assign({
  4497. name: constant(config.name),
  4498. configFields: constant(config.configFields),
  4499. sketch: sketch
  4500. }, apis), extraApis);
  4501. };
  4502. var composite$1 = function (rawConfig) {
  4503. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4504. var sketch = function (spec) {
  4505. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  4506. };
  4507. var parts = generate$2(config.name, config.partFields);
  4508. var apis = map(config.apis, makeApi);
  4509. var extraApis = map(config.extraApis, function (f, k) {
  4510. return markAsExtraApi(f, k);
  4511. });
  4512. return __assign(__assign({
  4513. name: constant(config.name),
  4514. partFields: constant(config.partFields),
  4515. configFields: constant(config.configFields),
  4516. sketch: sketch,
  4517. parts: constant(parts)
  4518. }, apis), extraApis);
  4519. };
  4520. var factory = function (detail) {
  4521. var events = events$2(detail.action);
  4522. var tag = detail.dom.tag;
  4523. var lookupAttr = function (attr) {
  4524. return get(detail.dom, 'attributes').bind(function (attrs) {
  4525. return get(attrs, attr);
  4526. });
  4527. };
  4528. var getModAttributes = function () {
  4529. if (tag === 'button') {
  4530. var type = lookupAttr('type').getOr('button');
  4531. var roleAttrs = lookupAttr('role').map(function (role) {
  4532. return { role: role };
  4533. }).getOr({});
  4534. return __assign({ type: type }, roleAttrs);
  4535. } else {
  4536. var role = lookupAttr('role').getOr('button');
  4537. return { role: role };
  4538. }
  4539. };
  4540. return {
  4541. uid: detail.uid,
  4542. dom: detail.dom,
  4543. components: detail.components,
  4544. events: events,
  4545. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4546. Focusing.config({}),
  4547. Keying.config({
  4548. mode: 'execution',
  4549. useSpace: true,
  4550. useEnter: true
  4551. })
  4552. ]),
  4553. domModification: { attributes: getModAttributes() },
  4554. eventOrder: detail.eventOrder
  4555. };
  4556. };
  4557. var Button = single$2({
  4558. name: 'Button',
  4559. factory: factory,
  4560. configFields: [
  4561. defaulted$1('uid', undefined),
  4562. strict$1('dom'),
  4563. defaulted$1('components', []),
  4564. SketchBehaviours.field('buttonBehaviours', [
  4565. Focusing,
  4566. Keying
  4567. ]),
  4568. option('action'),
  4569. option('role'),
  4570. defaulted$1('eventOrder', {})
  4571. ]
  4572. });
  4573. var exhibit$2 = function () {
  4574. return nu$5({
  4575. styles: {
  4576. '-webkit-user-select': 'none',
  4577. 'user-select': 'none',
  4578. '-ms-user-select': 'none',
  4579. '-moz-user-select': '-moz-none'
  4580. },
  4581. attributes: { unselectable: 'on' }
  4582. });
  4583. };
  4584. var events$4 = function () {
  4585. return derive([abort(selectstart(), constant(true))]);
  4586. };
  4587. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4588. __proto__: null,
  4589. events: events$4,
  4590. exhibit: exhibit$2
  4591. });
  4592. var Unselecting = create$1({
  4593. fields: [],
  4594. name: 'unselecting',
  4595. active: ActiveUnselecting
  4596. });
  4597. var getAttrs = function (elem) {
  4598. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  4599. return foldl(attributes, function (b, attr) {
  4600. var _a;
  4601. if (attr.name === 'class') {
  4602. return b;
  4603. } else {
  4604. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4605. }
  4606. }, {});
  4607. };
  4608. var getClasses = function (elem) {
  4609. return Array.prototype.slice.call(elem.dom().classList, 0);
  4610. };
  4611. var fromHtml$2 = function (html) {
  4612. var elem = Element.fromHtml(html);
  4613. var children$1 = children(elem);
  4614. var attrs = getAttrs(elem);
  4615. var classes = getClasses(elem);
  4616. var contents = children$1.length === 0 ? {} : { innerHtml: get$3(elem) };
  4617. return __assign({
  4618. tag: name(elem),
  4619. classes: classes,
  4620. attributes: attrs
  4621. }, contents);
  4622. };
  4623. var dom$1 = function (rawHtml) {
  4624. var html = supplant(rawHtml, { prefix: prefix });
  4625. return fromHtml$2(html);
  4626. };
  4627. var spec = function (rawHtml) {
  4628. return { dom: dom$1(rawHtml) };
  4629. };
  4630. var forToolbarCommand = function (editor, command) {
  4631. return forToolbar(command, function () {
  4632. editor.execCommand(command);
  4633. }, {}, editor);
  4634. };
  4635. var getToggleBehaviours = function (command) {
  4636. return derive$1([
  4637. Toggling.config({
  4638. toggleClass: resolve('toolbar-button-selected'),
  4639. toggleOnExecute: false,
  4640. aria: { mode: 'pressed' }
  4641. }),
  4642. format(command, function (button, status) {
  4643. var toggle = status ? Toggling.on : Toggling.off;
  4644. toggle(button);
  4645. })
  4646. ]);
  4647. };
  4648. var forToolbarStateCommand = function (editor, command) {
  4649. var extraBehaviours = getToggleBehaviours(command);
  4650. return forToolbar(command, function () {
  4651. editor.execCommand(command);
  4652. }, extraBehaviours, editor);
  4653. };
  4654. var forToolbarStateAction = function (editor, clazz, command, action) {
  4655. var extraBehaviours = getToggleBehaviours(command);
  4656. return forToolbar(clazz, action, extraBehaviours, editor);
  4657. };
  4658. var getToolbarIconButton = function (clazz, editor) {
  4659. var icons = editor.ui.registry.getAll().icons;
  4660. var optOxideIcon = Option.from(icons[clazz]);
  4661. return optOxideIcon.fold(function () {
  4662. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4663. }, function (icon) {
  4664. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4665. });
  4666. };
  4667. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4668. return Button.sketch({
  4669. dom: getToolbarIconButton(clazz, editor),
  4670. action: action,
  4671. buttonBehaviours: deepMerge(derive$1([Unselecting.config({})]), extraBehaviours)
  4672. });
  4673. };
  4674. var labelPart = optional({
  4675. schema: [strict$1('dom')],
  4676. name: 'label'
  4677. });
  4678. var edgePart = function (name) {
  4679. return optional({
  4680. name: '' + name + '-edge',
  4681. overrides: function (detail) {
  4682. var action = detail.model.manager.edgeActions[name];
  4683. return action.fold(function () {
  4684. return {};
  4685. }, function (a) {
  4686. return {
  4687. events: derive([
  4688. runActionExtra(touchstart(), function (comp, se, d) {
  4689. return a(comp, d);
  4690. }, [detail]),
  4691. runActionExtra(mousedown(), function (comp, se, d) {
  4692. return a(comp, d);
  4693. }, [detail]),
  4694. runActionExtra(mousemove(), function (comp, se, det) {
  4695. if (det.mouseIsDown.get()) {
  4696. a(comp, det);
  4697. }
  4698. }, [detail])
  4699. ])
  4700. };
  4701. });
  4702. }
  4703. });
  4704. };
  4705. var tlEdgePart = edgePart('top-left');
  4706. var tedgePart = edgePart('top');
  4707. var trEdgePart = edgePart('top-right');
  4708. var redgePart = edgePart('right');
  4709. var brEdgePart = edgePart('bottom-right');
  4710. var bedgePart = edgePart('bottom');
  4711. var blEdgePart = edgePart('bottom-left');
  4712. var ledgePart = edgePart('left');
  4713. var thumbPart = required({
  4714. name: 'thumb',
  4715. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  4716. overrides: function (detail) {
  4717. return {
  4718. events: derive([
  4719. redirectToPart(touchstart(), detail, 'spectrum'),
  4720. redirectToPart(touchmove(), detail, 'spectrum'),
  4721. redirectToPart(touchend(), detail, 'spectrum'),
  4722. redirectToPart(mousedown(), detail, 'spectrum'),
  4723. redirectToPart(mousemove(), detail, 'spectrum'),
  4724. redirectToPart(mouseup(), detail, 'spectrum')
  4725. ])
  4726. };
  4727. }
  4728. });
  4729. var spectrumPart = required({
  4730. schema: [state$1('mouseIsDown', function () {
  4731. return Cell(false);
  4732. })],
  4733. name: 'spectrum',
  4734. overrides: function (detail) {
  4735. var modelDetail = detail.model;
  4736. var model = modelDetail.manager;
  4737. var setValueFrom = function (component, simulatedEvent) {
  4738. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  4739. return model.setValueFrom(component, detail, value);
  4740. });
  4741. };
  4742. return {
  4743. behaviours: derive$1([
  4744. Keying.config({
  4745. mode: 'special',
  4746. onLeft: function (spectrum) {
  4747. return model.onLeft(spectrum, detail);
  4748. },
  4749. onRight: function (spectrum) {
  4750. return model.onRight(spectrum, detail);
  4751. },
  4752. onUp: function (spectrum) {
  4753. return model.onUp(spectrum, detail);
  4754. },
  4755. onDown: function (spectrum) {
  4756. return model.onDown(spectrum, detail);
  4757. }
  4758. }),
  4759. Focusing.config({})
  4760. ]),
  4761. events: derive([
  4762. run(touchstart(), setValueFrom),
  4763. run(touchmove(), setValueFrom),
  4764. run(mousedown(), setValueFrom),
  4765. run(mousemove(), function (spectrum, se) {
  4766. if (detail.mouseIsDown.get()) {
  4767. setValueFrom(spectrum, se);
  4768. }
  4769. })
  4770. ])
  4771. };
  4772. }
  4773. });
  4774. var SliderParts = [
  4775. labelPart,
  4776. ledgePart,
  4777. redgePart,
  4778. tedgePart,
  4779. bedgePart,
  4780. tlEdgePart,
  4781. trEdgePart,
  4782. blEdgePart,
  4783. brEdgePart,
  4784. thumbPart,
  4785. spectrumPart
  4786. ];
  4787. var onLoad$1 = function (component, repConfig, repState) {
  4788. repConfig.store.manager.onLoad(component, repConfig, repState);
  4789. };
  4790. var onUnload = function (component, repConfig, repState) {
  4791. repConfig.store.manager.onUnload(component, repConfig, repState);
  4792. };
  4793. var setValue = function (component, repConfig, repState, data) {
  4794. repConfig.store.manager.setValue(component, repConfig, repState, data);
  4795. };
  4796. var getValue = function (component, repConfig, repState) {
  4797. return repConfig.store.manager.getValue(component, repConfig, repState);
  4798. };
  4799. var getState = function (component, repConfig, repState) {
  4800. return repState;
  4801. };
  4802. var RepresentApis = /*#__PURE__*/Object.freeze({
  4803. __proto__: null,
  4804. onLoad: onLoad$1,
  4805. onUnload: onUnload,
  4806. setValue: setValue,
  4807. getValue: getValue,
  4808. getState: getState
  4809. });
  4810. var events$5 = function (repConfig, repState) {
  4811. var es = repConfig.resetOnDom ? [
  4812. runOnAttached(function (comp, _se) {
  4813. onLoad$1(comp, repConfig, repState);
  4814. }),
  4815. runOnDetached(function (comp, _se) {
  4816. onUnload(comp, repConfig, repState);
  4817. })
  4818. ] : [loadEvent(repConfig, repState, onLoad$1)];
  4819. return derive(es);
  4820. };
  4821. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  4822. __proto__: null,
  4823. events: events$5
  4824. });
  4825. var memory = function () {
  4826. var data = Cell(null);
  4827. var readState = function () {
  4828. return {
  4829. mode: 'memory',
  4830. value: data.get()
  4831. };
  4832. };
  4833. var isNotSet = function () {
  4834. return data.get() === null;
  4835. };
  4836. var clear = function () {
  4837. data.set(null);
  4838. };
  4839. return nu$6({
  4840. set: data.set,
  4841. get: data.get,
  4842. isNotSet: isNotSet,
  4843. clear: clear,
  4844. readState: readState
  4845. });
  4846. };
  4847. var manual = function () {
  4848. var readState = function () {
  4849. };
  4850. return nu$6({ readState: readState });
  4851. };
  4852. var dataset = function () {
  4853. var dataByValue = Cell({});
  4854. var dataByText = Cell({});
  4855. var readState = function () {
  4856. return {
  4857. mode: 'dataset',
  4858. dataByValue: dataByValue.get(),
  4859. dataByText: dataByText.get()
  4860. };
  4861. };
  4862. var clear = function () {
  4863. dataByValue.set({});
  4864. dataByText.set({});
  4865. };
  4866. var lookup = function (itemString) {
  4867. return get(dataByValue.get(), itemString).orThunk(function () {
  4868. return get(dataByText.get(), itemString);
  4869. });
  4870. };
  4871. var update = function (items) {
  4872. var currentDataByValue = dataByValue.get();
  4873. var currentDataByText = dataByText.get();
  4874. var newDataByValue = {};
  4875. var newDataByText = {};
  4876. each$1(items, function (item) {
  4877. newDataByValue[item.value] = item;
  4878. get(item, 'meta').each(function (meta) {
  4879. get(meta, 'text').each(function (text) {
  4880. newDataByText[text] = item;
  4881. });
  4882. });
  4883. });
  4884. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  4885. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  4886. };
  4887. return nu$6({
  4888. readState: readState,
  4889. lookup: lookup,
  4890. update: update,
  4891. clear: clear
  4892. });
  4893. };
  4894. var init$1 = function (spec) {
  4895. return spec.store.manager.state(spec);
  4896. };
  4897. var RepresentState = /*#__PURE__*/Object.freeze({
  4898. __proto__: null,
  4899. memory: memory,
  4900. dataset: dataset,
  4901. manual: manual,
  4902. init: init$1
  4903. });
  4904. var setValue$1 = function (component, repConfig, repState, data) {
  4905. var store = repConfig.store;
  4906. repState.update([data]);
  4907. store.setValue(component, data);
  4908. repConfig.onSetValue(component, data);
  4909. };
  4910. var getValue$1 = function (component, repConfig, repState) {
  4911. var store = repConfig.store;
  4912. var key = store.getDataKey(component);
  4913. return repState.lookup(key).fold(function () {
  4914. return store.getFallbackEntry(key);
  4915. }, function (data) {
  4916. return data;
  4917. });
  4918. };
  4919. var onLoad$2 = function (component, repConfig, repState) {
  4920. var store = repConfig.store;
  4921. store.initialValue.each(function (data) {
  4922. setValue$1(component, repConfig, repState, data);
  4923. });
  4924. };
  4925. var onUnload$1 = function (component, repConfig, repState) {
  4926. repState.clear();
  4927. };
  4928. var DatasetStore = [
  4929. option('initialValue'),
  4930. strict$1('getFallbackEntry'),
  4931. strict$1('getDataKey'),
  4932. strict$1('setValue'),
  4933. output('manager', {
  4934. setValue: setValue$1,
  4935. getValue: getValue$1,
  4936. onLoad: onLoad$2,
  4937. onUnload: onUnload$1,
  4938. state: dataset
  4939. })
  4940. ];
  4941. var getValue$2 = function (component, repConfig, _repState) {
  4942. return repConfig.store.getValue(component);
  4943. };
  4944. var setValue$2 = function (component, repConfig, _repState, data) {
  4945. repConfig.store.setValue(component, data);
  4946. repConfig.onSetValue(component, data);
  4947. };
  4948. var onLoad$3 = function (component, repConfig, _repState) {
  4949. repConfig.store.initialValue.each(function (data) {
  4950. repConfig.store.setValue(component, data);
  4951. });
  4952. };
  4953. var ManualStore = [
  4954. strict$1('getValue'),
  4955. defaulted$1('setValue', noop),
  4956. option('initialValue'),
  4957. output('manager', {
  4958. setValue: setValue$2,
  4959. getValue: getValue$2,
  4960. onLoad: onLoad$3,
  4961. onUnload: noop,
  4962. state: NoState.init
  4963. })
  4964. ];
  4965. var setValue$3 = function (component, repConfig, repState, data) {
  4966. repState.set(data);
  4967. repConfig.onSetValue(component, data);
  4968. };
  4969. var getValue$3 = function (component, repConfig, repState) {
  4970. return repState.get();
  4971. };
  4972. var onLoad$4 = function (component, repConfig, repState) {
  4973. repConfig.store.initialValue.each(function (initVal) {
  4974. if (repState.isNotSet()) {
  4975. repState.set(initVal);
  4976. }
  4977. });
  4978. };
  4979. var onUnload$2 = function (component, repConfig, repState) {
  4980. repState.clear();
  4981. };
  4982. var MemoryStore = [
  4983. option('initialValue'),
  4984. output('manager', {
  4985. setValue: setValue$3,
  4986. getValue: getValue$3,
  4987. onLoad: onLoad$4,
  4988. onUnload: onUnload$2,
  4989. state: memory
  4990. })
  4991. ];
  4992. var RepresentSchema = [
  4993. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  4994. memory: MemoryStore,
  4995. manual: ManualStore,
  4996. dataset: DatasetStore
  4997. })),
  4998. onHandler('onSetValue'),
  4999. defaulted$1('resetOnDom', false)
  5000. ];
  5001. var Representing = create$1({
  5002. fields: RepresentSchema,
  5003. name: 'representing',
  5004. active: ActiveRepresenting,
  5005. apis: RepresentApis,
  5006. extra: {
  5007. setValueFrom: function (component, source) {
  5008. var value = Representing.getValue(source);
  5009. Representing.setValue(component, value);
  5010. }
  5011. },
  5012. state: RepresentState
  5013. });
  5014. var api$1 = Dimension('width', function (element) {
  5015. return element.dom().offsetWidth;
  5016. });
  5017. var set$4 = function (element, h) {
  5018. return api$1.set(element, h);
  5019. };
  5020. var get$7 = function (element) {
  5021. return api$1.get(element);
  5022. };
  5023. var r = function (left, top) {
  5024. var translate = function (x, y) {
  5025. return r(left + x, top + y);
  5026. };
  5027. return {
  5028. left: constant(left),
  5029. top: constant(top),
  5030. translate: translate
  5031. };
  5032. };
  5033. var Position = r;
  5034. var _sliderChangeEvent = 'slider.change.value';
  5035. var sliderChangeEvent = constant(_sliderChangeEvent);
  5036. var isTouchEvent = function (evt) {
  5037. return evt.type.indexOf('touch') !== -1;
  5038. };
  5039. var getEventSource = function (simulatedEvent) {
  5040. var evt = simulatedEvent.event().raw();
  5041. if (isTouchEvent(evt)) {
  5042. var touchEvent = evt;
  5043. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  5044. return Position(t.clientX, t.clientY);
  5045. }) : Option.none();
  5046. } else {
  5047. var mouseEvent = evt;
  5048. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  5049. return Position(me.clientX, me.clientY);
  5050. }) : Option.none();
  5051. }
  5052. };
  5053. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  5054. var minX = function (detail) {
  5055. return detail.model.minX;
  5056. };
  5057. var minY = function (detail) {
  5058. return detail.model.minY;
  5059. };
  5060. var min1X = function (detail) {
  5061. return detail.model.minX - 1;
  5062. };
  5063. var min1Y = function (detail) {
  5064. return detail.model.minY - 1;
  5065. };
  5066. var maxX = function (detail) {
  5067. return detail.model.maxX;
  5068. };
  5069. var maxY = function (detail) {
  5070. return detail.model.maxY;
  5071. };
  5072. var max1X = function (detail) {
  5073. return detail.model.maxX + 1;
  5074. };
  5075. var max1Y = function (detail) {
  5076. return detail.model.maxY + 1;
  5077. };
  5078. var range = function (detail, max, min) {
  5079. return max(detail) - min(detail);
  5080. };
  5081. var xRange = function (detail) {
  5082. return range(detail, maxX, minX);
  5083. };
  5084. var yRange = function (detail) {
  5085. return range(detail, maxY, minY);
  5086. };
  5087. var halfX = function (detail) {
  5088. return xRange(detail) / 2;
  5089. };
  5090. var halfY = function (detail) {
  5091. return yRange(detail) / 2;
  5092. };
  5093. var step = function (detail) {
  5094. return detail.stepSize;
  5095. };
  5096. var snap = function (detail) {
  5097. return detail.snapToGrid;
  5098. };
  5099. var snapStart = function (detail) {
  5100. return detail.snapStart;
  5101. };
  5102. var rounded = function (detail) {
  5103. return detail.rounded;
  5104. };
  5105. var hasEdge = function (detail, edgeName) {
  5106. return detail[edgeName + '-edge'] !== undefined;
  5107. };
  5108. var hasLEdge = function (detail) {
  5109. return hasEdge(detail, l);
  5110. };
  5111. var hasREdge = function (detail) {
  5112. return hasEdge(detail, r$1);
  5113. };
  5114. var hasTEdge = function (detail) {
  5115. return hasEdge(detail, t);
  5116. };
  5117. var hasBEdge = function (detail) {
  5118. return hasEdge(detail, b);
  5119. };
  5120. var currentValue = function (detail) {
  5121. return detail.model.value.get();
  5122. };
  5123. var xValue = function (x) {
  5124. return { x: constant(x) };
  5125. };
  5126. var yValue = function (y) {
  5127. return { y: constant(y) };
  5128. };
  5129. var xyValue = function (x, y) {
  5130. return {
  5131. x: constant(x),
  5132. y: constant(y)
  5133. };
  5134. };
  5135. var fireSliderChange = function (component, value) {
  5136. emitWith(component, sliderChangeEvent(), { value: value });
  5137. };
  5138. var setToTLEdgeXY = function (edge, detail) {
  5139. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  5140. };
  5141. var setToTEdge = function (edge, detail) {
  5142. fireSliderChange(edge, yValue(min1Y(detail)));
  5143. };
  5144. var setToTEdgeXY = function (edge, detail) {
  5145. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  5146. };
  5147. var setToTREdgeXY = function (edge, detail) {
  5148. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  5149. };
  5150. var setToREdge = function (edge, detail) {
  5151. fireSliderChange(edge, xValue(max1X(detail)));
  5152. };
  5153. var setToREdgeXY = function (edge, detail) {
  5154. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  5155. };
  5156. var setToBREdgeXY = function (edge, detail) {
  5157. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  5158. };
  5159. var setToBEdge = function (edge, detail) {
  5160. fireSliderChange(edge, yValue(max1Y(detail)));
  5161. };
  5162. var setToBEdgeXY = function (edge, detail) {
  5163. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  5164. };
  5165. var setToBLEdgeXY = function (edge, detail) {
  5166. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  5167. };
  5168. var setToLEdge = function (edge, detail) {
  5169. fireSliderChange(edge, xValue(min1X(detail)));
  5170. };
  5171. var setToLEdgeXY = function (edge, detail) {
  5172. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  5173. };
  5174. var reduceBy = function (value, min, max, step) {
  5175. if (value < min) {
  5176. return value;
  5177. } else if (value > max) {
  5178. return max;
  5179. } else if (value === min) {
  5180. return min - 1;
  5181. } else {
  5182. return Math.max(min, value - step);
  5183. }
  5184. };
  5185. var increaseBy = function (value, min, max, step) {
  5186. if (value > max) {
  5187. return value;
  5188. } else if (value < min) {
  5189. return min;
  5190. } else if (value === max) {
  5191. return max + 1;
  5192. } else {
  5193. return Math.min(max, value + step);
  5194. }
  5195. };
  5196. var capValue = function (value, min, max) {
  5197. return Math.max(min, Math.min(max, value));
  5198. };
  5199. var snapValueOf = function (value, min, max, step, snapStart) {
  5200. return snapStart.fold(function () {
  5201. var initValue = value - min;
  5202. var extraValue = Math.round(initValue / step) * step;
  5203. return capValue(min + extraValue, min - 1, max + 1);
  5204. }, function (start) {
  5205. var remainder = (value - start) % step;
  5206. var adjustment = Math.round(remainder / step);
  5207. var rawSteps = Math.floor((value - start) / step);
  5208. var maxSteps = Math.floor((max - start) / step);
  5209. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5210. var r = start + numSteps * step;
  5211. return Math.max(start, r);
  5212. });
  5213. };
  5214. var findOffsetOf = function (value, min, max) {
  5215. return Math.min(max, Math.max(value, min)) - min;
  5216. };
  5217. var findValueOf = function (args) {
  5218. 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;
  5219. var capMin = hasMinEdge ? min - 1 : min;
  5220. var capMax = hasMaxEdge ? max + 1 : max;
  5221. if (value < minBound) {
  5222. return capMin;
  5223. } else if (value > maxBound) {
  5224. return capMax;
  5225. } else {
  5226. var offset = findOffsetOf(value, minBound, maxBound);
  5227. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5228. if (snap && newValue >= min && newValue <= max) {
  5229. return snapValueOf(newValue, min, max, step, snapStart);
  5230. } else if (rounded) {
  5231. return Math.round(newValue);
  5232. } else {
  5233. return newValue;
  5234. }
  5235. }
  5236. };
  5237. var findOffsetOfValue = function (args) {
  5238. 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;
  5239. if (value < min) {
  5240. return hasMinEdge ? 0 : centerMinEdge;
  5241. } else if (value > max) {
  5242. return hasMaxEdge ? maxBound : centerMaxEdge;
  5243. } else {
  5244. return (value - min) / range * maxOffset;
  5245. }
  5246. };
  5247. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5248. var getBounds = function (component) {
  5249. return component.element().dom().getBoundingClientRect();
  5250. };
  5251. var getBoundsProperty = function (bounds, property) {
  5252. return bounds[property];
  5253. };
  5254. var getMinXBounds = function (component) {
  5255. var bounds = getBounds(component);
  5256. return getBoundsProperty(bounds, left);
  5257. };
  5258. var getMaxXBounds = function (component) {
  5259. var bounds = getBounds(component);
  5260. return getBoundsProperty(bounds, right);
  5261. };
  5262. var getMinYBounds = function (component) {
  5263. var bounds = getBounds(component);
  5264. return getBoundsProperty(bounds, top);
  5265. };
  5266. var getMaxYBounds = function (component) {
  5267. var bounds = getBounds(component);
  5268. return getBoundsProperty(bounds, bottom);
  5269. };
  5270. var getXScreenRange = function (component) {
  5271. var bounds = getBounds(component);
  5272. return getBoundsProperty(bounds, width);
  5273. };
  5274. var getYScreenRange = function (component) {
  5275. var bounds = getBounds(component);
  5276. return getBoundsProperty(bounds, height);
  5277. };
  5278. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5279. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5280. };
  5281. var getXCenterOffSetOf = function (component, spectrum) {
  5282. var componentBounds = getBounds(component);
  5283. var spectrumBounds = getBounds(spectrum);
  5284. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5285. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5286. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5287. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5288. };
  5289. var getYCenterOffSetOf = function (component, spectrum) {
  5290. var componentBounds = getBounds(component);
  5291. var spectrumBounds = getBounds(spectrum);
  5292. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5293. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5294. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5295. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5296. };
  5297. var fireSliderChange$1 = function (spectrum, value) {
  5298. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5299. };
  5300. var sliderValue = function (x) {
  5301. return { x: constant(x) };
  5302. };
  5303. var findValueOfOffset = function (spectrum, detail, left) {
  5304. var args = {
  5305. min: minX(detail),
  5306. max: maxX(detail),
  5307. range: xRange(detail),
  5308. value: left,
  5309. step: step(detail),
  5310. snap: snap(detail),
  5311. snapStart: snapStart(detail),
  5312. rounded: rounded(detail),
  5313. hasMinEdge: hasLEdge(detail),
  5314. hasMaxEdge: hasREdge(detail),
  5315. minBound: getMinXBounds(spectrum),
  5316. maxBound: getMaxXBounds(spectrum),
  5317. screenRange: getXScreenRange(spectrum)
  5318. };
  5319. return findValueOf(args);
  5320. };
  5321. var setValueFrom = function (spectrum, detail, value) {
  5322. var xValue = findValueOfOffset(spectrum, detail, value);
  5323. var sliderVal = sliderValue(xValue);
  5324. fireSliderChange$1(spectrum, sliderVal);
  5325. return xValue;
  5326. };
  5327. var setToMin = function (spectrum, detail) {
  5328. var min = minX(detail);
  5329. fireSliderChange$1(spectrum, sliderValue(min));
  5330. };
  5331. var setToMax = function (spectrum, detail) {
  5332. var max = maxX(detail);
  5333. fireSliderChange$1(spectrum, sliderValue(max));
  5334. };
  5335. var moveBy = function (direction, spectrum, detail) {
  5336. var f = direction > 0 ? increaseBy : reduceBy;
  5337. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  5338. fireSliderChange$1(spectrum, sliderValue(xValue));
  5339. return Option.some(xValue);
  5340. };
  5341. var handleMovement = function (direction) {
  5342. return function (spectrum, detail) {
  5343. return moveBy(direction, spectrum, detail).map(function () {
  5344. return true;
  5345. });
  5346. };
  5347. };
  5348. var getValueFromEvent = function (simulatedEvent) {
  5349. var pos = getEventSource(simulatedEvent);
  5350. return pos.map(function (p) {
  5351. return p.left();
  5352. });
  5353. };
  5354. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5355. var minOffset = 0;
  5356. var maxOffset = getXScreenRange(spectrum);
  5357. var centerMinEdge = minEdge.bind(function (edge) {
  5358. return Option.some(getXCenterOffSetOf(edge, spectrum));
  5359. }).getOr(minOffset);
  5360. var centerMaxEdge = maxEdge.bind(function (edge) {
  5361. return Option.some(getXCenterOffSetOf(edge, spectrum));
  5362. }).getOr(maxOffset);
  5363. var args = {
  5364. min: minX(detail),
  5365. max: maxX(detail),
  5366. range: xRange(detail),
  5367. value: value,
  5368. hasMinEdge: hasLEdge(detail),
  5369. hasMaxEdge: hasREdge(detail),
  5370. minBound: getMinXBounds(spectrum),
  5371. minOffset: minOffset,
  5372. maxBound: getMaxXBounds(spectrum),
  5373. maxOffset: maxOffset,
  5374. centerMinEdge: centerMinEdge,
  5375. centerMaxEdge: centerMaxEdge
  5376. };
  5377. return findOffsetOfValue(args);
  5378. };
  5379. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5380. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5381. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5382. };
  5383. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5384. var value = currentValue(detail);
  5385. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5386. var thumbRadius = get$7(thumb.element()) / 2;
  5387. set$3(thumb.element(), 'left', pos - thumbRadius + 'px');
  5388. };
  5389. var onLeft = handleMovement(-1);
  5390. var onRight = handleMovement(1);
  5391. var onUp = Option.none;
  5392. var onDown = Option.none;
  5393. var edgeActions = {
  5394. 'top-left': Option.none(),
  5395. 'top': Option.none(),
  5396. 'top-right': Option.none(),
  5397. 'right': Option.some(setToREdge),
  5398. 'bottom-right': Option.none(),
  5399. 'bottom': Option.none(),
  5400. 'bottom-left': Option.none(),
  5401. 'left': Option.some(setToLEdge)
  5402. };
  5403. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5404. __proto__: null,
  5405. setValueFrom: setValueFrom,
  5406. setToMin: setToMin,
  5407. setToMax: setToMax,
  5408. findValueOfOffset: findValueOfOffset,
  5409. getValueFromEvent: getValueFromEvent,
  5410. findPositionOfValue: findPositionOfValue,
  5411. setPositionFromValue: setPositionFromValue,
  5412. onLeft: onLeft,
  5413. onRight: onRight,
  5414. onUp: onUp,
  5415. onDown: onDown,
  5416. edgeActions: edgeActions
  5417. });
  5418. var fireSliderChange$2 = function (spectrum, value) {
  5419. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5420. };
  5421. var sliderValue$1 = function (y) {
  5422. return { y: constant(y) };
  5423. };
  5424. var findValueOfOffset$1 = function (spectrum, detail, top) {
  5425. var args = {
  5426. min: minY(detail),
  5427. max: maxY(detail),
  5428. range: yRange(detail),
  5429. value: top,
  5430. step: step(detail),
  5431. snap: snap(detail),
  5432. snapStart: snapStart(detail),
  5433. rounded: rounded(detail),
  5434. hasMinEdge: hasTEdge(detail),
  5435. hasMaxEdge: hasBEdge(detail),
  5436. minBound: getMinYBounds(spectrum),
  5437. maxBound: getMaxYBounds(spectrum),
  5438. screenRange: getYScreenRange(spectrum)
  5439. };
  5440. return findValueOf(args);
  5441. };
  5442. var setValueFrom$1 = function (spectrum, detail, value) {
  5443. var yValue = findValueOfOffset$1(spectrum, detail, value);
  5444. var sliderVal = sliderValue$1(yValue);
  5445. fireSliderChange$2(spectrum, sliderVal);
  5446. return yValue;
  5447. };
  5448. var setToMin$1 = function (spectrum, detail) {
  5449. var min = minY(detail);
  5450. fireSliderChange$2(spectrum, sliderValue$1(min));
  5451. };
  5452. var setToMax$1 = function (spectrum, detail) {
  5453. var max = maxY(detail);
  5454. fireSliderChange$2(spectrum, sliderValue$1(max));
  5455. };
  5456. var moveBy$1 = function (direction, spectrum, detail) {
  5457. var f = direction > 0 ? increaseBy : reduceBy;
  5458. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  5459. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  5460. return Option.some(yValue);
  5461. };
  5462. var handleMovement$1 = function (direction) {
  5463. return function (spectrum, detail) {
  5464. return moveBy$1(direction, spectrum, detail).map(function () {
  5465. return true;
  5466. });
  5467. };
  5468. };
  5469. var getValueFromEvent$1 = function (simulatedEvent) {
  5470. var pos = getEventSource(simulatedEvent);
  5471. return pos.map(function (p) {
  5472. return p.top();
  5473. });
  5474. };
  5475. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  5476. var minOffset = 0;
  5477. var maxOffset = getYScreenRange(spectrum);
  5478. var centerMinEdge = minEdge.bind(function (edge) {
  5479. return Option.some(getYCenterOffSetOf(edge, spectrum));
  5480. }).getOr(minOffset);
  5481. var centerMaxEdge = maxEdge.bind(function (edge) {
  5482. return Option.some(getYCenterOffSetOf(edge, spectrum));
  5483. }).getOr(maxOffset);
  5484. var args = {
  5485. min: minY(detail),
  5486. max: maxY(detail),
  5487. range: yRange(detail),
  5488. value: value,
  5489. hasMinEdge: hasTEdge(detail),
  5490. hasMaxEdge: hasBEdge(detail),
  5491. minBound: getMinYBounds(spectrum),
  5492. minOffset: minOffset,
  5493. maxBound: getMaxYBounds(spectrum),
  5494. maxOffset: maxOffset,
  5495. centerMinEdge: centerMinEdge,
  5496. centerMaxEdge: centerMaxEdge
  5497. };
  5498. return findOffsetOfValue(args);
  5499. };
  5500. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5501. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  5502. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5503. };
  5504. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5505. var value = currentValue(detail);
  5506. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5507. var thumbRadius = get$5(thumb.element()) / 2;
  5508. set$3(thumb.element(), 'top', pos - thumbRadius + 'px');
  5509. };
  5510. var onLeft$1 = Option.none;
  5511. var onRight$1 = Option.none;
  5512. var onUp$1 = handleMovement$1(-1);
  5513. var onDown$1 = handleMovement$1(1);
  5514. var edgeActions$1 = {
  5515. 'top-left': Option.none(),
  5516. 'top': Option.some(setToTEdge),
  5517. 'top-right': Option.none(),
  5518. 'right': Option.none(),
  5519. 'bottom-right': Option.none(),
  5520. 'bottom': Option.some(setToBEdge),
  5521. 'bottom-left': Option.none(),
  5522. 'left': Option.none()
  5523. };
  5524. var VerticalModel = /*#__PURE__*/Object.freeze({
  5525. __proto__: null,
  5526. setValueFrom: setValueFrom$1,
  5527. setToMin: setToMin$1,
  5528. setToMax: setToMax$1,
  5529. findValueOfOffset: findValueOfOffset$1,
  5530. getValueFromEvent: getValueFromEvent$1,
  5531. findPositionOfValue: findPositionOfValue$1,
  5532. setPositionFromValue: setPositionFromValue$1,
  5533. onLeft: onLeft$1,
  5534. onRight: onRight$1,
  5535. onUp: onUp$1,
  5536. onDown: onDown$1,
  5537. edgeActions: edgeActions$1
  5538. });
  5539. var fireSliderChange$3 = function (spectrum, value) {
  5540. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5541. };
  5542. var sliderValue$2 = function (x, y) {
  5543. return {
  5544. x: constant(x),
  5545. y: constant(y)
  5546. };
  5547. };
  5548. var setValueFrom$2 = function (spectrum, detail, value) {
  5549. var xValue = findValueOfOffset(spectrum, detail, value.left());
  5550. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  5551. var val = sliderValue$2(xValue, yValue);
  5552. fireSliderChange$3(spectrum, val);
  5553. return val;
  5554. };
  5555. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  5556. var f = direction > 0 ? increaseBy : reduceBy;
  5557. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  5558. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  5559. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  5560. return Option.some(xValue);
  5561. };
  5562. var handleMovement$2 = function (direction, isVerticalMovement) {
  5563. return function (spectrum, detail) {
  5564. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  5565. return true;
  5566. });
  5567. };
  5568. };
  5569. var setToMin$2 = function (spectrum, detail) {
  5570. var mX = minX(detail);
  5571. var mY = minY(detail);
  5572. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5573. };
  5574. var setToMax$2 = function (spectrum, detail) {
  5575. var mX = maxX(detail);
  5576. var mY = maxY(detail);
  5577. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5578. };
  5579. var getValueFromEvent$2 = function (simulatedEvent) {
  5580. return getEventSource(simulatedEvent);
  5581. };
  5582. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5583. var value = currentValue(detail);
  5584. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5585. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5586. var thumbXRadius = get$7(thumb.element()) / 2;
  5587. var thumbYRadius = get$5(thumb.element()) / 2;
  5588. set$3(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  5589. set$3(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  5590. };
  5591. var onLeft$2 = handleMovement$2(-1, false);
  5592. var onRight$2 = handleMovement$2(1, false);
  5593. var onUp$2 = handleMovement$2(-1, true);
  5594. var onDown$2 = handleMovement$2(1, true);
  5595. var edgeActions$2 = {
  5596. 'top-left': Option.some(setToTLEdgeXY),
  5597. 'top': Option.some(setToTEdgeXY),
  5598. 'top-right': Option.some(setToTREdgeXY),
  5599. 'right': Option.some(setToREdgeXY),
  5600. 'bottom-right': Option.some(setToBREdgeXY),
  5601. 'bottom': Option.some(setToBEdgeXY),
  5602. 'bottom-left': Option.some(setToBLEdgeXY),
  5603. 'left': Option.some(setToLEdgeXY)
  5604. };
  5605. var TwoDModel = /*#__PURE__*/Object.freeze({
  5606. __proto__: null,
  5607. setValueFrom: setValueFrom$2,
  5608. setToMin: setToMin$2,
  5609. setToMax: setToMax$2,
  5610. getValueFromEvent: getValueFromEvent$2,
  5611. setPositionFromValue: setPositionFromValue$2,
  5612. onLeft: onLeft$2,
  5613. onRight: onRight$2,
  5614. onUp: onUp$2,
  5615. onDown: onDown$2,
  5616. edgeActions: edgeActions$2
  5617. });
  5618. var SliderSchema = [
  5619. defaulted$1('stepSize', 1),
  5620. defaulted$1('onChange', noop),
  5621. defaulted$1('onChoose', noop),
  5622. defaulted$1('onInit', noop),
  5623. defaulted$1('onDragStart', noop),
  5624. defaulted$1('onDragEnd', noop),
  5625. defaulted$1('snapToGrid', false),
  5626. defaulted$1('rounded', true),
  5627. option('snapStart'),
  5628. strictOf('model', choose$1('mode', {
  5629. x: [
  5630. defaulted$1('minX', 0),
  5631. defaulted$1('maxX', 100),
  5632. state$1('value', function (spec) {
  5633. return Cell(spec.mode.minX);
  5634. }),
  5635. strict$1('getInitialValue'),
  5636. output('manager', HorizontalModel)
  5637. ],
  5638. y: [
  5639. defaulted$1('minY', 0),
  5640. defaulted$1('maxY', 100),
  5641. state$1('value', function (spec) {
  5642. return Cell(spec.mode.minY);
  5643. }),
  5644. strict$1('getInitialValue'),
  5645. output('manager', VerticalModel)
  5646. ],
  5647. xy: [
  5648. defaulted$1('minX', 0),
  5649. defaulted$1('maxX', 100),
  5650. defaulted$1('minY', 0),
  5651. defaulted$1('maxY', 100),
  5652. state$1('value', function (spec) {
  5653. return Cell({
  5654. x: constant(spec.mode.minX),
  5655. y: constant(spec.mode.minY)
  5656. });
  5657. }),
  5658. strict$1('getInitialValue'),
  5659. output('manager', TwoDModel)
  5660. ]
  5661. })),
  5662. field$1('sliderBehaviours', [
  5663. Keying,
  5664. Representing
  5665. ]),
  5666. state$1('mouseIsDown', function () {
  5667. return Cell(false);
  5668. })
  5669. ];
  5670. var mouseReleased = constant('mouse.released');
  5671. var sketch = function (detail, components, _spec, _externals) {
  5672. var _a;
  5673. var getThumb = function (component) {
  5674. return getPartOrDie(component, detail, 'thumb');
  5675. };
  5676. var getSpectrum = function (component) {
  5677. return getPartOrDie(component, detail, 'spectrum');
  5678. };
  5679. var getLeftEdge = function (component) {
  5680. return getPart(component, detail, 'left-edge');
  5681. };
  5682. var getRightEdge = function (component) {
  5683. return getPart(component, detail, 'right-edge');
  5684. };
  5685. var getTopEdge = function (component) {
  5686. return getPart(component, detail, 'top-edge');
  5687. };
  5688. var getBottomEdge = function (component) {
  5689. return getPart(component, detail, 'bottom-edge');
  5690. };
  5691. var modelDetail = detail.model;
  5692. var model = modelDetail.manager;
  5693. var refresh = function (slider, thumb) {
  5694. model.setPositionFromValue(slider, thumb, detail, {
  5695. getLeftEdge: getLeftEdge,
  5696. getRightEdge: getRightEdge,
  5697. getTopEdge: getTopEdge,
  5698. getBottomEdge: getBottomEdge,
  5699. getSpectrum: getSpectrum
  5700. });
  5701. };
  5702. var changeValue = function (slider, newValue) {
  5703. modelDetail.value.set(newValue);
  5704. var thumb = getThumb(slider);
  5705. refresh(slider, thumb);
  5706. detail.onChange(slider, thumb, newValue);
  5707. return Option.some(true);
  5708. };
  5709. var resetToMin = function (slider) {
  5710. model.setToMin(slider, detail);
  5711. };
  5712. var resetToMax = function (slider) {
  5713. model.setToMax(slider, detail);
  5714. };
  5715. var choose = function (slider) {
  5716. var fireOnChoose = function () {
  5717. getPart(slider, detail, 'thumb').each(function (thumb) {
  5718. var value = modelDetail.value.get();
  5719. detail.onChoose(slider, thumb, value);
  5720. });
  5721. };
  5722. var wasDown = detail.mouseIsDown.get();
  5723. detail.mouseIsDown.set(false);
  5724. if (wasDown) {
  5725. fireOnChoose();
  5726. }
  5727. };
  5728. var onDragStart = function (slider, simulatedEvent) {
  5729. simulatedEvent.stop();
  5730. detail.mouseIsDown.set(true);
  5731. detail.onDragStart(slider, getThumb(slider));
  5732. };
  5733. var onDragEnd = function (slider, simulatedEvent) {
  5734. simulatedEvent.stop();
  5735. detail.onDragEnd(slider, getThumb(slider));
  5736. choose(slider);
  5737. };
  5738. return {
  5739. uid: detail.uid,
  5740. dom: detail.dom,
  5741. components: components,
  5742. behaviours: augment(detail.sliderBehaviours, [
  5743. Keying.config({
  5744. mode: 'special',
  5745. focusIn: function (slider) {
  5746. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  5747. }
  5748. }),
  5749. Representing.config({
  5750. store: {
  5751. mode: 'manual',
  5752. getValue: function (_) {
  5753. return modelDetail.value.get();
  5754. }
  5755. }
  5756. }),
  5757. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  5758. ]),
  5759. events: derive([
  5760. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  5761. changeValue(slider, simulatedEvent.event().value());
  5762. }),
  5763. runOnAttached(function (slider, _simulatedEvent) {
  5764. var getInitial = modelDetail.getInitialValue();
  5765. modelDetail.value.set(getInitial);
  5766. var thumb = getThumb(slider);
  5767. refresh(slider, thumb);
  5768. var spectrum = getSpectrum(slider);
  5769. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  5770. }),
  5771. run(touchstart(), onDragStart),
  5772. run(touchend(), onDragEnd),
  5773. run(mousedown(), onDragStart),
  5774. run(mouseup(), onDragEnd)
  5775. ]),
  5776. apis: {
  5777. resetToMin: resetToMin,
  5778. resetToMax: resetToMax,
  5779. changeValue: changeValue,
  5780. refresh: refresh
  5781. },
  5782. domModification: { styles: { position: 'relative' } }
  5783. };
  5784. };
  5785. var Slider = composite$1({
  5786. name: 'Slider',
  5787. configFields: SliderSchema,
  5788. partFields: SliderParts,
  5789. factory: sketch,
  5790. apis: {
  5791. resetToMin: function (apis, slider) {
  5792. apis.resetToMin(slider);
  5793. },
  5794. resetToMax: function (apis, slider) {
  5795. apis.resetToMax(slider);
  5796. },
  5797. refresh: function (apis, slider) {
  5798. apis.refresh(slider);
  5799. }
  5800. }
  5801. });
  5802. var button = function (realm, clazz, makeItems, editor) {
  5803. return forToolbar(clazz, function () {
  5804. var items = makeItems();
  5805. realm.setContextToolbar([{
  5806. label: clazz + ' group',
  5807. items: items
  5808. }]);
  5809. }, {}, editor);
  5810. };
  5811. var BLACK = -1;
  5812. var makeSlider = function (spec$1) {
  5813. var getColor = function (hue) {
  5814. if (hue < 0) {
  5815. return 'black';
  5816. } else if (hue > 360) {
  5817. return 'white';
  5818. } else {
  5819. return 'hsl(' + hue + ', 100%, 50%)';
  5820. }
  5821. };
  5822. var onInit = function (slider, thumb, spectrum, value) {
  5823. var color = getColor(value.x());
  5824. set$3(thumb.element(), 'background-color', color);
  5825. };
  5826. var onChange = function (slider, thumb, value) {
  5827. var color = getColor(value.x());
  5828. set$3(thumb.element(), 'background-color', color);
  5829. spec$1.onChange(slider, thumb, color);
  5830. };
  5831. return Slider.sketch({
  5832. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  5833. components: [
  5834. Slider.parts()['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  5835. Slider.parts().spectrum({
  5836. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  5837. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  5838. behaviours: derive$1([Toggling.config({ toggleClass: resolve('thumb-active') })])
  5839. }),
  5840. Slider.parts()['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  5841. Slider.parts().thumb({
  5842. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  5843. behaviours: derive$1([Toggling.config({ toggleClass: resolve('thumb-active') })])
  5844. })
  5845. ],
  5846. onChange: onChange,
  5847. onDragStart: function (slider, thumb) {
  5848. Toggling.on(thumb);
  5849. },
  5850. onDragEnd: function (slider, thumb) {
  5851. Toggling.off(thumb);
  5852. },
  5853. onInit: onInit,
  5854. stepSize: 10,
  5855. model: {
  5856. mode: 'x',
  5857. minX: 0,
  5858. maxX: 360,
  5859. getInitialValue: function () {
  5860. return {
  5861. x: function () {
  5862. return spec$1.getInitialValue();
  5863. }
  5864. };
  5865. }
  5866. },
  5867. sliderBehaviours: derive$1([orientation(Slider.refresh)])
  5868. });
  5869. };
  5870. var makeItems = function (spec) {
  5871. return [makeSlider(spec)];
  5872. };
  5873. var sketch$1 = function (realm, editor) {
  5874. var spec = {
  5875. onChange: function (slider, thumb, color) {
  5876. editor.undoManager.transact(function () {
  5877. editor.formatter.apply('forecolor', { value: color });
  5878. editor.nodeChanged();
  5879. });
  5880. },
  5881. getInitialValue: function () {
  5882. return BLACK;
  5883. }
  5884. };
  5885. return button(realm, 'color-levels', function () {
  5886. return makeItems(spec);
  5887. }, editor);
  5888. };
  5889. var schema$7 = objOfOnly([
  5890. strict$1('getInitialValue'),
  5891. strict$1('onChange'),
  5892. strict$1('category'),
  5893. strict$1('sizes')
  5894. ]);
  5895. var sketch$2 = function (rawSpec) {
  5896. var spec$1 = asRawOrDie('SizeSlider', schema$7, rawSpec);
  5897. var isValidValue = function (valueIndex) {
  5898. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  5899. };
  5900. var onChange = function (slider, thumb, valueIndex) {
  5901. var index = valueIndex.x();
  5902. if (isValidValue(index)) {
  5903. spec$1.onChange(index);
  5904. }
  5905. };
  5906. return Slider.sketch({
  5907. dom: {
  5908. tag: 'div',
  5909. classes: [
  5910. resolve('slider-' + spec$1.category + '-size-container'),
  5911. resolve('slider'),
  5912. resolve('slider-size-container')
  5913. ]
  5914. },
  5915. onChange: onChange,
  5916. onDragStart: function (slider, thumb) {
  5917. Toggling.on(thumb);
  5918. },
  5919. onDragEnd: function (slider, thumb) {
  5920. Toggling.off(thumb);
  5921. },
  5922. model: {
  5923. mode: 'x',
  5924. minX: 0,
  5925. maxX: spec$1.sizes.length - 1,
  5926. getInitialValue: function () {
  5927. return {
  5928. x: function () {
  5929. return spec$1.getInitialValue();
  5930. }
  5931. };
  5932. }
  5933. },
  5934. stepSize: 1,
  5935. snapToGrid: true,
  5936. sliderBehaviours: derive$1([orientation(Slider.refresh)]),
  5937. components: [
  5938. Slider.parts().spectrum({
  5939. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  5940. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  5941. }),
  5942. Slider.parts().thumb({
  5943. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  5944. behaviours: derive$1([Toggling.config({ toggleClass: resolve('thumb-active') })])
  5945. })
  5946. ]
  5947. });
  5948. };
  5949. var candidatesArray = [
  5950. '9px',
  5951. '10px',
  5952. '11px',
  5953. '12px',
  5954. '14px',
  5955. '16px',
  5956. '18px',
  5957. '20px',
  5958. '24px',
  5959. '32px',
  5960. '36px'
  5961. ];
  5962. var defaultSize = 'medium';
  5963. var defaultIndex = 2;
  5964. var indexToSize = function (index) {
  5965. return Option.from(candidatesArray[index]);
  5966. };
  5967. var sizeToIndex = function (size) {
  5968. return findIndex(candidatesArray, function (v) {
  5969. return v === size;
  5970. });
  5971. };
  5972. var getRawOrComputed = function (isRoot, rawStart) {
  5973. var optStart = isElement(rawStart) ? Option.some(rawStart) : parent(rawStart).filter(isElement);
  5974. return optStart.map(function (start) {
  5975. var inline = closest$1(start, function (elem) {
  5976. return getRaw(elem, 'font-size').isSome();
  5977. }, isRoot).bind(function (elem) {
  5978. return getRaw(elem, 'font-size');
  5979. });
  5980. return inline.getOrThunk(function () {
  5981. return get$4(start, 'font-size');
  5982. });
  5983. }).getOr('');
  5984. };
  5985. var getSize = function (editor) {
  5986. var node = editor.selection.getStart();
  5987. var elem = Element.fromDom(node);
  5988. var root = Element.fromDom(editor.getBody());
  5989. var isRoot = function (e) {
  5990. return eq(root, e);
  5991. };
  5992. var elemSize = getRawOrComputed(isRoot, elem);
  5993. return find$2(candidatesArray, function (size) {
  5994. return elemSize === size;
  5995. }).getOr(defaultSize);
  5996. };
  5997. var applySize = function (editor, value) {
  5998. var currentValue = getSize(editor);
  5999. if (currentValue !== value) {
  6000. editor.execCommand('fontSize', false, value);
  6001. }
  6002. };
  6003. var get$8 = function (editor) {
  6004. var size = getSize(editor);
  6005. return sizeToIndex(size).getOr(defaultIndex);
  6006. };
  6007. var apply$1 = function (editor, index) {
  6008. indexToSize(index).each(function (size) {
  6009. applySize(editor, size);
  6010. });
  6011. };
  6012. var candidates = constant(candidatesArray);
  6013. var sizes = candidates();
  6014. var makeSlider$1 = function (spec) {
  6015. return sketch$2({
  6016. onChange: spec.onChange,
  6017. sizes: sizes,
  6018. category: 'font',
  6019. getInitialValue: spec.getInitialValue
  6020. });
  6021. };
  6022. var makeItems$1 = function (spec$1) {
  6023. return [
  6024. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6025. makeSlider$1(spec$1),
  6026. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6027. ];
  6028. };
  6029. var sketch$3 = function (realm, editor) {
  6030. var spec = {
  6031. onChange: function (value) {
  6032. apply$1(editor, value);
  6033. },
  6034. getInitialValue: function () {
  6035. return get$8(editor);
  6036. }
  6037. };
  6038. return button(realm, 'font-size', function () {
  6039. return makeItems$1(spec);
  6040. }, editor);
  6041. };
  6042. var record = function (spec) {
  6043. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$3('memento');
  6044. var get = function (anyInSystem) {
  6045. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6046. };
  6047. var getOpt = function (anyInSystem) {
  6048. return anyInSystem.getSystem().getByUid(uid).toOption();
  6049. };
  6050. var asSpec = function () {
  6051. return __assign(__assign({}, spec), { uid: uid });
  6052. };
  6053. return {
  6054. get: get,
  6055. getOpt: getOpt,
  6056. asSpec: asSpec
  6057. };
  6058. };
  6059. var promise = function () {
  6060. var Promise = function (fn) {
  6061. if (typeof this !== 'object') {
  6062. throw new TypeError('Promises must be constructed via new');
  6063. }
  6064. if (typeof fn !== 'function') {
  6065. throw new TypeError('not a function');
  6066. }
  6067. this._state = null;
  6068. this._value = null;
  6069. this._deferreds = [];
  6070. doResolve(fn, bind(resolve, this), bind(reject, this));
  6071. };
  6072. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  6073. domGlobals.setTimeout(fn, 1);
  6074. };
  6075. function bind(fn, thisArg) {
  6076. return function () {
  6077. return fn.apply(thisArg, arguments);
  6078. };
  6079. }
  6080. var isArray = Array.isArray || function (value) {
  6081. return Object.prototype.toString.call(value) === '[object Array]';
  6082. };
  6083. function handle(deferred) {
  6084. var me = this;
  6085. if (this._state === null) {
  6086. this._deferreds.push(deferred);
  6087. return;
  6088. }
  6089. asap(function () {
  6090. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  6091. if (cb === null) {
  6092. (me._state ? deferred.resolve : deferred.reject)(me._value);
  6093. return;
  6094. }
  6095. var ret;
  6096. try {
  6097. ret = cb(me._value);
  6098. } catch (e) {
  6099. deferred.reject(e);
  6100. return;
  6101. }
  6102. deferred.resolve(ret);
  6103. });
  6104. }
  6105. function resolve(newValue) {
  6106. try {
  6107. if (newValue === this) {
  6108. throw new TypeError('A promise cannot be resolved with itself.');
  6109. }
  6110. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6111. var then = newValue.then;
  6112. if (typeof then === 'function') {
  6113. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  6114. return;
  6115. }
  6116. }
  6117. this._state = true;
  6118. this._value = newValue;
  6119. finale.call(this);
  6120. } catch (e) {
  6121. reject.call(this, e);
  6122. }
  6123. }
  6124. function reject(newValue) {
  6125. this._state = false;
  6126. this._value = newValue;
  6127. finale.call(this);
  6128. }
  6129. function finale() {
  6130. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  6131. var deferred = _a[_i];
  6132. handle.call(this, deferred);
  6133. }
  6134. this._deferreds = [];
  6135. }
  6136. function Handler(onFulfilled, onRejected, resolve, reject) {
  6137. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6138. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6139. this.resolve = resolve;
  6140. this.reject = reject;
  6141. }
  6142. function doResolve(fn, onFulfilled, onRejected) {
  6143. var done = false;
  6144. try {
  6145. fn(function (value) {
  6146. if (done) {
  6147. return;
  6148. }
  6149. done = true;
  6150. onFulfilled(value);
  6151. }, function (reason) {
  6152. if (done) {
  6153. return;
  6154. }
  6155. done = true;
  6156. onRejected(reason);
  6157. });
  6158. } catch (ex) {
  6159. if (done) {
  6160. return;
  6161. }
  6162. done = true;
  6163. onRejected(ex);
  6164. }
  6165. }
  6166. Promise.prototype.catch = function (onRejected) {
  6167. return this.then(null, onRejected);
  6168. };
  6169. Promise.prototype.then = function (onFulfilled, onRejected) {
  6170. var me = this;
  6171. return new Promise(function (resolve, reject) {
  6172. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  6173. });
  6174. };
  6175. Promise.all = function () {
  6176. var values = [];
  6177. for (var _i = 0; _i < arguments.length; _i++) {
  6178. values[_i] = arguments[_i];
  6179. }
  6180. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  6181. return new Promise(function (resolve, reject) {
  6182. if (args.length === 0) {
  6183. return resolve([]);
  6184. }
  6185. var remaining = args.length;
  6186. function res(i, val) {
  6187. try {
  6188. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6189. var then = val.then;
  6190. if (typeof then === 'function') {
  6191. then.call(val, function (val) {
  6192. res(i, val);
  6193. }, reject);
  6194. return;
  6195. }
  6196. }
  6197. args[i] = val;
  6198. if (--remaining === 0) {
  6199. resolve(args);
  6200. }
  6201. } catch (ex) {
  6202. reject(ex);
  6203. }
  6204. }
  6205. for (var i = 0; i < args.length; i++) {
  6206. res(i, args[i]);
  6207. }
  6208. });
  6209. };
  6210. Promise.resolve = function (value) {
  6211. if (value && typeof value === 'object' && value.constructor === Promise) {
  6212. return value;
  6213. }
  6214. return new Promise(function (resolve) {
  6215. resolve(value);
  6216. });
  6217. };
  6218. Promise.reject = function (reason) {
  6219. return new Promise(function (resolve, reject) {
  6220. reject(reason);
  6221. });
  6222. };
  6223. Promise.race = function (values) {
  6224. return new Promise(function (resolve, reject) {
  6225. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  6226. var value = values_1[_i];
  6227. value.then(resolve, reject);
  6228. }
  6229. });
  6230. };
  6231. return Promise;
  6232. };
  6233. var Promise = window.Promise ? window.Promise : promise();
  6234. function blobToDataUri(blob) {
  6235. return new Promise(function (resolve) {
  6236. var reader = new domGlobals.FileReader();
  6237. reader.onloadend = function () {
  6238. resolve(reader.result);
  6239. };
  6240. reader.readAsDataURL(blob);
  6241. });
  6242. }
  6243. function blobToBase64(blob) {
  6244. return blobToDataUri(blob).then(function (dataUri) {
  6245. return dataUri.split(',')[1];
  6246. });
  6247. }
  6248. var blobToBase64$1 = function (blob) {
  6249. return blobToBase64(blob);
  6250. };
  6251. var addImage = function (editor, blob) {
  6252. blobToBase64$1(blob).then(function (base64) {
  6253. editor.undoManager.transact(function () {
  6254. var cache = editor.editorUpload.blobCache;
  6255. var info = cache.create(generate$1('mceu'), blob, base64);
  6256. cache.add(info);
  6257. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6258. editor.insertContent(img);
  6259. });
  6260. });
  6261. };
  6262. var extractBlob = function (simulatedEvent) {
  6263. var event = simulatedEvent.event();
  6264. var files = event.raw().target.files || event.raw().dataTransfer.files;
  6265. return Option.from(files[0]);
  6266. };
  6267. var sketch$4 = function (editor) {
  6268. var pickerDom = {
  6269. tag: 'input',
  6270. attributes: {
  6271. accept: 'image/*',
  6272. type: 'file',
  6273. title: ''
  6274. },
  6275. styles: {
  6276. visibility: 'hidden',
  6277. position: 'absolute'
  6278. }
  6279. };
  6280. var memPicker = record({
  6281. dom: pickerDom,
  6282. events: derive([
  6283. cutter(click()),
  6284. run(change(), function (picker, simulatedEvent) {
  6285. extractBlob(simulatedEvent).each(function (blob) {
  6286. addImage(editor, blob);
  6287. });
  6288. })
  6289. ])
  6290. });
  6291. return Button.sketch({
  6292. dom: getToolbarIconButton('image', editor),
  6293. components: [memPicker.asSpec()],
  6294. action: function (button) {
  6295. var picker = memPicker.get(button);
  6296. picker.element().dom().click();
  6297. }
  6298. });
  6299. };
  6300. var get$9 = function (element) {
  6301. return element.dom().textContent;
  6302. };
  6303. var set$5 = function (element, value) {
  6304. return element.dom().textContent = value;
  6305. };
  6306. var isNotEmpty = function (val) {
  6307. return val.length > 0;
  6308. };
  6309. var defaultToEmpty = function (str) {
  6310. return str === undefined || str === null ? '' : str;
  6311. };
  6312. var noLink = function (editor) {
  6313. var text = editor.selection.getContent({ format: 'text' });
  6314. return {
  6315. url: '',
  6316. text: text,
  6317. title: '',
  6318. target: '',
  6319. link: Option.none()
  6320. };
  6321. };
  6322. var fromLink = function (link) {
  6323. var text = get$9(link);
  6324. var url = get$1(link, 'href');
  6325. var title = get$1(link, 'title');
  6326. var target = get$1(link, 'target');
  6327. return {
  6328. url: defaultToEmpty(url),
  6329. text: text !== url ? defaultToEmpty(text) : '',
  6330. title: defaultToEmpty(title),
  6331. target: defaultToEmpty(target),
  6332. link: Option.some(link)
  6333. };
  6334. };
  6335. var getInfo = function (editor) {
  6336. return query(editor).fold(function () {
  6337. return noLink(editor);
  6338. }, function (link) {
  6339. return fromLink(link);
  6340. });
  6341. };
  6342. var wasSimple = function (link) {
  6343. var prevHref = get$1(link, 'href');
  6344. var prevText = get$9(link);
  6345. return prevHref === prevText;
  6346. };
  6347. var getTextToApply = function (link, url, info) {
  6348. return info.text.toOption().filter(isNotEmpty).fold(function () {
  6349. return wasSimple(link) ? Option.some(url) : Option.none();
  6350. }, Option.some);
  6351. };
  6352. var unlinkIfRequired = function (editor, info) {
  6353. var activeLink = info.link.bind(identity);
  6354. activeLink.each(function (_link) {
  6355. editor.execCommand('unlink');
  6356. });
  6357. };
  6358. var getAttrs$1 = function (url, info) {
  6359. var attrs = {};
  6360. attrs.href = url;
  6361. info.title.toOption().filter(isNotEmpty).each(function (title) {
  6362. attrs.title = title;
  6363. });
  6364. info.target.toOption().filter(isNotEmpty).each(function (target) {
  6365. attrs.target = target;
  6366. });
  6367. return attrs;
  6368. };
  6369. var applyInfo = function (editor, info) {
  6370. info.url.toOption().filter(isNotEmpty).fold(function () {
  6371. unlinkIfRequired(editor, info);
  6372. }, function (url) {
  6373. var attrs = getAttrs$1(url, info);
  6374. var activeLink = info.link.bind(identity);
  6375. activeLink.fold(function () {
  6376. var text = info.text.toOption().filter(isNotEmpty).getOr(url);
  6377. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6378. }, function (link) {
  6379. var text = getTextToApply(link, url, info);
  6380. setAll(link, attrs);
  6381. text.each(function (newText) {
  6382. set$5(link, newText);
  6383. });
  6384. });
  6385. });
  6386. };
  6387. var query = function (editor) {
  6388. var start = Element.fromDom(editor.selection.getStart());
  6389. return closest$2(start, 'a');
  6390. };
  6391. var platform$1 = detect$3();
  6392. var preserve = function (f, editor) {
  6393. var rng = editor.selection.getRng();
  6394. f();
  6395. editor.selection.setRng(rng);
  6396. };
  6397. var forAndroid = function (editor, f) {
  6398. var wrapper = platform$1.os.isAndroid() ? preserve : apply;
  6399. wrapper(f, editor);
  6400. };
  6401. var events$6 = function (name, eventHandlers) {
  6402. var events = derive(eventHandlers);
  6403. return create$1({
  6404. fields: [strict$1('enabled')],
  6405. name: name,
  6406. active: { events: constant(events) }
  6407. });
  6408. };
  6409. var config = function (name, eventHandlers) {
  6410. var me = events$6(name, eventHandlers);
  6411. return {
  6412. key: name,
  6413. value: {
  6414. config: {},
  6415. me: me,
  6416. configAsRaw: constant({}),
  6417. initialConfig: {},
  6418. state: NoState
  6419. }
  6420. };
  6421. };
  6422. var getCurrent = function (component, composeConfig, _composeState) {
  6423. return composeConfig.find(component);
  6424. };
  6425. var ComposeApis = /*#__PURE__*/Object.freeze({
  6426. __proto__: null,
  6427. getCurrent: getCurrent
  6428. });
  6429. var ComposeSchema = [strict$1('find')];
  6430. var Composing = create$1({
  6431. fields: ComposeSchema,
  6432. name: 'composing',
  6433. apis: ComposeApis
  6434. });
  6435. var factory$1 = function (detail) {
  6436. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6437. return {
  6438. uid: detail.uid,
  6439. dom: __assign({
  6440. tag: 'div',
  6441. attributes: __assign({ role: 'presentation' }, attributes)
  6442. }, domWithoutAttributes),
  6443. components: detail.components,
  6444. behaviours: get$6(detail.containerBehaviours),
  6445. events: detail.events,
  6446. domModification: detail.domModification,
  6447. eventOrder: detail.eventOrder
  6448. };
  6449. };
  6450. var Container = single$2({
  6451. name: 'Container',
  6452. factory: factory$1,
  6453. configFields: [
  6454. defaulted$1('components', []),
  6455. field$1('containerBehaviours', []),
  6456. defaulted$1('events', {}),
  6457. defaulted$1('domModification', {}),
  6458. defaulted$1('eventOrder', {})
  6459. ]
  6460. });
  6461. var factory$2 = function (detail) {
  6462. return {
  6463. uid: detail.uid,
  6464. dom: detail.dom,
  6465. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6466. Representing.config({
  6467. store: {
  6468. mode: 'memory',
  6469. initialValue: detail.getInitialValue()
  6470. }
  6471. }),
  6472. Composing.config({ find: Option.some })
  6473. ]),
  6474. events: derive([runOnAttached(function (component, _simulatedEvent) {
  6475. Representing.setValue(component, detail.getInitialValue());
  6476. })])
  6477. };
  6478. };
  6479. var DataField = single$2({
  6480. name: 'DataField',
  6481. factory: factory$2,
  6482. configFields: [
  6483. strict$1('uid'),
  6484. strict$1('dom'),
  6485. strict$1('getInitialValue'),
  6486. SketchBehaviours.field('dataBehaviours', [
  6487. Representing,
  6488. Composing
  6489. ])
  6490. ]
  6491. });
  6492. var get$a = function (element) {
  6493. return element.dom().value;
  6494. };
  6495. var set$6 = function (element, value) {
  6496. if (value === undefined) {
  6497. throw new Error('Value.set was undefined');
  6498. }
  6499. element.dom().value = value;
  6500. };
  6501. var schema$8 = constant([
  6502. option('data'),
  6503. defaulted$1('inputAttributes', {}),
  6504. defaulted$1('inputStyles', {}),
  6505. defaulted$1('tag', 'input'),
  6506. defaulted$1('inputClasses', []),
  6507. onHandler('onSetValue'),
  6508. defaulted$1('styles', {}),
  6509. defaulted$1('eventOrder', {}),
  6510. field$1('inputBehaviours', [
  6511. Representing,
  6512. Focusing
  6513. ]),
  6514. defaulted$1('selectOnFocus', true)
  6515. ]);
  6516. var focusBehaviours = function (detail) {
  6517. return derive$1([Focusing.config({
  6518. onFocus: !detail.selectOnFocus ? noop : function (component) {
  6519. var input = component.element();
  6520. var value = get$a(input);
  6521. input.dom().setSelectionRange(0, value.length);
  6522. }
  6523. })]);
  6524. };
  6525. var behaviours = function (detail) {
  6526. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6527. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  6528. return { initialValue: data };
  6529. }).getOr({})), {
  6530. getValue: function (input) {
  6531. return get$a(input.element());
  6532. },
  6533. setValue: function (input, data) {
  6534. var current = get$a(input.element());
  6535. if (current !== data) {
  6536. set$6(input.element(), data);
  6537. }
  6538. }
  6539. }),
  6540. onSetValue: detail.onSetValue
  6541. })]));
  6542. };
  6543. var dom$2 = function (detail) {
  6544. return {
  6545. tag: detail.tag,
  6546. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6547. styles: detail.inputStyles,
  6548. classes: detail.inputClasses
  6549. };
  6550. };
  6551. var factory$3 = function (detail, _spec) {
  6552. return {
  6553. uid: detail.uid,
  6554. dom: dom$2(detail),
  6555. components: [],
  6556. behaviours: behaviours(detail),
  6557. eventOrder: detail.eventOrder
  6558. };
  6559. };
  6560. var Input = single$2({
  6561. name: 'Input',
  6562. configFields: schema$8(),
  6563. factory: factory$3
  6564. });
  6565. var exhibit$3 = function (base, tabConfig) {
  6566. return nu$5({
  6567. attributes: wrapAll$1([{
  6568. key: tabConfig.tabAttr,
  6569. value: 'true'
  6570. }])
  6571. });
  6572. };
  6573. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6574. __proto__: null,
  6575. exhibit: exhibit$3
  6576. });
  6577. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  6578. var Tabstopping = create$1({
  6579. fields: TabstopSchema,
  6580. name: 'tabstopping',
  6581. active: ActiveTabstopping
  6582. });
  6583. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6584. var clearInputBehaviour = 'input-clearing';
  6585. var field$2 = function (name, placeholder) {
  6586. var inputSpec = record(Input.sketch({
  6587. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6588. onSetValue: function (input$1, _data) {
  6589. emit(input$1, input());
  6590. },
  6591. inputBehaviours: derive$1([
  6592. Composing.config({ find: Option.some }),
  6593. Tabstopping.config({}),
  6594. Keying.config({ mode: 'execution' })
  6595. ]),
  6596. selectOnFocus: false
  6597. }));
  6598. var buttonSpec = record(Button.sketch({
  6599. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6600. action: function (button) {
  6601. var input = inputSpec.get(button);
  6602. Representing.setValue(input, '');
  6603. }
  6604. }));
  6605. return {
  6606. name: name,
  6607. spec: Container.sketch({
  6608. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6609. components: [
  6610. inputSpec.asSpec(),
  6611. buttonSpec.asSpec()
  6612. ],
  6613. containerBehaviours: derive$1([
  6614. Toggling.config({ toggleClass: resolve('input-container-empty') }),
  6615. Composing.config({
  6616. find: function (comp) {
  6617. return Option.some(inputSpec.get(comp));
  6618. }
  6619. }),
  6620. config(clearInputBehaviour, [run(input(), function (iContainer) {
  6621. var input = inputSpec.get(iContainer);
  6622. var val = Representing.getValue(input);
  6623. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6624. f(iContainer);
  6625. })])
  6626. ])
  6627. })
  6628. };
  6629. };
  6630. var hidden = function (name) {
  6631. return {
  6632. name: name,
  6633. spec: DataField.sketch({
  6634. dom: {
  6635. tag: 'span',
  6636. styles: { display: 'none' }
  6637. },
  6638. getInitialValue: function () {
  6639. return Option.none();
  6640. }
  6641. })
  6642. };
  6643. };
  6644. var nativeDisabled = [
  6645. 'input',
  6646. 'button',
  6647. 'textarea',
  6648. 'select'
  6649. ];
  6650. var onLoad$5 = function (component, disableConfig, disableState) {
  6651. var f = disableConfig.disabled() ? disable : enable;
  6652. f(component, disableConfig, disableState);
  6653. };
  6654. var hasNative = function (component, config) {
  6655. return config.useNative === true && contains(nativeDisabled, name(component.element()));
  6656. };
  6657. var nativeIsDisabled = function (component) {
  6658. return has$1(component.element(), 'disabled');
  6659. };
  6660. var nativeDisable = function (component) {
  6661. set(component.element(), 'disabled', 'disabled');
  6662. };
  6663. var nativeEnable = function (component) {
  6664. remove$1(component.element(), 'disabled');
  6665. };
  6666. var ariaIsDisabled = function (component) {
  6667. return get$1(component.element(), 'aria-disabled') === 'true';
  6668. };
  6669. var ariaDisable = function (component) {
  6670. set(component.element(), 'aria-disabled', 'true');
  6671. };
  6672. var ariaEnable = function (component) {
  6673. set(component.element(), 'aria-disabled', 'false');
  6674. };
  6675. var disable = function (component, disableConfig, _disableState) {
  6676. disableConfig.disableClass.each(function (disableClass) {
  6677. add$2(component.element(), disableClass);
  6678. });
  6679. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6680. f(component);
  6681. disableConfig.onDisabled(component);
  6682. };
  6683. var enable = function (component, disableConfig, _disableState) {
  6684. disableConfig.disableClass.each(function (disableClass) {
  6685. remove$4(component.element(), disableClass);
  6686. });
  6687. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6688. f(component);
  6689. disableConfig.onEnabled(component);
  6690. };
  6691. var isDisabled = function (component, disableConfig) {
  6692. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6693. };
  6694. var set$7 = function (component, disableConfig, disableState, disabled) {
  6695. var f = disabled ? disable : enable;
  6696. f(component, disableConfig, disableState);
  6697. };
  6698. var DisableApis = /*#__PURE__*/Object.freeze({
  6699. __proto__: null,
  6700. enable: enable,
  6701. disable: disable,
  6702. isDisabled: isDisabled,
  6703. onLoad: onLoad$5,
  6704. set: set$7
  6705. });
  6706. var exhibit$4 = function (base, disableConfig) {
  6707. return nu$5({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  6708. };
  6709. var events$7 = function (disableConfig, disableState) {
  6710. return derive([
  6711. abort(execute(), function (component, _simulatedEvent) {
  6712. return isDisabled(component, disableConfig);
  6713. }),
  6714. loadEvent(disableConfig, disableState, onLoad$5)
  6715. ]);
  6716. };
  6717. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6718. __proto__: null,
  6719. exhibit: exhibit$4,
  6720. events: events$7
  6721. });
  6722. var DisableSchema = [
  6723. defaultedFunction('disabled', never),
  6724. defaulted$1('useNative', true),
  6725. option('disableClass'),
  6726. onHandler('onDisabled'),
  6727. onHandler('onEnabled')
  6728. ];
  6729. var Disabling = create$1({
  6730. fields: DisableSchema,
  6731. name: 'disabling',
  6732. active: ActiveDisable,
  6733. apis: DisableApis
  6734. });
  6735. var owner$1 = 'form';
  6736. var schema$9 = [field$1('formBehaviours', [Representing])];
  6737. var getPartName = function (name) {
  6738. return '<alloy.field.' + name + '>';
  6739. };
  6740. var sketch$5 = function (fSpec) {
  6741. var parts = function () {
  6742. var record = [];
  6743. var field = function (name, config) {
  6744. record.push(name);
  6745. return generateOne(owner$1, getPartName(name), config);
  6746. };
  6747. return {
  6748. field: field,
  6749. record: function () {
  6750. return record;
  6751. }
  6752. };
  6753. }();
  6754. var spec = fSpec(parts);
  6755. var partNames = parts.record();
  6756. var fieldParts = map$1(partNames, function (n) {
  6757. return required({
  6758. name: n,
  6759. pname: getPartName(n)
  6760. });
  6761. });
  6762. return composite(owner$1, schema$9, fieldParts, make, spec);
  6763. };
  6764. var toResult$1 = function (o, e) {
  6765. return o.fold(function () {
  6766. return Result.error(e);
  6767. }, Result.value);
  6768. };
  6769. var make = function (detail, components) {
  6770. return {
  6771. uid: detail.uid,
  6772. dom: detail.dom,
  6773. components: components,
  6774. behaviours: augment(detail.formBehaviours, [Representing.config({
  6775. store: {
  6776. mode: 'manual',
  6777. getValue: function (form) {
  6778. var resPs = getAllParts(form, detail);
  6779. return map(resPs, function (resPThunk, pName) {
  6780. return resPThunk().bind(function (v) {
  6781. var opt = Composing.getCurrent(v);
  6782. return toResult$1(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element())));
  6783. }).map(Representing.getValue);
  6784. });
  6785. },
  6786. setValue: function (form, values) {
  6787. each(values, function (newValue, key) {
  6788. getPart(form, detail, key).each(function (wrapper) {
  6789. Composing.getCurrent(wrapper).each(function (field) {
  6790. Representing.setValue(field, newValue);
  6791. });
  6792. });
  6793. });
  6794. }
  6795. }
  6796. })]),
  6797. apis: {
  6798. getField: function (form, key) {
  6799. return getPart(form, detail, key).bind(Composing.getCurrent);
  6800. }
  6801. }
  6802. };
  6803. };
  6804. var Form = {
  6805. getField: makeApi(function (apis, component, key) {
  6806. return apis.getField(component, key);
  6807. }),
  6808. sketch: sketch$5
  6809. };
  6810. var api$2 = function () {
  6811. var subject = Cell(Option.none());
  6812. var revoke = function () {
  6813. subject.get().each(function (s) {
  6814. s.destroy();
  6815. });
  6816. };
  6817. var clear = function () {
  6818. revoke();
  6819. subject.set(Option.none());
  6820. };
  6821. var set = function (s) {
  6822. revoke();
  6823. subject.set(Option.some(s));
  6824. };
  6825. var run = function (f) {
  6826. subject.get().each(f);
  6827. };
  6828. var isSet = function () {
  6829. return subject.get().isSome();
  6830. };
  6831. return {
  6832. clear: clear,
  6833. isSet: isSet,
  6834. set: set,
  6835. run: run
  6836. };
  6837. };
  6838. var value$2 = function () {
  6839. var subject = Cell(Option.none());
  6840. var clear = function () {
  6841. subject.set(Option.none());
  6842. };
  6843. var set = function (s) {
  6844. subject.set(Option.some(s));
  6845. };
  6846. var on = function (f) {
  6847. subject.get().each(f);
  6848. };
  6849. var isSet = function () {
  6850. return subject.get().isSome();
  6851. };
  6852. return {
  6853. clear: clear,
  6854. set: set,
  6855. isSet: isSet,
  6856. on: on
  6857. };
  6858. };
  6859. var SWIPING_LEFT = 1;
  6860. var SWIPING_RIGHT = -1;
  6861. var SWIPING_NONE = 0;
  6862. var init$2 = function (xValue) {
  6863. return {
  6864. xValue: xValue,
  6865. points: []
  6866. };
  6867. };
  6868. var move$1 = function (model, xValue) {
  6869. if (xValue === model.xValue) {
  6870. return model;
  6871. }
  6872. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  6873. var newPoint = {
  6874. direction: currentDirection,
  6875. xValue: xValue
  6876. };
  6877. var priorPoints = function () {
  6878. if (model.points.length === 0) {
  6879. return [];
  6880. } else {
  6881. var prev = model.points[model.points.length - 1];
  6882. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  6883. }
  6884. }();
  6885. return {
  6886. xValue: xValue,
  6887. points: priorPoints.concat([newPoint])
  6888. };
  6889. };
  6890. var complete = function (model) {
  6891. if (model.points.length === 0) {
  6892. return SWIPING_NONE;
  6893. } else {
  6894. var firstDirection = model.points[0].direction;
  6895. var lastDirection = model.points[model.points.length - 1].direction;
  6896. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  6897. }
  6898. };
  6899. var sketch$6 = function (rawSpec) {
  6900. var navigateEvent = 'navigateEvent';
  6901. var wrapperAdhocEvents = 'serializer-wrapper-events';
  6902. var formAdhocEvents = 'form-events';
  6903. var schema = objOf([
  6904. strict$1('fields'),
  6905. defaulted$1('maxFieldIndex', rawSpec.fields.length - 1),
  6906. strict$1('onExecute'),
  6907. strict$1('getInitialValue'),
  6908. state$1('state', function () {
  6909. return {
  6910. dialogSwipeState: value$2(),
  6911. currentScreen: Cell(0)
  6912. };
  6913. })
  6914. ]);
  6915. var spec$1 = asRawOrDie('SerialisedDialog', schema, rawSpec);
  6916. var navigationButton = function (direction, directionName, enabled) {
  6917. return Button.sketch({
  6918. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  6919. action: function (button) {
  6920. emitWith(button, navigateEvent, { direction: direction });
  6921. },
  6922. buttonBehaviours: derive$1([Disabling.config({
  6923. disableClass: resolve('toolbar-navigation-disabled'),
  6924. disabled: function () {
  6925. return !enabled;
  6926. }
  6927. })])
  6928. });
  6929. };
  6930. var reposition = function (dialog, message) {
  6931. descendant$1(dialog.element(), '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  6932. set$3(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  6933. });
  6934. };
  6935. var navigate = function (dialog, direction) {
  6936. var screens = descendants(dialog.element(), '.' + resolve('serialised-dialog-screen'));
  6937. descendant$1(dialog.element(), '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  6938. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  6939. getRaw(parent, 'left').each(function (left) {
  6940. var currentLeft = parseInt(left, 10);
  6941. var w = get$7(screens[0]);
  6942. set$3(parent, 'left', currentLeft - direction * w + 'px');
  6943. });
  6944. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  6945. }
  6946. });
  6947. };
  6948. var focusInput = function (dialog) {
  6949. var inputs = descendants(dialog.element(), 'input');
  6950. var optInput = Option.from(inputs[spec$1.state.currentScreen.get()]);
  6951. optInput.each(function (input) {
  6952. dialog.getSystem().getByDom(input).each(function (inputComp) {
  6953. dispatchFocus(dialog, inputComp.element());
  6954. });
  6955. });
  6956. var dotitems = memDots.get(dialog);
  6957. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  6958. };
  6959. var resetState = function () {
  6960. spec$1.state.currentScreen.set(0);
  6961. spec$1.state.dialogSwipeState.clear();
  6962. };
  6963. var memForm = record(Form.sketch(function (parts) {
  6964. return {
  6965. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  6966. components: [Container.sketch({
  6967. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  6968. components: map$1(spec$1.fields, function (field, i) {
  6969. return i <= spec$1.maxFieldIndex ? Container.sketch({
  6970. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  6971. components: [
  6972. navigationButton(-1, 'previous', i > 0),
  6973. parts.field(field.name, field.spec),
  6974. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  6975. ]
  6976. }) : parts.field(field.name, field.spec);
  6977. })
  6978. })],
  6979. formBehaviours: derive$1([
  6980. orientation(function (dialog, message) {
  6981. reposition(dialog, message);
  6982. }),
  6983. Keying.config({
  6984. mode: 'special',
  6985. focusIn: function (dialog, _specialInfo) {
  6986. focusInput(dialog);
  6987. },
  6988. onTab: function (dialog, _specialInfo) {
  6989. navigate(dialog, +1);
  6990. return Option.some(true);
  6991. },
  6992. onShiftTab: function (dialog, _specialInfo) {
  6993. navigate(dialog, -1);
  6994. return Option.some(true);
  6995. }
  6996. }),
  6997. config(formAdhocEvents, [
  6998. runOnAttached(function (dialog, _simulatedEvent) {
  6999. resetState();
  7000. var dotitems = memDots.get(dialog);
  7001. Highlighting.highlightFirst(dotitems);
  7002. spec$1.getInitialValue(dialog).each(function (v) {
  7003. Representing.setValue(dialog, v);
  7004. });
  7005. }),
  7006. runOnExecute(spec$1.onExecute),
  7007. run(transitionend(), function (dialog, simulatedEvent) {
  7008. var event = simulatedEvent.event();
  7009. if (event.raw().propertyName === 'left') {
  7010. focusInput(dialog);
  7011. }
  7012. }),
  7013. run(navigateEvent, function (dialog, simulatedEvent) {
  7014. var event = simulatedEvent.event();
  7015. var direction = event.direction();
  7016. navigate(dialog, direction);
  7017. })
  7018. ])
  7019. ])
  7020. };
  7021. }));
  7022. var memDots = record({
  7023. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7024. behaviours: derive$1([Highlighting.config({
  7025. highlightClass: resolve('dot-active'),
  7026. itemClass: resolve('dot-item')
  7027. })]),
  7028. components: bind(spec$1.fields, function (_f, i) {
  7029. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7030. })
  7031. });
  7032. return {
  7033. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7034. components: [
  7035. memForm.asSpec(),
  7036. memDots.asSpec()
  7037. ],
  7038. behaviours: derive$1([
  7039. Keying.config({
  7040. mode: 'special',
  7041. focusIn: function (wrapper) {
  7042. var form = memForm.get(wrapper);
  7043. Keying.focusIn(form);
  7044. }
  7045. }),
  7046. config(wrapperAdhocEvents, [
  7047. run(touchstart(), function (_wrapper, simulatedEvent) {
  7048. var event = simulatedEvent.event();
  7049. spec$1.state.dialogSwipeState.set(init$2(event.raw().touches[0].clientX));
  7050. }),
  7051. run(touchmove(), function (_wrapper, simulatedEvent) {
  7052. var event = simulatedEvent.event();
  7053. spec$1.state.dialogSwipeState.on(function (state) {
  7054. simulatedEvent.event().prevent();
  7055. spec$1.state.dialogSwipeState.set(move$1(state, event.raw().touches[0].clientX));
  7056. });
  7057. }),
  7058. run(touchend(), function (wrapper, _simulatedEvent) {
  7059. spec$1.state.dialogSwipeState.on(function (state) {
  7060. var dialog = memForm.get(wrapper);
  7061. var direction = -1 * complete(state);
  7062. navigate(dialog, direction);
  7063. });
  7064. })
  7065. ])
  7066. ])
  7067. };
  7068. };
  7069. var getGroups = cached(function (realm, editor) {
  7070. return [{
  7071. label: 'the link group',
  7072. items: [sketch$6({
  7073. fields: [
  7074. field$2('url', 'Type or paste URL'),
  7075. field$2('text', 'Link text'),
  7076. field$2('title', 'Link title'),
  7077. field$2('target', 'Link target'),
  7078. hidden('link')
  7079. ],
  7080. maxFieldIndex: [
  7081. 'url',
  7082. 'text',
  7083. 'title',
  7084. 'target'
  7085. ].length - 1,
  7086. getInitialValue: function () {
  7087. return Option.some(getInfo(editor));
  7088. },
  7089. onExecute: function (dialog, _simulatedEvent) {
  7090. var info = Representing.getValue(dialog);
  7091. applyInfo(editor, info);
  7092. realm.restoreToolbar();
  7093. editor.focus();
  7094. }
  7095. })]
  7096. }];
  7097. });
  7098. var sketch$7 = function (realm, editor) {
  7099. return forToolbarStateAction(editor, 'link', 'link', function () {
  7100. var groups = getGroups(realm, editor);
  7101. realm.setContextToolbar(groups);
  7102. forAndroid(editor, function () {
  7103. realm.focusToolbar();
  7104. });
  7105. query(editor).each(function (link) {
  7106. editor.selection.select(link.dom());
  7107. });
  7108. });
  7109. };
  7110. var DefaultStyleFormats = [
  7111. {
  7112. title: 'Headings',
  7113. items: [
  7114. {
  7115. title: 'Heading 1',
  7116. format: 'h1'
  7117. },
  7118. {
  7119. title: 'Heading 2',
  7120. format: 'h2'
  7121. },
  7122. {
  7123. title: 'Heading 3',
  7124. format: 'h3'
  7125. },
  7126. {
  7127. title: 'Heading 4',
  7128. format: 'h4'
  7129. },
  7130. {
  7131. title: 'Heading 5',
  7132. format: 'h5'
  7133. },
  7134. {
  7135. title: 'Heading 6',
  7136. format: 'h6'
  7137. }
  7138. ]
  7139. },
  7140. {
  7141. title: 'Inline',
  7142. items: [
  7143. {
  7144. title: 'Bold',
  7145. icon: 'bold',
  7146. format: 'bold'
  7147. },
  7148. {
  7149. title: 'Italic',
  7150. icon: 'italic',
  7151. format: 'italic'
  7152. },
  7153. {
  7154. title: 'Underline',
  7155. icon: 'underline',
  7156. format: 'underline'
  7157. },
  7158. {
  7159. title: 'Strikethrough',
  7160. icon: 'strikethrough',
  7161. format: 'strikethrough'
  7162. },
  7163. {
  7164. title: 'Superscript',
  7165. icon: 'superscript',
  7166. format: 'superscript'
  7167. },
  7168. {
  7169. title: 'Subscript',
  7170. icon: 'subscript',
  7171. format: 'subscript'
  7172. },
  7173. {
  7174. title: 'Code',
  7175. icon: 'code',
  7176. format: 'code'
  7177. }
  7178. ]
  7179. },
  7180. {
  7181. title: 'Blocks',
  7182. items: [
  7183. {
  7184. title: 'Paragraph',
  7185. format: 'p'
  7186. },
  7187. {
  7188. title: 'Blockquote',
  7189. format: 'blockquote'
  7190. },
  7191. {
  7192. title: 'Div',
  7193. format: 'div'
  7194. },
  7195. {
  7196. title: 'Pre',
  7197. format: 'pre'
  7198. }
  7199. ]
  7200. },
  7201. {
  7202. title: 'Alignment',
  7203. items: [
  7204. {
  7205. title: 'Left',
  7206. icon: 'alignleft',
  7207. format: 'alignleft'
  7208. },
  7209. {
  7210. title: 'Center',
  7211. icon: 'aligncenter',
  7212. format: 'aligncenter'
  7213. },
  7214. {
  7215. title: 'Right',
  7216. icon: 'alignright',
  7217. format: 'alignright'
  7218. },
  7219. {
  7220. title: 'Justify',
  7221. icon: 'alignjustify',
  7222. format: 'alignjustify'
  7223. }
  7224. ]
  7225. }
  7226. ];
  7227. var isRecursive = function (component, originator, target) {
  7228. return eq(originator, component.element()) && !eq(originator, target);
  7229. };
  7230. var events$8 = derive([can(focus(), function (component, simulatedEvent) {
  7231. var originator = simulatedEvent.event().originator();
  7232. var target = simulatedEvent.event().target();
  7233. if (isRecursive(component, originator, target)) {
  7234. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  7235. return false;
  7236. } else {
  7237. return true;
  7238. }
  7239. })]);
  7240. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7241. __proto__: null,
  7242. events: events$8
  7243. });
  7244. var make$1 = identity;
  7245. var NoContextApi = function (getComp) {
  7246. var fail = function (event) {
  7247. return function () {
  7248. throw new Error('The component must be in a context to send: ' + event + (getComp ? '\n' + element(getComp().element()) + ' is not in context.' : ''));
  7249. };
  7250. };
  7251. return {
  7252. debugInfo: constant('fake'),
  7253. triggerEvent: fail('triggerEvent'),
  7254. triggerFocus: fail('triggerFocus'),
  7255. triggerEscape: fail('triggerEscape'),
  7256. build: fail('build'),
  7257. addToWorld: fail('addToWorld'),
  7258. removeFromWorld: fail('removeFromWorld'),
  7259. addToGui: fail('addToGui'),
  7260. removeFromGui: fail('removeFromGui'),
  7261. getByUid: fail('getByUid'),
  7262. getByDom: fail('getByDom'),
  7263. broadcast: fail('broadcast'),
  7264. broadcastOn: fail('broadcastOn'),
  7265. broadcastEvent: fail('broadcastEvent'),
  7266. isConnected: constant(false)
  7267. };
  7268. };
  7269. var singleton = NoContextApi();
  7270. var generateFrom = function (spec, all) {
  7271. var schema = map$1(all, function (a) {
  7272. return optionObjOf(a.name(), [
  7273. strict$1('config'),
  7274. defaulted$1('state', NoState)
  7275. ]);
  7276. });
  7277. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7278. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7279. }, function (v) {
  7280. return v;
  7281. });
  7282. return {
  7283. list: all,
  7284. data: map(validated, function (optBlobThunk) {
  7285. var output = optBlobThunk.map(function (blob) {
  7286. return {
  7287. config: blob.config,
  7288. state: blob.state.init(blob.config)
  7289. };
  7290. });
  7291. return function () {
  7292. return output;
  7293. };
  7294. })
  7295. };
  7296. };
  7297. var getBehaviours = function (bData) {
  7298. return bData.list;
  7299. };
  7300. var getData = function (bData) {
  7301. return bData.data;
  7302. };
  7303. var byInnerKey = function (data, tuple) {
  7304. var r = {};
  7305. each(data, function (detail, key) {
  7306. each(detail, function (value, indexKey) {
  7307. var chain = get(r, indexKey).getOr([]);
  7308. r[indexKey] = chain.concat([tuple(key, value)]);
  7309. });
  7310. });
  7311. return r;
  7312. };
  7313. var combine$1 = function (info, baseMod, behaviours, base) {
  7314. var modsByBehaviour = __assign({}, baseMod);
  7315. each$1(behaviours, function (behaviour) {
  7316. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7317. });
  7318. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  7319. return {
  7320. name: name,
  7321. modification: modification
  7322. };
  7323. });
  7324. var combineObjects = function (objects) {
  7325. return foldr(objects, function (b, a) {
  7326. return __assign(__assign({}, a.modification), b);
  7327. }, {});
  7328. };
  7329. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7330. return a.modification.concat(b);
  7331. }, []);
  7332. var combinedAttributes = combineObjects(byAspect.attributes);
  7333. var combinedStyles = combineObjects(byAspect.styles);
  7334. return nu$5({
  7335. classes: combinedClasses,
  7336. attributes: combinedAttributes,
  7337. styles: combinedStyles
  7338. });
  7339. };
  7340. var sortKeys = function (label, keyName, array, order) {
  7341. try {
  7342. var sorted = sort(array, function (a, b) {
  7343. var aKey = a[keyName]();
  7344. var bKey = b[keyName]();
  7345. var aIndex = order.indexOf(aKey);
  7346. var bIndex = order.indexOf(bKey);
  7347. if (aIndex === -1) {
  7348. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7349. }
  7350. if (bIndex === -1) {
  7351. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7352. }
  7353. if (aIndex < bIndex) {
  7354. return -1;
  7355. } else if (bIndex < aIndex) {
  7356. return 1;
  7357. } else {
  7358. return 0;
  7359. }
  7360. });
  7361. return Result.value(sorted);
  7362. } catch (err) {
  7363. return Result.error([err]);
  7364. }
  7365. };
  7366. var uncurried = function (handler, purpose) {
  7367. return {
  7368. handler: handler,
  7369. purpose: constant(purpose)
  7370. };
  7371. };
  7372. var curried = function (handler, purpose) {
  7373. return {
  7374. cHandler: handler,
  7375. purpose: constant(purpose)
  7376. };
  7377. };
  7378. var curryArgs = function (descHandler, extraArgs) {
  7379. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  7380. };
  7381. var getCurried = function (descHandler) {
  7382. return descHandler.cHandler;
  7383. };
  7384. var behaviourTuple = function (name, handler) {
  7385. return {
  7386. name: constant(name),
  7387. handler: constant(handler)
  7388. };
  7389. };
  7390. var nameToHandlers = function (behaviours, info) {
  7391. var r = {};
  7392. each$1(behaviours, function (behaviour) {
  7393. r[behaviour.name()] = behaviour.handlers(info);
  7394. });
  7395. return r;
  7396. };
  7397. var groupByEvents = function (info, behaviours, base) {
  7398. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7399. return byInnerKey(behaviourEvents, behaviourTuple);
  7400. };
  7401. var combine$2 = function (info, eventOrder, behaviours, base) {
  7402. var byEventName = groupByEvents(info, behaviours, base);
  7403. return combineGroups(byEventName, eventOrder);
  7404. };
  7405. var assemble = function (rawHandler) {
  7406. var handler = read(rawHandler);
  7407. return function (component, simulatedEvent) {
  7408. var rest = [];
  7409. for (var _i = 2; _i < arguments.length; _i++) {
  7410. rest[_i - 2] = arguments[_i];
  7411. }
  7412. var args = [
  7413. component,
  7414. simulatedEvent
  7415. ].concat(rest);
  7416. if (handler.abort.apply(undefined, args)) {
  7417. simulatedEvent.stop();
  7418. } else if (handler.can.apply(undefined, args)) {
  7419. handler.run.apply(undefined, args);
  7420. }
  7421. };
  7422. };
  7423. var missingOrderError = function (eventName, tuples) {
  7424. 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) {
  7425. return c.name();
  7426. }), null, 2)]);
  7427. };
  7428. var fuse$1 = function (tuples, eventOrder, eventName) {
  7429. var order = eventOrder[eventName];
  7430. if (!order) {
  7431. return missingOrderError(eventName, tuples);
  7432. } else {
  7433. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7434. var handlers = map$1(sortedTuples, function (tuple) {
  7435. return tuple.handler();
  7436. });
  7437. return fuse(handlers);
  7438. });
  7439. }
  7440. };
  7441. var combineGroups = function (byEventName, eventOrder) {
  7442. var r = mapToArray(byEventName, function (tuples, eventName) {
  7443. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  7444. return combined.map(function (handler) {
  7445. var assembled = assemble(handler);
  7446. var purpose = tuples.length > 1 ? filter$1(eventOrder[eventName], function (o) {
  7447. return exists(tuples, function (t) {
  7448. return t.name() === o;
  7449. });
  7450. }).join(' > ') : tuples[0].name();
  7451. return wrap$1(eventName, uncurried(assembled, purpose));
  7452. });
  7453. });
  7454. return consolidate(r, {});
  7455. };
  7456. var toInfo = function (spec) {
  7457. return asRaw('custom.definition', objOf([
  7458. field('dom', 'dom', strict(), objOf([
  7459. strict$1('tag'),
  7460. defaulted$1('styles', {}),
  7461. defaulted$1('classes', []),
  7462. defaulted$1('attributes', {}),
  7463. option('value'),
  7464. option('innerHtml')
  7465. ])),
  7466. strict$1('components'),
  7467. strict$1('uid'),
  7468. defaulted$1('events', {}),
  7469. defaulted$1('apis', {}),
  7470. field('eventOrder', 'eventOrder', mergeWith({
  7471. 'alloy.execute': [
  7472. 'disabling',
  7473. 'alloy.base.behaviour',
  7474. 'toggling',
  7475. 'typeaheadevents'
  7476. ],
  7477. 'alloy.focus': [
  7478. 'alloy.base.behaviour',
  7479. 'focusing',
  7480. 'keying'
  7481. ],
  7482. 'alloy.system.init': [
  7483. 'alloy.base.behaviour',
  7484. 'disabling',
  7485. 'toggling',
  7486. 'representing'
  7487. ],
  7488. 'input': [
  7489. 'alloy.base.behaviour',
  7490. 'representing',
  7491. 'streaming',
  7492. 'invalidating'
  7493. ],
  7494. 'alloy.system.detached': [
  7495. 'alloy.base.behaviour',
  7496. 'representing',
  7497. 'item-events',
  7498. 'tooltipping'
  7499. ],
  7500. 'mousedown': [
  7501. 'focusing',
  7502. 'alloy.base.behaviour',
  7503. 'item-type-events'
  7504. ],
  7505. 'touchstart': [
  7506. 'focusing',
  7507. 'alloy.base.behaviour',
  7508. 'item-type-events'
  7509. ],
  7510. 'mouseover': [
  7511. 'item-type-events',
  7512. 'tooltipping'
  7513. ],
  7514. 'alloy.receive': [
  7515. 'receiving',
  7516. 'reflecting'
  7517. ]
  7518. }), anyValue$1()),
  7519. option('domModification')
  7520. ]), spec);
  7521. };
  7522. var toDefinition = function (detail) {
  7523. return __assign(__assign({}, detail.dom), {
  7524. uid: detail.uid,
  7525. domChildren: map$1(detail.components, function (comp) {
  7526. return comp.element();
  7527. })
  7528. });
  7529. };
  7530. var toModification = function (detail) {
  7531. return detail.domModification.fold(function () {
  7532. return nu$5({});
  7533. }, nu$5);
  7534. };
  7535. var toEvents = function (info) {
  7536. return info.events;
  7537. };
  7538. var add$3 = function (element, classes) {
  7539. each$1(classes, function (x) {
  7540. add$2(element, x);
  7541. });
  7542. };
  7543. var remove$6 = function (element, classes) {
  7544. each$1(classes, function (x) {
  7545. remove$4(element, x);
  7546. });
  7547. };
  7548. var renderToDom = function (definition) {
  7549. var subject = Element.fromTag(definition.tag);
  7550. setAll(subject, definition.attributes);
  7551. add$3(subject, definition.classes);
  7552. setAll$1(subject, definition.styles);
  7553. definition.innerHtml.each(function (html) {
  7554. return set$1(subject, html);
  7555. });
  7556. var children = definition.domChildren;
  7557. append$1(subject, children);
  7558. definition.value.each(function (value) {
  7559. set$6(subject, value);
  7560. });
  7561. if (!definition.uid) {
  7562. debugger;
  7563. }
  7564. writeOnly(subject, definition.uid);
  7565. return subject;
  7566. };
  7567. var getBehaviours$1 = function (spec) {
  7568. var behaviours = get(spec, 'behaviours').getOr({});
  7569. var keys$1 = filter$1(keys(behaviours), function (k) {
  7570. return behaviours[k] !== undefined;
  7571. });
  7572. return map$1(keys$1, function (k) {
  7573. return behaviours[k].me;
  7574. });
  7575. };
  7576. var generateFrom$1 = function (spec, all) {
  7577. return generateFrom(spec, all);
  7578. };
  7579. var generate$4 = function (spec) {
  7580. var all = getBehaviours$1(spec);
  7581. return generateFrom$1(spec, all);
  7582. };
  7583. var getDomDefinition = function (info, bList, bData) {
  7584. var definition = toDefinition(info);
  7585. var infoModification = toModification(info);
  7586. var baseModification = { 'alloy.base.modification': infoModification };
  7587. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7588. return merge$1(definition, modification);
  7589. };
  7590. var getEvents = function (info, bList, bData) {
  7591. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7592. return combine$2(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7593. };
  7594. var build = function (spec) {
  7595. var getMe = function () {
  7596. return me;
  7597. };
  7598. var systemApi = Cell(singleton);
  7599. var info = getOrDie(toInfo(spec));
  7600. var bBlob = generate$4(spec);
  7601. var bList = getBehaviours(bBlob);
  7602. var bData = getData(bBlob);
  7603. var modDefinition = getDomDefinition(info, bList, bData);
  7604. var item = renderToDom(modDefinition);
  7605. var events = getEvents(info, bList, bData);
  7606. var subcomponents = Cell(info.components);
  7607. var connect = function (newApi) {
  7608. systemApi.set(newApi);
  7609. };
  7610. var disconnect = function () {
  7611. systemApi.set(NoContextApi(getMe));
  7612. };
  7613. var syncComponents = function () {
  7614. var children$1 = children(item);
  7615. var subs = bind(children$1, function (child) {
  7616. return systemApi.get().getByDom(child).fold(function () {
  7617. return [];
  7618. }, function (c) {
  7619. return [c];
  7620. });
  7621. });
  7622. subcomponents.set(subs);
  7623. };
  7624. var config = function (behaviour) {
  7625. var b = bData;
  7626. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7627. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7628. };
  7629. return f();
  7630. };
  7631. var hasConfigured = function (behaviour) {
  7632. return isFunction(bData[behaviour.name()]);
  7633. };
  7634. var getApis = function () {
  7635. return info.apis;
  7636. };
  7637. var readState = function (behaviourName) {
  7638. return bData[behaviourName]().map(function (b) {
  7639. return b.state.readState();
  7640. }).getOr('not enabled');
  7641. };
  7642. var me = {
  7643. getSystem: systemApi.get,
  7644. config: config,
  7645. hasConfigured: hasConfigured,
  7646. spec: constant(spec),
  7647. readState: readState,
  7648. getApis: getApis,
  7649. connect: connect,
  7650. disconnect: disconnect,
  7651. element: constant(item),
  7652. syncComponents: syncComponents,
  7653. components: subcomponents.get,
  7654. events: constant(events)
  7655. };
  7656. return me;
  7657. };
  7658. var buildSubcomponents = function (spec) {
  7659. var components = get(spec, 'components').getOr([]);
  7660. return map$1(components, build$1);
  7661. };
  7662. var buildFromSpec = function (userSpec) {
  7663. var _a = make$1(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7664. var components = buildSubcomponents(spec);
  7665. var completeSpec = __assign(__assign({}, spec), {
  7666. events: __assign(__assign({}, DefaultEvents), specEvents),
  7667. components: components
  7668. });
  7669. return Result.value(build(completeSpec));
  7670. };
  7671. var text = function (textContent) {
  7672. var element = Element.fromText(textContent);
  7673. return external$1({ element: element });
  7674. };
  7675. var external$1 = function (spec) {
  7676. var extSpec = asRawOrDie('external.component', objOfOnly([
  7677. strict$1('element'),
  7678. option('uid')
  7679. ]), spec);
  7680. var systemApi = Cell(NoContextApi());
  7681. var connect = function (newApi) {
  7682. systemApi.set(newApi);
  7683. };
  7684. var disconnect = function () {
  7685. systemApi.set(NoContextApi(function () {
  7686. return me;
  7687. }));
  7688. };
  7689. extSpec.uid.each(function (uid) {
  7690. writeOnly(extSpec.element, uid);
  7691. });
  7692. var me = {
  7693. getSystem: systemApi.get,
  7694. config: Option.none,
  7695. hasConfigured: constant(false),
  7696. connect: connect,
  7697. disconnect: disconnect,
  7698. getApis: function () {
  7699. return {};
  7700. },
  7701. element: constant(extSpec.element),
  7702. spec: constant(spec),
  7703. readState: constant('No state'),
  7704. syncComponents: noop,
  7705. components: constant([]),
  7706. events: constant({})
  7707. };
  7708. return premade(me);
  7709. };
  7710. var uids = generate$3;
  7711. var build$1 = function (spec) {
  7712. return getPremade(spec).fold(function () {
  7713. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  7714. return buildFromSpec(userSpecWithUid).getOrDie();
  7715. }, function (prebuilt) {
  7716. return prebuilt;
  7717. });
  7718. };
  7719. var premade$1 = premade;
  7720. var hoverEvent = 'alloy.item-hover';
  7721. var focusEvent = 'alloy.item-focus';
  7722. var onHover = function (item) {
  7723. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  7724. if (!Focusing.isFocused(item)) {
  7725. Focusing.focus(item);
  7726. }
  7727. emitWith(item, hoverEvent, { item: item });
  7728. }
  7729. };
  7730. var onFocus = function (item) {
  7731. emitWith(item, focusEvent, { item: item });
  7732. };
  7733. var hover = constant(hoverEvent);
  7734. var focus$3 = constant(focusEvent);
  7735. var builder = function (detail) {
  7736. return {
  7737. dom: detail.dom,
  7738. 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 } : {}) }),
  7739. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7740. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7741. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7742. }),
  7743. Focusing.config({
  7744. ignore: detail.ignoreFocus,
  7745. stopMousedown: detail.ignoreFocus,
  7746. onFocus: function (component) {
  7747. onFocus(component);
  7748. }
  7749. }),
  7750. Keying.config({ mode: 'execution' }),
  7751. Representing.config({
  7752. store: {
  7753. mode: 'memory',
  7754. initialValue: detail.data
  7755. }
  7756. }),
  7757. config('item-type-events', __spreadArrays(pointerEvents(), [
  7758. run(mouseover(), onHover),
  7759. run(focusItem(), Focusing.focus)
  7760. ]))
  7761. ]),
  7762. components: detail.components,
  7763. eventOrder: detail.eventOrder
  7764. };
  7765. };
  7766. var schema$a = [
  7767. strict$1('data'),
  7768. strict$1('components'),
  7769. strict$1('dom'),
  7770. defaulted$1('hasSubmenu', false),
  7771. option('toggling'),
  7772. SketchBehaviours.field('itemBehaviours', [
  7773. Toggling,
  7774. Focusing,
  7775. Keying,
  7776. Representing
  7777. ]),
  7778. defaulted$1('ignoreFocus', false),
  7779. defaulted$1('domModification', {}),
  7780. output('builder', builder),
  7781. defaulted$1('eventOrder', {})
  7782. ];
  7783. var builder$1 = function (detail) {
  7784. return {
  7785. dom: detail.dom,
  7786. components: detail.components,
  7787. events: derive([stopper(focusItem())])
  7788. };
  7789. };
  7790. var schema$b = [
  7791. strict$1('dom'),
  7792. strict$1('components'),
  7793. output('builder', builder$1)
  7794. ];
  7795. var owner$2 = function () {
  7796. return 'item-widget';
  7797. };
  7798. var parts = constant([required({
  7799. name: 'widget',
  7800. overrides: function (detail) {
  7801. return {
  7802. behaviours: derive$1([Representing.config({
  7803. store: {
  7804. mode: 'manual',
  7805. getValue: function (_component) {
  7806. return detail.data;
  7807. },
  7808. setValue: function () {
  7809. }
  7810. }
  7811. })])
  7812. };
  7813. }
  7814. })]);
  7815. var builder$2 = function (detail) {
  7816. var subs = substitutes(owner$2(), detail, parts());
  7817. var components$1 = components(owner$2(), detail, subs.internals());
  7818. var focusWidget = function (component) {
  7819. return getPart(component, detail, 'widget').map(function (widget) {
  7820. Keying.focusIn(widget);
  7821. return widget;
  7822. });
  7823. };
  7824. var onHorizontalArrow = function (component, simulatedEvent) {
  7825. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  7826. if (detail.autofocus) {
  7827. simulatedEvent.setSource(component.element());
  7828. return Option.none();
  7829. } else {
  7830. return Option.none();
  7831. }
  7832. }();
  7833. };
  7834. return {
  7835. dom: detail.dom,
  7836. components: components$1,
  7837. domModification: detail.domModification,
  7838. events: derive([
  7839. runOnExecute(function (component, simulatedEvent) {
  7840. focusWidget(component).each(function (_widget) {
  7841. simulatedEvent.stop();
  7842. });
  7843. }),
  7844. run(mouseover(), onHover),
  7845. run(focusItem(), function (component, _simulatedEvent) {
  7846. if (detail.autofocus) {
  7847. focusWidget(component);
  7848. } else {
  7849. Focusing.focus(component);
  7850. }
  7851. })
  7852. ]),
  7853. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7854. Representing.config({
  7855. store: {
  7856. mode: 'memory',
  7857. initialValue: detail.data
  7858. }
  7859. }),
  7860. Focusing.config({
  7861. ignore: detail.ignoreFocus,
  7862. onFocus: function (component) {
  7863. onFocus(component);
  7864. }
  7865. }),
  7866. Keying.config({
  7867. mode: 'special',
  7868. focusIn: detail.autofocus ? function (component) {
  7869. focusWidget(component);
  7870. } : revoke(),
  7871. onLeft: onHorizontalArrow,
  7872. onRight: onHorizontalArrow,
  7873. onEscape: function (component, simulatedEvent) {
  7874. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7875. Focusing.focus(component);
  7876. return Option.some(true);
  7877. } else if (detail.autofocus) {
  7878. simulatedEvent.setSource(component.element());
  7879. return Option.none();
  7880. } else {
  7881. return Option.none();
  7882. }
  7883. }
  7884. })
  7885. ])
  7886. };
  7887. };
  7888. var schema$c = [
  7889. strict$1('uid'),
  7890. strict$1('data'),
  7891. strict$1('components'),
  7892. strict$1('dom'),
  7893. defaulted$1('autofocus', false),
  7894. defaulted$1('ignoreFocus', false),
  7895. SketchBehaviours.field('widgetBehaviours', [
  7896. Representing,
  7897. Focusing,
  7898. Keying
  7899. ]),
  7900. defaulted$1('domModification', {}),
  7901. defaultUidsSchema(parts()),
  7902. output('builder', builder$2)
  7903. ];
  7904. var itemSchema$1 = choose$1('type', {
  7905. widget: schema$c,
  7906. item: schema$a,
  7907. separator: schema$b
  7908. });
  7909. var configureGrid = function (detail, movementInfo) {
  7910. return {
  7911. mode: 'flatgrid',
  7912. selector: '.' + detail.markers.item,
  7913. initSize: {
  7914. numColumns: movementInfo.initSize.numColumns,
  7915. numRows: movementInfo.initSize.numRows
  7916. },
  7917. focusManager: detail.focusManager
  7918. };
  7919. };
  7920. var configureMatrix = function (detail, movementInfo) {
  7921. return {
  7922. mode: 'matrix',
  7923. selectors: {
  7924. row: movementInfo.rowSelector,
  7925. cell: '.' + detail.markers.item
  7926. },
  7927. focusManager: detail.focusManager
  7928. };
  7929. };
  7930. var configureMenu = function (detail, movementInfo) {
  7931. return {
  7932. mode: 'menu',
  7933. selector: '.' + detail.markers.item,
  7934. moveOnTab: movementInfo.moveOnTab,
  7935. focusManager: detail.focusManager
  7936. };
  7937. };
  7938. var parts$1 = constant([group({
  7939. factory: {
  7940. sketch: function (spec) {
  7941. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  7942. return itemInfo.builder(itemInfo);
  7943. }
  7944. },
  7945. name: 'items',
  7946. unit: 'item',
  7947. defaults: function (detail, u) {
  7948. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$3('item') });
  7949. },
  7950. overrides: function (detail, u) {
  7951. return {
  7952. type: u.type,
  7953. ignoreFocus: detail.fakeFocus,
  7954. domModification: { classes: [detail.markers.item] }
  7955. };
  7956. }
  7957. })]);
  7958. var schema$d = constant([
  7959. strict$1('value'),
  7960. strict$1('items'),
  7961. strict$1('dom'),
  7962. strict$1('components'),
  7963. defaulted$1('eventOrder', {}),
  7964. field$1('menuBehaviours', [
  7965. Highlighting,
  7966. Representing,
  7967. Composing,
  7968. Keying
  7969. ]),
  7970. defaultedOf('movement', {
  7971. mode: 'menu',
  7972. moveOnTab: true
  7973. }, choose$1('mode', {
  7974. grid: [
  7975. initSize(),
  7976. output('config', configureGrid)
  7977. ],
  7978. matrix: [
  7979. output('config', configureMatrix),
  7980. strict$1('rowSelector')
  7981. ],
  7982. menu: [
  7983. defaulted$1('moveOnTab', true),
  7984. output('config', configureMenu)
  7985. ]
  7986. })),
  7987. itemMarkers(),
  7988. defaulted$1('fakeFocus', false),
  7989. defaulted$1('focusManager', dom()),
  7990. onHandler('onHighlight')
  7991. ]);
  7992. var focus$4 = constant('alloy.menu-focus');
  7993. var make$2 = function (detail, components, _spec, _externals) {
  7994. return {
  7995. uid: detail.uid,
  7996. dom: detail.dom,
  7997. markers: detail.markers,
  7998. behaviours: augment(detail.menuBehaviours, [
  7999. Highlighting.config({
  8000. highlightClass: detail.markers.selectedItem,
  8001. itemClass: detail.markers.item,
  8002. onHighlight: detail.onHighlight
  8003. }),
  8004. Representing.config({
  8005. store: {
  8006. mode: 'memory',
  8007. initialValue: detail.value
  8008. }
  8009. }),
  8010. Composing.config({ find: Option.some }),
  8011. Keying.config(detail.movement.config(detail, detail.movement))
  8012. ]),
  8013. events: derive([
  8014. run(focus$3(), function (menu, simulatedEvent) {
  8015. var event = simulatedEvent.event();
  8016. menu.getSystem().getByDom(event.target()).each(function (item) {
  8017. Highlighting.highlight(menu, item);
  8018. simulatedEvent.stop();
  8019. emitWith(menu, focus$4(), {
  8020. menu: menu,
  8021. item: item
  8022. });
  8023. });
  8024. }),
  8025. run(hover(), function (menu, simulatedEvent) {
  8026. var item = simulatedEvent.event().item();
  8027. Highlighting.highlight(menu, item);
  8028. })
  8029. ]),
  8030. components: components,
  8031. eventOrder: detail.eventOrder,
  8032. domModification: { attributes: { role: 'menu' } }
  8033. };
  8034. };
  8035. var Menu = composite$1({
  8036. name: 'Menu',
  8037. configFields: schema$d(),
  8038. partFields: parts$1(),
  8039. factory: make$2
  8040. });
  8041. var preserve$1 = function (f, container) {
  8042. var ownerDoc = owner(container);
  8043. var refocus = active(ownerDoc).bind(function (focused) {
  8044. var hasFocus = function (elem) {
  8045. return eq(focused, elem);
  8046. };
  8047. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  8048. });
  8049. var result = f(container);
  8050. refocus.each(function (oldFocus) {
  8051. active(ownerDoc).filter(function (newFocus) {
  8052. return eq(newFocus, oldFocus);
  8053. }).fold(function () {
  8054. focus$1(oldFocus);
  8055. }, noop);
  8056. });
  8057. return result;
  8058. };
  8059. var set$8 = function (component, replaceConfig, replaceState, data) {
  8060. preserve$1(function () {
  8061. var newChildren = map$1(data, component.getSystem().build);
  8062. replaceChildren(component, newChildren);
  8063. }, component.element());
  8064. };
  8065. var insert = function (component, replaceConfig, insertion, childSpec) {
  8066. var child = component.getSystem().build(childSpec);
  8067. attachWith(component, child, insertion);
  8068. };
  8069. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  8070. insert(component, replaceConfig, append, appendee);
  8071. };
  8072. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  8073. insert(component, replaceConfig, prepend, prependee);
  8074. };
  8075. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  8076. var children = contents(component);
  8077. var foundChild = find$2(children, function (child) {
  8078. return eq(removee.element(), child.element());
  8079. });
  8080. foundChild.each(detach);
  8081. };
  8082. var contents = function (component, _replaceConfig) {
  8083. return component.components();
  8084. };
  8085. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8086. var children = contents(component);
  8087. return Option.from(children[replaceeIndex]).map(function (replacee) {
  8088. remove$7(component, replaceConfig, replaceState, replacee);
  8089. replacer.each(function (r) {
  8090. insert(component, replaceConfig, function (p, c) {
  8091. appendAt(p, c, replaceeIndex);
  8092. }, r);
  8093. });
  8094. return replacee;
  8095. });
  8096. };
  8097. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8098. var children = contents(component);
  8099. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  8100. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8101. });
  8102. };
  8103. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8104. __proto__: null,
  8105. append: append$2,
  8106. prepend: prepend$1,
  8107. remove: remove$7,
  8108. replaceAt: replaceAt,
  8109. replaceBy: replaceBy,
  8110. set: set$8,
  8111. contents: contents
  8112. });
  8113. var Replacing = create$1({
  8114. fields: [],
  8115. name: 'replacing',
  8116. apis: ReplaceApis
  8117. });
  8118. var transpose = function (obj) {
  8119. return tupleMap(obj, function (v, k) {
  8120. return {
  8121. k: v,
  8122. v: k
  8123. };
  8124. });
  8125. };
  8126. var trace = function (items, byItem, byMenu, finish) {
  8127. return get(byMenu, finish).bind(function (triggerItem) {
  8128. return get(items, triggerItem).bind(function (triggerMenu) {
  8129. var rest = trace(items, byItem, byMenu, triggerMenu);
  8130. return Option.some([triggerMenu].concat(rest));
  8131. });
  8132. }).getOr([]);
  8133. };
  8134. var generate$5 = function (menus, expansions) {
  8135. var items = {};
  8136. each(menus, function (menuItems, menu) {
  8137. each$1(menuItems, function (item) {
  8138. items[item] = menu;
  8139. });
  8140. });
  8141. var byItem = expansions;
  8142. var byMenu = transpose(expansions);
  8143. var menuPaths = map(byMenu, function (_triggerItem, submenu) {
  8144. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8145. });
  8146. return map(items, function (menu) {
  8147. return get(menuPaths, menu).getOr([menu]);
  8148. });
  8149. };
  8150. var init$3 = function () {
  8151. var expansions = Cell({});
  8152. var menus = Cell({});
  8153. var paths = Cell({});
  8154. var primary = Cell(Option.none());
  8155. var directory = Cell({});
  8156. var clear = function () {
  8157. expansions.set({});
  8158. menus.set({});
  8159. paths.set({});
  8160. primary.set(Option.none());
  8161. };
  8162. var isClear = function () {
  8163. return primary.get().isNone();
  8164. };
  8165. var setMenuBuilt = function (menuName, built) {
  8166. var _a;
  8167. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8168. type: 'prepared',
  8169. menu: built
  8170. }, _a)));
  8171. };
  8172. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8173. primary.set(Option.some(sPrimary));
  8174. expansions.set(sExpansions);
  8175. menus.set(sMenus);
  8176. directory.set(dir);
  8177. var sPaths = generate$5(dir, sExpansions);
  8178. paths.set(sPaths);
  8179. };
  8180. var getTriggeringItem = function (menuValue) {
  8181. return find(expansions.get(), function (v, _k) {
  8182. return v === menuValue;
  8183. });
  8184. };
  8185. var getTriggerData = function (menuValue, getItemByValue, path) {
  8186. return getPreparedMenu(menuValue).bind(function (menu) {
  8187. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8188. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8189. return {
  8190. triggeredMenu: menu,
  8191. triggeringItem: triggeredItem,
  8192. triggeringPath: path
  8193. };
  8194. });
  8195. });
  8196. });
  8197. };
  8198. var getTriggeringPath = function (itemValue, getItemByValue) {
  8199. var extraPath = filter$1(lookupItem(itemValue).toArray(), function (menuValue) {
  8200. return getPreparedMenu(menuValue).isSome();
  8201. });
  8202. return get(paths.get(), itemValue).bind(function (path) {
  8203. var revPath = reverse(extraPath.concat(path));
  8204. var triggers = bind(revPath, function (menuValue, menuIndex) {
  8205. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8206. return primary.get().is(menuValue) ? [] : [Option.none()];
  8207. }, function (data) {
  8208. return [Option.some(data)];
  8209. });
  8210. });
  8211. return sequence(triggers);
  8212. });
  8213. };
  8214. var expand = function (itemValue) {
  8215. return get(expansions.get(), itemValue).map(function (menu) {
  8216. var current = get(paths.get(), itemValue).getOr([]);
  8217. return [menu].concat(current);
  8218. });
  8219. };
  8220. var collapse = function (itemValue) {
  8221. return get(paths.get(), itemValue).bind(function (path) {
  8222. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  8223. });
  8224. };
  8225. var refresh = function (itemValue) {
  8226. return get(paths.get(), itemValue);
  8227. };
  8228. var getPreparedMenu = function (menuValue) {
  8229. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8230. };
  8231. var lookupMenu = function (menuValue) {
  8232. return get(menus.get(), menuValue);
  8233. };
  8234. var lookupItem = function (itemValue) {
  8235. return get(expansions.get(), itemValue);
  8236. };
  8237. var otherMenus = function (path) {
  8238. var menuValues = directory.get();
  8239. return difference(keys(menuValues), path);
  8240. };
  8241. var getPrimary = function () {
  8242. return primary.get().bind(getPreparedMenu);
  8243. };
  8244. var getMenus = function () {
  8245. return menus.get();
  8246. };
  8247. return {
  8248. setMenuBuilt: setMenuBuilt,
  8249. setContents: setContents,
  8250. expand: expand,
  8251. refresh: refresh,
  8252. collapse: collapse,
  8253. lookupMenu: lookupMenu,
  8254. lookupItem: lookupItem,
  8255. otherMenus: otherMenus,
  8256. getPrimary: getPrimary,
  8257. getMenus: getMenus,
  8258. clear: clear,
  8259. isClear: isClear,
  8260. getTriggeringPath: getTriggeringPath
  8261. };
  8262. };
  8263. var extractPreparedMenu = function (prep) {
  8264. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  8265. };
  8266. var LayeredState = {
  8267. init: init$3,
  8268. extractPreparedMenu: extractPreparedMenu
  8269. };
  8270. var make$3 = function (detail, _rawUiSpec) {
  8271. var submenuParentItems = Cell(Option.none());
  8272. var buildMenus = function (container, primaryName, menus) {
  8273. return map(menus, function (spec, name) {
  8274. var makeSketch = function () {
  8275. return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), {
  8276. value: name,
  8277. items: spec.items,
  8278. markers: detail.markers,
  8279. fakeFocus: detail.fakeFocus,
  8280. onHighlight: detail.onHighlight,
  8281. focusManager: detail.fakeFocus ? highlights() : dom()
  8282. }));
  8283. };
  8284. return name === primaryName ? {
  8285. type: 'prepared',
  8286. menu: container.getSystem().build(makeSketch())
  8287. } : {
  8288. type: 'notbuilt',
  8289. nbMenu: makeSketch
  8290. };
  8291. });
  8292. };
  8293. var layeredState = LayeredState.init();
  8294. var setup = function (container) {
  8295. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8296. var directory = toDirectory();
  8297. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8298. return layeredState.getPrimary();
  8299. };
  8300. var getItemValue = function (item) {
  8301. return Representing.getValue(item).value;
  8302. };
  8303. var getItemByValue = function (_container, menus, itemValue) {
  8304. return findMap(menus, function (menu) {
  8305. if (!menu.getSystem().isConnected()) {
  8306. return Option.none();
  8307. }
  8308. var candidates = Highlighting.getCandidates(menu);
  8309. return find$2(candidates, function (c) {
  8310. return getItemValue(c) === itemValue;
  8311. });
  8312. });
  8313. };
  8314. var toDirectory = function (_container) {
  8315. return map(detail.data.menus, function (data, _menuName) {
  8316. return bind(data.items, function (item) {
  8317. return item.type === 'separator' ? [] : [item.data.value];
  8318. });
  8319. });
  8320. };
  8321. var setActiveMenu = function (container, menu) {
  8322. Highlighting.highlight(container, menu);
  8323. Highlighting.getHighlighted(menu).orThunk(function () {
  8324. return Highlighting.getFirst(menu);
  8325. }).each(function (item) {
  8326. dispatch(container, item.element(), focusItem());
  8327. });
  8328. };
  8329. var getMenus = function (state, menuValues) {
  8330. return cat(map$1(menuValues, function (mv) {
  8331. return state.lookupMenu(mv).bind(function (prep) {
  8332. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  8333. });
  8334. }));
  8335. };
  8336. var closeOthers = function (container, state, path) {
  8337. var others = getMenus(state, state.otherMenus(path));
  8338. each$1(others, function (o) {
  8339. remove$6(o.element(), [detail.markers.backgroundMenu]);
  8340. if (!detail.stayInDom) {
  8341. Replacing.remove(container, o);
  8342. }
  8343. });
  8344. };
  8345. var getSubmenuParents = function (container) {
  8346. return submenuParentItems.get().getOrThunk(function () {
  8347. var r = {};
  8348. var items = descendants(container.element(), '.' + detail.markers.item);
  8349. var parentItems = filter$1(items, function (i) {
  8350. return get$1(i, 'aria-haspopup') === 'true';
  8351. });
  8352. each$1(parentItems, function (i) {
  8353. container.getSystem().getByDom(i).each(function (itemComp) {
  8354. var key = getItemValue(itemComp);
  8355. r[key] = itemComp;
  8356. });
  8357. });
  8358. submenuParentItems.set(Option.some(r));
  8359. return r;
  8360. });
  8361. };
  8362. var updateAriaExpansions = function (container, path) {
  8363. var parentItems = getSubmenuParents(container);
  8364. each(parentItems, function (v, k) {
  8365. var expanded = contains(path, k);
  8366. set(v.element(), 'aria-expanded', expanded);
  8367. });
  8368. };
  8369. var updateMenuPath = function (container, state, path) {
  8370. return Option.from(path[0]).bind(function (latestMenuName) {
  8371. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8372. if (menuPrep.type === 'notbuilt') {
  8373. return Option.none();
  8374. } else {
  8375. var activeMenu = menuPrep.menu;
  8376. var rest = getMenus(state, path.slice(1));
  8377. each$1(rest, function (r) {
  8378. add$2(r.element(), detail.markers.backgroundMenu);
  8379. });
  8380. if (!inBody(activeMenu.element())) {
  8381. Replacing.append(container, premade$1(activeMenu));
  8382. }
  8383. remove$6(activeMenu.element(), [detail.markers.backgroundMenu]);
  8384. setActiveMenu(container, activeMenu);
  8385. closeOthers(container, state, path);
  8386. return Option.some(activeMenu);
  8387. }
  8388. });
  8389. });
  8390. };
  8391. var ExpandHighlightDecision;
  8392. (function (ExpandHighlightDecision) {
  8393. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8394. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8395. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8396. var buildIfRequired = function (container, menuName, menuPrep) {
  8397. if (menuPrep.type === 'notbuilt') {
  8398. var menu = container.getSystem().build(menuPrep.nbMenu());
  8399. layeredState.setMenuBuilt(menuName, menu);
  8400. return menu;
  8401. } else {
  8402. return menuPrep.menu;
  8403. }
  8404. };
  8405. var expandRight = function (container, item, decision) {
  8406. if (decision === void 0) {
  8407. decision = ExpandHighlightDecision.HighlightSubmenu;
  8408. }
  8409. var value = getItemValue(item);
  8410. return layeredState.expand(value).bind(function (path) {
  8411. updateAriaExpansions(container, path);
  8412. return Option.from(path[0]).bind(function (menuName) {
  8413. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8414. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8415. if (!inBody(activeMenu.element())) {
  8416. Replacing.append(container, premade$1(activeMenu));
  8417. }
  8418. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8419. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8420. Highlighting.highlightFirst(activeMenu);
  8421. return updateMenuPath(container, layeredState, path);
  8422. } else {
  8423. Highlighting.dehighlightAll(activeMenu);
  8424. return Option.some(item);
  8425. }
  8426. });
  8427. });
  8428. });
  8429. };
  8430. var collapseLeft = function (container, item) {
  8431. var value = getItemValue(item);
  8432. return layeredState.collapse(value).bind(function (path) {
  8433. updateAriaExpansions(container, path);
  8434. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8435. detail.onCollapseMenu(container, item, activeMenu);
  8436. return activeMenu;
  8437. });
  8438. });
  8439. };
  8440. var updateView = function (container, item) {
  8441. var value = getItemValue(item);
  8442. return layeredState.refresh(value).bind(function (path) {
  8443. updateAriaExpansions(container, path);
  8444. return updateMenuPath(container, layeredState, path);
  8445. });
  8446. };
  8447. var onRight = function (container, item) {
  8448. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8449. };
  8450. var onLeft = function (container, item) {
  8451. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  8452. };
  8453. var onEscape = function (container, item) {
  8454. return collapseLeft(container, item).orThunk(function () {
  8455. return detail.onEscape(container, item).map(function () {
  8456. return container;
  8457. });
  8458. });
  8459. };
  8460. var keyOnItem = function (f) {
  8461. return function (container, simulatedEvent) {
  8462. return closest$2(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8463. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  8464. return f(container, item).map(function () {
  8465. return true;
  8466. });
  8467. });
  8468. });
  8469. };
  8470. };
  8471. var events = derive([
  8472. run(focus$4(), function (sandbox, simulatedEvent) {
  8473. var item = simulatedEvent.event().item();
  8474. layeredState.lookupItem(getItemValue(item)).each(function () {
  8475. var menu = simulatedEvent.event().menu();
  8476. Highlighting.highlight(sandbox, menu);
  8477. var value = getItemValue(simulatedEvent.event().item());
  8478. layeredState.refresh(value).each(function (path) {
  8479. return closeOthers(sandbox, layeredState, path);
  8480. });
  8481. });
  8482. }),
  8483. runOnExecute(function (component, simulatedEvent) {
  8484. var target = simulatedEvent.event().target();
  8485. component.getSystem().getByDom(target).each(function (item) {
  8486. var itemValue = getItemValue(item);
  8487. if (itemValue.indexOf('collapse-item') === 0) {
  8488. collapseLeft(component, item);
  8489. }
  8490. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8491. detail.onExecute(component, item);
  8492. }, function () {
  8493. });
  8494. });
  8495. }),
  8496. runOnAttached(function (container, _simulatedEvent) {
  8497. setup(container).each(function (primary) {
  8498. Replacing.append(container, premade$1(primary));
  8499. detail.onOpenMenu(container, primary);
  8500. if (detail.highlightImmediately) {
  8501. setActiveMenu(container, primary);
  8502. }
  8503. });
  8504. })
  8505. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8506. var item = simulatedEvent.event().item();
  8507. updateView(sandbox, item);
  8508. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8509. detail.onHover(sandbox, item);
  8510. })] : []));
  8511. var getActiveItem = function (container) {
  8512. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8513. };
  8514. var collapseMenuApi = function (container) {
  8515. getActiveItem(container).each(function (currentItem) {
  8516. collapseLeft(container, currentItem);
  8517. });
  8518. };
  8519. var highlightPrimary = function (container) {
  8520. layeredState.getPrimary().each(function (primary) {
  8521. setActiveMenu(container, primary);
  8522. });
  8523. };
  8524. var extractMenuFromContainer = function (container) {
  8525. return Option.from(container.components()[0]).filter(function (comp) {
  8526. return get$1(comp.element(), 'role') === 'menu';
  8527. });
  8528. };
  8529. var repositionMenus = function (container) {
  8530. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8531. return getActiveItem(container).bind(function (currentItem) {
  8532. var itemValue = getItemValue(currentItem);
  8533. var allMenus = values(layeredState.getMenus());
  8534. var preparedMenus = cat(map$1(allMenus, LayeredState.extractPreparedMenu));
  8535. return layeredState.getTriggeringPath(itemValue, function (v) {
  8536. return getItemByValue(container, preparedMenus, v);
  8537. });
  8538. }).map(function (triggeringPath) {
  8539. return {
  8540. primary: primary,
  8541. triggeringPath: triggeringPath
  8542. };
  8543. });
  8544. });
  8545. maybeActivePrimary.fold(function () {
  8546. extractMenuFromContainer(container).each(function (primaryMenu) {
  8547. detail.onRepositionMenu(container, primaryMenu, []);
  8548. });
  8549. }, function (_a) {
  8550. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8551. detail.onRepositionMenu(container, primary, triggeringPath);
  8552. });
  8553. };
  8554. var apis = {
  8555. collapseMenu: collapseMenuApi,
  8556. highlightPrimary: highlightPrimary,
  8557. repositionMenus: repositionMenus
  8558. };
  8559. return {
  8560. uid: detail.uid,
  8561. dom: detail.dom,
  8562. markers: detail.markers,
  8563. behaviours: augment(detail.tmenuBehaviours, [
  8564. Keying.config({
  8565. mode: 'special',
  8566. onRight: keyOnItem(onRight),
  8567. onLeft: keyOnItem(onLeft),
  8568. onEscape: keyOnItem(onEscape),
  8569. focusIn: function (container, _keyInfo) {
  8570. layeredState.getPrimary().each(function (primary) {
  8571. dispatch(container, primary.element(), focusItem());
  8572. });
  8573. }
  8574. }),
  8575. Highlighting.config({
  8576. highlightClass: detail.markers.selectedMenu,
  8577. itemClass: detail.markers.menu
  8578. }),
  8579. Composing.config({
  8580. find: function (container) {
  8581. return Highlighting.getHighlighted(container);
  8582. }
  8583. }),
  8584. Replacing.config({})
  8585. ]),
  8586. eventOrder: detail.eventOrder,
  8587. apis: apis,
  8588. events: events
  8589. };
  8590. };
  8591. var collapseItem = constant('collapse-item');
  8592. var tieredData = function (primary, menus, expansions) {
  8593. return {
  8594. primary: primary,
  8595. menus: menus,
  8596. expansions: expansions
  8597. };
  8598. };
  8599. var singleData = function (name, menu) {
  8600. return {
  8601. primary: name,
  8602. menus: wrap$1(name, menu),
  8603. expansions: {}
  8604. };
  8605. };
  8606. var collapseItem$1 = function (text) {
  8607. return {
  8608. value: generate$1(collapseItem()),
  8609. meta: { text: text }
  8610. };
  8611. };
  8612. var tieredMenu = single$2({
  8613. name: 'TieredMenu',
  8614. configFields: [
  8615. onStrictKeyboardHandler('onExecute'),
  8616. onStrictKeyboardHandler('onEscape'),
  8617. onStrictHandler('onOpenMenu'),
  8618. onStrictHandler('onOpenSubmenu'),
  8619. onHandler('onRepositionMenu'),
  8620. onHandler('onCollapseMenu'),
  8621. defaulted$1('highlightImmediately', true),
  8622. strictObjOf('data', [
  8623. strict$1('primary'),
  8624. strict$1('menus'),
  8625. strict$1('expansions')
  8626. ]),
  8627. defaulted$1('fakeFocus', false),
  8628. onHandler('onHighlight'),
  8629. onHandler('onHover'),
  8630. tieredMenuMarkers(),
  8631. strict$1('dom'),
  8632. defaulted$1('navigateOnHover', true),
  8633. defaulted$1('stayInDom', false),
  8634. field$1('tmenuBehaviours', [
  8635. Keying,
  8636. Highlighting,
  8637. Composing,
  8638. Replacing
  8639. ]),
  8640. defaulted$1('eventOrder', {})
  8641. ],
  8642. apis: {
  8643. collapseMenu: function (apis, tmenu) {
  8644. apis.collapseMenu(tmenu);
  8645. },
  8646. highlightPrimary: function (apis, tmenu) {
  8647. apis.highlightPrimary(tmenu);
  8648. },
  8649. repositionMenus: function (apis, tmenu) {
  8650. apis.repositionMenus(tmenu);
  8651. }
  8652. },
  8653. factory: make$3,
  8654. extraApis: {
  8655. tieredData: tieredData,
  8656. singleData: singleData,
  8657. collapseItem: collapseItem$1
  8658. }
  8659. });
  8660. var findRoute = function (component, transConfig, transState, route) {
  8661. return get(transConfig.routes, route.start).bind(function (sConfig) {
  8662. return get(sConfig, route.destination);
  8663. });
  8664. };
  8665. var getTransition = function (comp, transConfig, transState) {
  8666. var route = getCurrentRoute(comp, transConfig);
  8667. return route.bind(function (r) {
  8668. return getTransitionOf(comp, transConfig, transState, r);
  8669. });
  8670. };
  8671. var getTransitionOf = function (comp, transConfig, transState, route) {
  8672. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8673. return r.transition.map(function (t) {
  8674. return {
  8675. transition: t,
  8676. route: r
  8677. };
  8678. });
  8679. });
  8680. };
  8681. var disableTransition = function (comp, transConfig, transState) {
  8682. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8683. var t = routeTransition.transition;
  8684. remove$4(comp.element(), t.transitionClass);
  8685. remove$1(comp.element(), transConfig.destinationAttr);
  8686. });
  8687. };
  8688. var getNewRoute = function (comp, transConfig, transState, destination) {
  8689. return {
  8690. start: get$1(comp.element(), transConfig.stateAttr),
  8691. destination: destination
  8692. };
  8693. };
  8694. var getCurrentRoute = function (comp, transConfig, _transState) {
  8695. var el = comp.element();
  8696. return getOpt(el, transConfig.destinationAttr).map(function (destination) {
  8697. return {
  8698. start: get$1(comp.element(), transConfig.stateAttr),
  8699. destination: destination
  8700. };
  8701. });
  8702. };
  8703. var jumpTo = function (comp, transConfig, transState, destination) {
  8704. disableTransition(comp, transConfig, transState);
  8705. if (has$1(comp.element(), transConfig.stateAttr) && get$1(comp.element(), transConfig.stateAttr) !== destination) {
  8706. transConfig.onFinish(comp, destination);
  8707. }
  8708. set(comp.element(), transConfig.stateAttr, destination);
  8709. };
  8710. var fasttrack = function (comp, transConfig, _transState, _destination) {
  8711. if (has$1(comp.element(), transConfig.destinationAttr)) {
  8712. getOpt(comp.element(), transConfig.destinationAttr).each(function (destination) {
  8713. set(comp.element(), transConfig.stateAttr, destination);
  8714. });
  8715. remove$1(comp.element(), transConfig.destinationAttr);
  8716. }
  8717. };
  8718. var progressTo = function (comp, transConfig, transState, destination) {
  8719. fasttrack(comp, transConfig);
  8720. var route = getNewRoute(comp, transConfig, transState, destination);
  8721. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8722. jumpTo(comp, transConfig, transState, destination);
  8723. }, function (routeTransition) {
  8724. disableTransition(comp, transConfig, transState);
  8725. var t = routeTransition.transition;
  8726. add$2(comp.element(), t.transitionClass);
  8727. set(comp.element(), transConfig.destinationAttr, destination);
  8728. });
  8729. };
  8730. var getState$1 = function (comp, transConfig, _transState) {
  8731. return getOpt(comp.element(), transConfig.stateAttr);
  8732. };
  8733. var TransitionApis = /*#__PURE__*/Object.freeze({
  8734. __proto__: null,
  8735. findRoute: findRoute,
  8736. disableTransition: disableTransition,
  8737. getCurrentRoute: getCurrentRoute,
  8738. jumpTo: jumpTo,
  8739. progressTo: progressTo,
  8740. getState: getState$1
  8741. });
  8742. var events$9 = function (transConfig, transState) {
  8743. return derive([
  8744. run(transitionend(), function (component, simulatedEvent) {
  8745. var raw = simulatedEvent.event().raw();
  8746. getCurrentRoute(component, transConfig).each(function (route) {
  8747. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8748. rInfo.transition.each(function (rTransition) {
  8749. if (raw.propertyName === rTransition.property) {
  8750. jumpTo(component, transConfig, transState, route.destination);
  8751. transConfig.onTransition(component, route);
  8752. }
  8753. });
  8754. });
  8755. });
  8756. }),
  8757. runOnAttached(function (comp, _se) {
  8758. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8759. })
  8760. ]);
  8761. };
  8762. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8763. __proto__: null,
  8764. events: events$9
  8765. });
  8766. var TransitionSchema = [
  8767. defaulted$1('destinationAttr', 'data-transitioning-destination'),
  8768. defaulted$1('stateAttr', 'data-transitioning-state'),
  8769. strict$1('initialState'),
  8770. onHandler('onTransition'),
  8771. onHandler('onFinish'),
  8772. strictOf('routes', setOf$1(Result.value, setOf$1(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8773. strict$1('property'),
  8774. strict$1('transitionClass')
  8775. ])]))))
  8776. ];
  8777. var createRoutes = function (routes) {
  8778. var r = {};
  8779. each(routes, function (v, k) {
  8780. var waypoints = k.split('<->');
  8781. r[waypoints[0]] = wrap$1(waypoints[1], v);
  8782. r[waypoints[1]] = wrap$1(waypoints[0], v);
  8783. });
  8784. return r;
  8785. };
  8786. var createBistate = function (first, second, transitions) {
  8787. return wrapAll$1([
  8788. {
  8789. key: first,
  8790. value: wrap$1(second, transitions)
  8791. },
  8792. {
  8793. key: second,
  8794. value: wrap$1(first, transitions)
  8795. }
  8796. ]);
  8797. };
  8798. var createTristate = function (first, second, third, transitions) {
  8799. return wrapAll$1([
  8800. {
  8801. key: first,
  8802. value: wrapAll$1([
  8803. {
  8804. key: second,
  8805. value: transitions
  8806. },
  8807. {
  8808. key: third,
  8809. value: transitions
  8810. }
  8811. ])
  8812. },
  8813. {
  8814. key: second,
  8815. value: wrapAll$1([
  8816. {
  8817. key: first,
  8818. value: transitions
  8819. },
  8820. {
  8821. key: third,
  8822. value: transitions
  8823. }
  8824. ])
  8825. },
  8826. {
  8827. key: third,
  8828. value: wrapAll$1([
  8829. {
  8830. key: first,
  8831. value: transitions
  8832. },
  8833. {
  8834. key: second,
  8835. value: transitions
  8836. }
  8837. ])
  8838. }
  8839. ]);
  8840. };
  8841. var Transitioning = create$1({
  8842. fields: TransitionSchema,
  8843. name: 'transitioning',
  8844. active: ActiveTransitioning,
  8845. apis: TransitionApis,
  8846. extra: {
  8847. createRoutes: createRoutes,
  8848. createBistate: createBistate,
  8849. createTristate: createTristate
  8850. }
  8851. });
  8852. var scrollableStyle = resolve('scrollable');
  8853. var register = function (element) {
  8854. add$2(element, scrollableStyle);
  8855. };
  8856. var deregister = function (element) {
  8857. remove$4(element, scrollableStyle);
  8858. };
  8859. var scrollable = scrollableStyle;
  8860. var getValue$4 = function (item) {
  8861. return get(item, 'format').getOr(item.title);
  8862. };
  8863. var convert$1 = function (formats, memMenuThunk) {
  8864. var mainMenu = makeMenu('Styles', [].concat(map$1(formats.items, function (k) {
  8865. return makeItem(getValue$4(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue$4(k)));
  8866. })), memMenuThunk, false);
  8867. var submenus = map(formats.menus, function (menuItems, menuName) {
  8868. var items = map$1(menuItems, function (item) {
  8869. return makeItem(getValue$4(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue$4(item)));
  8870. });
  8871. return makeMenu(menuName, items, memMenuThunk, true);
  8872. });
  8873. var menus = deepMerge(submenus, wrap$1('styles', mainMenu));
  8874. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  8875. return { tmenu: tmenu };
  8876. };
  8877. var makeItem = function (value, text, selected, preview, isMenu) {
  8878. return {
  8879. data: {
  8880. value: value,
  8881. text: text
  8882. },
  8883. type: 'item',
  8884. dom: {
  8885. tag: 'div',
  8886. classes: isMenu ? [resolve('styles-item-is-menu')] : []
  8887. },
  8888. toggling: {
  8889. toggleOnExecute: false,
  8890. toggleClass: resolve('format-matches'),
  8891. selected: selected
  8892. },
  8893. itemBehaviours: derive$1(isMenu ? [] : [format(value, function (comp, status) {
  8894. var toggle = status ? Toggling.on : Toggling.off;
  8895. toggle(comp);
  8896. })]),
  8897. components: [{
  8898. dom: {
  8899. tag: 'div',
  8900. attributes: { style: preview },
  8901. innerHtml: text
  8902. }
  8903. }]
  8904. };
  8905. };
  8906. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  8907. return {
  8908. value: value,
  8909. dom: { tag: 'div' },
  8910. components: [
  8911. Button.sketch({
  8912. dom: {
  8913. tag: 'div',
  8914. classes: [resolve('styles-collapser')]
  8915. },
  8916. components: collapsable ? [
  8917. {
  8918. dom: {
  8919. tag: 'span',
  8920. classes: [resolve('styles-collapse-icon')]
  8921. }
  8922. },
  8923. text(value)
  8924. ] : [text(value)],
  8925. action: function (item) {
  8926. if (collapsable) {
  8927. var comp = memMenuThunk().get(item);
  8928. tieredMenu.collapseMenu(comp);
  8929. }
  8930. }
  8931. }),
  8932. {
  8933. dom: {
  8934. tag: 'div',
  8935. classes: [resolve('styles-menu-items-container')]
  8936. },
  8937. components: [Menu.parts().items({})],
  8938. behaviours: derive$1([config('adhoc-scrollable-menu', [
  8939. runOnAttached(function (component, _simulatedEvent) {
  8940. set$3(component.element(), 'overflow-y', 'auto');
  8941. set$3(component.element(), '-webkit-overflow-scrolling', 'touch');
  8942. register(component.element());
  8943. }),
  8944. runOnDetached(function (component) {
  8945. remove$5(component.element(), 'overflow-y');
  8946. remove$5(component.element(), '-webkit-overflow-scrolling');
  8947. deregister(component.element());
  8948. })
  8949. ])])
  8950. }
  8951. ],
  8952. items: items,
  8953. menuBehaviours: derive$1([Transitioning.config({
  8954. initialState: 'after',
  8955. routes: Transitioning.createTristate('before', 'current', 'after', {
  8956. transition: {
  8957. property: 'transform',
  8958. transitionClass: 'transitioning'
  8959. }
  8960. })
  8961. })])
  8962. };
  8963. };
  8964. var sketch$8 = function (settings) {
  8965. var dataset = convert$1(settings.formats, function () {
  8966. return memMenu;
  8967. });
  8968. var memMenu = record(tieredMenu.sketch({
  8969. dom: {
  8970. tag: 'div',
  8971. classes: [resolve('styles-menu')]
  8972. },
  8973. components: [],
  8974. fakeFocus: true,
  8975. stayInDom: true,
  8976. onExecute: function (_tmenu, item) {
  8977. var v = Representing.getValue(item);
  8978. settings.handle(item, v.value);
  8979. return Option.none();
  8980. },
  8981. onEscape: function () {
  8982. return Option.none();
  8983. },
  8984. onOpenMenu: function (container, menu) {
  8985. var w = get$7(container.element());
  8986. set$4(menu.element(), w);
  8987. Transitioning.jumpTo(menu, 'current');
  8988. },
  8989. onOpenSubmenu: function (container, item, submenu) {
  8990. var w = get$7(container.element());
  8991. var menu = ancestor$2(item.element(), '[role="menu"]').getOrDie('hacky');
  8992. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  8993. set$4(submenu.element(), w);
  8994. Transitioning.progressTo(menuComp, 'before');
  8995. Transitioning.jumpTo(submenu, 'after');
  8996. Transitioning.progressTo(submenu, 'current');
  8997. },
  8998. onCollapseMenu: function (container, item, menu) {
  8999. var submenu = ancestor$2(item.element(), '[role="menu"]').getOrDie('hacky');
  9000. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9001. Transitioning.progressTo(submenuComp, 'after');
  9002. Transitioning.progressTo(menu, 'current');
  9003. },
  9004. navigateOnHover: false,
  9005. highlightImmediately: true,
  9006. data: dataset.tmenu,
  9007. markers: {
  9008. backgroundMenu: resolve('styles-background-menu'),
  9009. menu: resolve('styles-menu'),
  9010. selectedMenu: resolve('styles-selected-menu'),
  9011. item: resolve('styles-item'),
  9012. selectedItem: resolve('styles-selected-item')
  9013. }
  9014. }));
  9015. return memMenu.asSpec();
  9016. };
  9017. var getFromExpandingItem = function (item) {
  9018. var newItem = deepMerge(exclude$1(item, ['items']), { menu: true });
  9019. var rest = expand(item.items);
  9020. var newMenus = deepMerge(rest.menus, wrap$1(item.title, rest.items));
  9021. var newExpansions = deepMerge(rest.expansions, wrap$1(item.title, item.title));
  9022. return {
  9023. item: newItem,
  9024. menus: newMenus,
  9025. expansions: newExpansions
  9026. };
  9027. };
  9028. var getFromItem = function (item) {
  9029. return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : {
  9030. item: item,
  9031. menus: {},
  9032. expansions: {}
  9033. };
  9034. };
  9035. var expand = function (items) {
  9036. return foldr(items, function (acc, item) {
  9037. var newData = getFromItem(item);
  9038. return {
  9039. menus: deepMerge(acc.menus, newData.menus),
  9040. items: [newData.item].concat(acc.items),
  9041. expansions: deepMerge(acc.expansions, newData.expansions)
  9042. };
  9043. }, {
  9044. menus: {},
  9045. expansions: {},
  9046. items: []
  9047. });
  9048. };
  9049. var register$1 = function (editor, settings) {
  9050. var isSelectedFor = function (format) {
  9051. return function () {
  9052. return editor.formatter.match(format);
  9053. };
  9054. };
  9055. var getPreview = function (format) {
  9056. return function () {
  9057. return editor.formatter.getCssText(format);
  9058. };
  9059. };
  9060. var enrichSupported = function (item) {
  9061. return deepMerge(item, {
  9062. isSelected: isSelectedFor(item.format),
  9063. getPreview: getPreview(item.format)
  9064. });
  9065. };
  9066. var enrichMenu = function (item) {
  9067. return deepMerge(item, {
  9068. isSelected: constant(false),
  9069. getPreview: constant('')
  9070. });
  9071. };
  9072. var enrichCustom = function (item) {
  9073. var formatName = generate$1(item.title);
  9074. var newItem = deepMerge(item, {
  9075. format: formatName,
  9076. isSelected: isSelectedFor(formatName),
  9077. getPreview: getPreview(formatName)
  9078. });
  9079. editor.formatter.register(formatName, newItem);
  9080. return newItem;
  9081. };
  9082. var formats = get(settings, 'style_formats').getOr(DefaultStyleFormats);
  9083. var doEnrich = function (items) {
  9084. return map$1(items, function (item) {
  9085. if (hasNonNullableKey(item, 'items')) {
  9086. var newItems = doEnrich(item.items);
  9087. return deepMerge(enrichMenu(item), { items: newItems });
  9088. } else if (hasNonNullableKey(item, 'format')) {
  9089. return enrichSupported(item);
  9090. } else {
  9091. return enrichCustom(item);
  9092. }
  9093. });
  9094. };
  9095. return doEnrich(formats);
  9096. };
  9097. var prune = function (editor, formats) {
  9098. var doPrune = function (items) {
  9099. return bind(items, function (item) {
  9100. if (item.items !== undefined) {
  9101. var newItems = doPrune(item.items);
  9102. return newItems.length > 0 ? [item] : [];
  9103. } else {
  9104. var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9105. return keep ? [item] : [];
  9106. }
  9107. });
  9108. };
  9109. var prunedItems = doPrune(formats);
  9110. return expand(prunedItems);
  9111. };
  9112. var ui = function (editor, formats, onDone) {
  9113. var pruned = prune(editor, formats);
  9114. return sketch$8({
  9115. formats: pruned,
  9116. handle: function (item, value) {
  9117. editor.undoManager.transact(function () {
  9118. if (Toggling.isOn(item)) {
  9119. editor.formatter.remove(value);
  9120. } else {
  9121. editor.formatter.apply(value);
  9122. }
  9123. });
  9124. onDone();
  9125. }
  9126. });
  9127. };
  9128. var defaults = [
  9129. 'undo',
  9130. 'bold',
  9131. 'italic',
  9132. 'link',
  9133. 'image',
  9134. 'bullist',
  9135. 'styleselect'
  9136. ];
  9137. var extract$1 = function (rawToolbar) {
  9138. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9139. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9140. };
  9141. var identifyFromArray = function (toolbar) {
  9142. return bind(toolbar, function (item) {
  9143. return isArray(item) ? identifyFromArray(item) : extract$1(item);
  9144. });
  9145. };
  9146. var identify = function (settings) {
  9147. var toolbar = settings.toolbar !== undefined ? settings.toolbar : defaults;
  9148. return isArray(toolbar) ? identifyFromArray(toolbar) : extract$1(toolbar);
  9149. };
  9150. var setup = function (realm, editor) {
  9151. var commandSketch = function (name) {
  9152. return function () {
  9153. return forToolbarCommand(editor, name);
  9154. };
  9155. };
  9156. var stateCommandSketch = function (name) {
  9157. return function () {
  9158. return forToolbarStateCommand(editor, name);
  9159. };
  9160. };
  9161. var actionSketch = function (name, query, action) {
  9162. return function () {
  9163. return forToolbarStateAction(editor, name, query, action);
  9164. };
  9165. };
  9166. var undo = commandSketch('undo');
  9167. var redo = commandSketch('redo');
  9168. var bold = stateCommandSketch('bold');
  9169. var italic = stateCommandSketch('italic');
  9170. var underline = stateCommandSketch('underline');
  9171. var removeformat = commandSketch('removeformat');
  9172. var link = function () {
  9173. return sketch$7(realm, editor);
  9174. };
  9175. var unlink = actionSketch('unlink', 'link', function () {
  9176. editor.execCommand('unlink', null, false);
  9177. });
  9178. var image = function () {
  9179. return sketch$4(editor);
  9180. };
  9181. var bullist = actionSketch('unordered-list', 'ul', function () {
  9182. editor.execCommand('InsertUnorderedList', null, false);
  9183. });
  9184. var numlist = actionSketch('ordered-list', 'ol', function () {
  9185. editor.execCommand('InsertOrderedList', null, false);
  9186. });
  9187. var fontsizeselect = function () {
  9188. return sketch$3(realm, editor);
  9189. };
  9190. var forecolor = function () {
  9191. return sketch$1(realm, editor);
  9192. };
  9193. var styleFormats = register$1(editor, editor.settings);
  9194. var styleFormatsMenu = function () {
  9195. return ui(editor, styleFormats, function () {
  9196. editor.fire('scrollIntoView');
  9197. });
  9198. };
  9199. var styleselect = function () {
  9200. return forToolbar('style-formats', function (button) {
  9201. editor.fire('toReading');
  9202. realm.dropup().appear(styleFormatsMenu, Toggling.on, button);
  9203. }, derive$1([
  9204. Toggling.config({
  9205. toggleClass: resolve('toolbar-button-selected'),
  9206. toggleOnExecute: false,
  9207. aria: { mode: 'pressed' }
  9208. }),
  9209. Receiving.config({
  9210. channels: wrapAll$1([
  9211. receive$1(orientationChanged, Toggling.off),
  9212. receive$1(dropupDismissed, Toggling.off)
  9213. ])
  9214. })
  9215. ]), editor);
  9216. };
  9217. var feature = function (prereq, sketch) {
  9218. return {
  9219. isSupported: function () {
  9220. var buttons = editor.ui.registry.getAll().buttons;
  9221. return prereq.forall(function (p) {
  9222. return hasNonNullableKey(buttons, p);
  9223. });
  9224. },
  9225. sketch: sketch
  9226. };
  9227. };
  9228. return {
  9229. undo: feature(Option.none(), undo),
  9230. redo: feature(Option.none(), redo),
  9231. bold: feature(Option.none(), bold),
  9232. italic: feature(Option.none(), italic),
  9233. underline: feature(Option.none(), underline),
  9234. removeformat: feature(Option.none(), removeformat),
  9235. link: feature(Option.none(), link),
  9236. unlink: feature(Option.none(), unlink),
  9237. image: feature(Option.none(), image),
  9238. bullist: feature(Option.some('bullist'), bullist),
  9239. numlist: feature(Option.some('numlist'), numlist),
  9240. fontsizeselect: feature(Option.none(), fontsizeselect),
  9241. forecolor: feature(Option.none(), forecolor),
  9242. styleselect: feature(Option.none(), styleselect)
  9243. };
  9244. };
  9245. var detect$4 = function (settings, features) {
  9246. var itemNames = identify(settings);
  9247. var present = {};
  9248. return bind(itemNames, function (iName) {
  9249. var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9250. present[iName] = true;
  9251. return r;
  9252. });
  9253. };
  9254. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9255. return {
  9256. target: constant(target),
  9257. x: constant(x),
  9258. y: constant(y),
  9259. stop: stop,
  9260. prevent: prevent,
  9261. kill: kill,
  9262. raw: constant(raw)
  9263. };
  9264. };
  9265. var fromRawEvent = function (rawEvent) {
  9266. var target = Element.fromDom(rawEvent.target);
  9267. var stop = function () {
  9268. return rawEvent.stopPropagation();
  9269. };
  9270. var prevent = function () {
  9271. return rawEvent.preventDefault();
  9272. };
  9273. var kill = compose(prevent, stop);
  9274. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9275. };
  9276. var handle = function (filter, handler) {
  9277. return function (rawEvent) {
  9278. if (filter(rawEvent)) {
  9279. handler(fromRawEvent(rawEvent));
  9280. }
  9281. };
  9282. };
  9283. var binder = function (element, event, filter, handler, useCapture) {
  9284. var wrapped = handle(filter, handler);
  9285. element.dom().addEventListener(event, wrapped, useCapture);
  9286. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9287. };
  9288. var bind$2 = function (element, event, filter, handler) {
  9289. return binder(element, event, filter, handler, false);
  9290. };
  9291. var capture = function (element, event, filter, handler) {
  9292. return binder(element, event, filter, handler, true);
  9293. };
  9294. var unbind = function (element, event, handler, useCapture) {
  9295. element.dom().removeEventListener(event, handler, useCapture);
  9296. };
  9297. var filter$2 = constant(true);
  9298. var bind$3 = function (element, event, handler) {
  9299. return bind$2(element, event, filter$2, handler);
  9300. };
  9301. var capture$1 = function (element, event, handler) {
  9302. return capture(element, event, filter$2, handler);
  9303. };
  9304. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9305. var INTERVAL = 50;
  9306. var INSURANCE = 1000 / INTERVAL;
  9307. var get$b = function (outerWindow) {
  9308. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9309. return { isPortrait: constant(isPortrait) };
  9310. };
  9311. var getActualWidth = function (outerWindow) {
  9312. var isIos = detect$3().os.isiOS();
  9313. var isPortrait = get$b(outerWindow).isPortrait();
  9314. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9315. };
  9316. var onChange = function (outerWindow, listeners) {
  9317. var win = Element.fromDom(outerWindow);
  9318. var poller = null;
  9319. var change = function () {
  9320. global$4.clearInterval(poller);
  9321. var orientation = get$b(outerWindow);
  9322. listeners.onChange(orientation);
  9323. onAdjustment(function () {
  9324. listeners.onReady(orientation);
  9325. });
  9326. };
  9327. var orientationHandle = bind$3(win, 'orientationchange', change);
  9328. var onAdjustment = function (f) {
  9329. global$4.clearInterval(poller);
  9330. var flag = outerWindow.innerHeight;
  9331. var insurance = 0;
  9332. poller = global$4.setInterval(function () {
  9333. if (flag !== outerWindow.innerHeight) {
  9334. global$4.clearInterval(poller);
  9335. f(Option.some(outerWindow.innerHeight));
  9336. } else if (insurance > INSURANCE) {
  9337. global$4.clearInterval(poller);
  9338. f(Option.none());
  9339. }
  9340. insurance++;
  9341. }, INTERVAL);
  9342. };
  9343. var destroy = function () {
  9344. orientationHandle.unbind();
  9345. };
  9346. return {
  9347. onAdjustment: onAdjustment,
  9348. destroy: destroy
  9349. };
  9350. };
  9351. function DelayedFunction (fun, delay) {
  9352. var ref = null;
  9353. var schedule = function () {
  9354. var args = [];
  9355. for (var _i = 0; _i < arguments.length; _i++) {
  9356. args[_i] = arguments[_i];
  9357. }
  9358. ref = domGlobals.setTimeout(function () {
  9359. fun.apply(null, args);
  9360. ref = null;
  9361. }, delay);
  9362. };
  9363. var cancel = function () {
  9364. if (ref !== null) {
  9365. domGlobals.clearTimeout(ref);
  9366. ref = null;
  9367. }
  9368. };
  9369. return {
  9370. cancel: cancel,
  9371. schedule: schedule
  9372. };
  9373. }
  9374. var SIGNIFICANT_MOVE = 5;
  9375. var LONGPRESS_DELAY = 400;
  9376. var getTouch = function (event) {
  9377. var raw = event.raw();
  9378. if (raw.touches === undefined || raw.touches.length !== 1) {
  9379. return Option.none();
  9380. }
  9381. return Option.some(raw.touches[0]);
  9382. };
  9383. var isFarEnough = function (touch, data) {
  9384. var distX = Math.abs(touch.clientX - data.x);
  9385. var distY = Math.abs(touch.clientY - data.y);
  9386. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  9387. };
  9388. var monitor = function (settings) {
  9389. var startData = Cell(Option.none());
  9390. var longpressFired = Cell(false);
  9391. var longpress$1 = DelayedFunction(function (event) {
  9392. settings.triggerEvent(longpress(), event);
  9393. longpressFired.set(true);
  9394. }, LONGPRESS_DELAY);
  9395. var handleTouchstart = function (event) {
  9396. getTouch(event).each(function (touch) {
  9397. longpress$1.cancel();
  9398. var data = {
  9399. x: touch.clientX,
  9400. y: touch.clientY,
  9401. target: event.target()
  9402. };
  9403. longpress$1.schedule(event);
  9404. longpressFired.set(false);
  9405. startData.set(Option.some(data));
  9406. });
  9407. return Option.none();
  9408. };
  9409. var handleTouchmove = function (event) {
  9410. longpress$1.cancel();
  9411. getTouch(event).each(function (touch) {
  9412. startData.get().each(function (data) {
  9413. if (isFarEnough(touch, data)) {
  9414. startData.set(Option.none());
  9415. }
  9416. });
  9417. });
  9418. return Option.none();
  9419. };
  9420. var handleTouchend = function (event) {
  9421. longpress$1.cancel();
  9422. var isSame = function (data) {
  9423. return eq(data.target, event.target());
  9424. };
  9425. return startData.get().filter(isSame).map(function (_data) {
  9426. if (longpressFired.get()) {
  9427. event.prevent();
  9428. return false;
  9429. } else {
  9430. return settings.triggerEvent(tap(), event);
  9431. }
  9432. });
  9433. };
  9434. var handlers = wrapAll$1([
  9435. {
  9436. key: touchstart(),
  9437. value: handleTouchstart
  9438. },
  9439. {
  9440. key: touchmove(),
  9441. value: handleTouchmove
  9442. },
  9443. {
  9444. key: touchend(),
  9445. value: handleTouchend
  9446. }
  9447. ]);
  9448. var fireIfReady = function (event, type) {
  9449. return get(handlers, type).bind(function (handler) {
  9450. return handler(event);
  9451. });
  9452. };
  9453. return { fireIfReady: fireIfReady };
  9454. };
  9455. var monitor$1 = function (editorApi) {
  9456. var tapEvent = monitor({
  9457. triggerEvent: function (type, evt) {
  9458. editorApi.onTapContent(evt);
  9459. }
  9460. });
  9461. var onTouchend = function () {
  9462. return bind$3(editorApi.body(), 'touchend', function (evt) {
  9463. tapEvent.fireIfReady(evt, 'touchend');
  9464. });
  9465. };
  9466. var onTouchmove = function () {
  9467. return bind$3(editorApi.body(), 'touchmove', function (evt) {
  9468. tapEvent.fireIfReady(evt, 'touchmove');
  9469. });
  9470. };
  9471. var fireTouchstart = function (evt) {
  9472. tapEvent.fireIfReady(evt, 'touchstart');
  9473. };
  9474. return {
  9475. fireTouchstart: fireTouchstart,
  9476. onTouchend: onTouchend,
  9477. onTouchmove: onTouchmove
  9478. };
  9479. };
  9480. var isAndroid6 = detect$3().os.version.major >= 6;
  9481. var initEvents = function (editorApi, toolstrip, alloy) {
  9482. var tapping = monitor$1(editorApi);
  9483. var outerDoc = owner(toolstrip);
  9484. var isRanged = function (sel) {
  9485. return !eq(sel.start(), sel.finish()) || sel.soffset() !== sel.foffset();
  9486. };
  9487. var hasRangeInUi = function () {
  9488. return active(outerDoc).filter(function (input) {
  9489. return name(input) === 'input';
  9490. }).exists(function (input) {
  9491. return input.dom().selectionStart !== input.dom().selectionEnd;
  9492. });
  9493. };
  9494. var updateMargin = function () {
  9495. var rangeInContent = editorApi.doc().dom().hasFocus() && editorApi.getSelection().exists(isRanged);
  9496. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  9497. };
  9498. var listeners = [
  9499. bind$3(editorApi.body(), 'touchstart', function (evt) {
  9500. editorApi.onTouchContent();
  9501. tapping.fireTouchstart(evt);
  9502. }),
  9503. tapping.onTouchmove(),
  9504. tapping.onTouchend(),
  9505. bind$3(toolstrip, 'touchstart', function (_evt) {
  9506. editorApi.onTouchToolstrip();
  9507. }),
  9508. editorApi.onToReading(function () {
  9509. blur(editorApi.body());
  9510. }),
  9511. editorApi.onToEditing(noop),
  9512. editorApi.onScrollToCursor(function (tinyEvent) {
  9513. tinyEvent.preventDefault();
  9514. editorApi.getCursorBox().each(function (bounds) {
  9515. var cWin = editorApi.win();
  9516. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  9517. var cScrollBy = isOutside ? bounds.bottom() - cWin.innerHeight + 50 : 0;
  9518. if (cScrollBy !== 0) {
  9519. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  9520. }
  9521. });
  9522. })
  9523. ].concat(isAndroid6 === true ? [] : [
  9524. bind$3(Element.fromDom(editorApi.win()), 'blur', function () {
  9525. alloy.getByDom(toolstrip).each(Toggling.off);
  9526. }),
  9527. bind$3(outerDoc, 'select', updateMargin),
  9528. bind$3(editorApi.doc(), 'selectionchange', updateMargin)
  9529. ]);
  9530. var destroy = function () {
  9531. each$1(listeners, function (l) {
  9532. l.unbind();
  9533. });
  9534. };
  9535. return { destroy: destroy };
  9536. };
  9537. var safeParse = function (element, attribute) {
  9538. var parsed = parseInt(get$1(element, attribute), 10);
  9539. return isNaN(parsed) ? 0 : parsed;
  9540. };
  9541. function NodeValue (is, name) {
  9542. var get = function (element) {
  9543. if (!is(element)) {
  9544. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9545. }
  9546. return getOption(element).getOr('');
  9547. };
  9548. var getOption = function (element) {
  9549. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  9550. };
  9551. var set = function (element, value) {
  9552. if (!is(element)) {
  9553. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9554. }
  9555. element.dom().nodeValue = value;
  9556. };
  9557. return {
  9558. get: get,
  9559. getOption: getOption,
  9560. set: set
  9561. };
  9562. }
  9563. var api$3 = NodeValue(isText, 'text');
  9564. var getOption = function (element) {
  9565. return api$3.getOption(element);
  9566. };
  9567. var getEnd = function (element) {
  9568. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  9569. return children(element).length;
  9570. }, function (v) {
  9571. return v.length;
  9572. });
  9573. };
  9574. var create$3 = function (start, soffset, finish, foffset) {
  9575. return {
  9576. start: constant(start),
  9577. soffset: constant(soffset),
  9578. finish: constant(finish),
  9579. foffset: constant(foffset)
  9580. };
  9581. };
  9582. var SimRange = { create: create$3 };
  9583. var adt$4 = Adt.generate([
  9584. { before: ['element'] },
  9585. {
  9586. on: [
  9587. 'element',
  9588. 'offset'
  9589. ]
  9590. },
  9591. { after: ['element'] }
  9592. ]);
  9593. var cata = function (subject, onBefore, onOn, onAfter) {
  9594. return subject.fold(onBefore, onOn, onAfter);
  9595. };
  9596. var getStart = function (situ) {
  9597. return situ.fold(identity, identity, identity);
  9598. };
  9599. var before$1 = adt$4.before;
  9600. var on$1 = adt$4.on;
  9601. var after$1 = adt$4.after;
  9602. var Situ = {
  9603. before: before$1,
  9604. on: on$1,
  9605. after: after$1,
  9606. cata: cata,
  9607. getStart: getStart
  9608. };
  9609. var adt$5 = Adt.generate([
  9610. { domRange: ['rng'] },
  9611. {
  9612. relative: [
  9613. 'startSitu',
  9614. 'finishSitu'
  9615. ]
  9616. },
  9617. {
  9618. exact: [
  9619. 'start',
  9620. 'soffset',
  9621. 'finish',
  9622. 'foffset'
  9623. ]
  9624. }
  9625. ]);
  9626. var exactFromRange = function (simRange) {
  9627. return adt$5.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  9628. };
  9629. var getStart$1 = function (selection) {
  9630. return selection.match({
  9631. domRange: function (rng) {
  9632. return Element.fromDom(rng.startContainer);
  9633. },
  9634. relative: function (startSitu, _finishSitu) {
  9635. return Situ.getStart(startSitu);
  9636. },
  9637. exact: function (start, _soffset, _finish, _foffset) {
  9638. return start;
  9639. }
  9640. });
  9641. };
  9642. var domRange = adt$5.domRange;
  9643. var relative = adt$5.relative;
  9644. var exact = adt$5.exact;
  9645. var getWin = function (selection) {
  9646. var start = getStart$1(selection);
  9647. return defaultView(start);
  9648. };
  9649. var range$1 = SimRange.create;
  9650. var Selection = {
  9651. domRange: domRange,
  9652. relative: relative,
  9653. exact: exact,
  9654. exactFromRange: exactFromRange,
  9655. getWin: getWin,
  9656. range: range$1
  9657. };
  9658. var setStart = function (rng, situ) {
  9659. situ.fold(function (e) {
  9660. rng.setStartBefore(e.dom());
  9661. }, function (e, o) {
  9662. rng.setStart(e.dom(), o);
  9663. }, function (e) {
  9664. rng.setStartAfter(e.dom());
  9665. });
  9666. };
  9667. var setFinish = function (rng, situ) {
  9668. situ.fold(function (e) {
  9669. rng.setEndBefore(e.dom());
  9670. }, function (e, o) {
  9671. rng.setEnd(e.dom(), o);
  9672. }, function (e) {
  9673. rng.setEndAfter(e.dom());
  9674. });
  9675. };
  9676. var relativeToNative = function (win, startSitu, finishSitu) {
  9677. var range = win.document.createRange();
  9678. setStart(range, startSitu);
  9679. setFinish(range, finishSitu);
  9680. return range;
  9681. };
  9682. var exactToNative = function (win, start, soffset, finish, foffset) {
  9683. var rng = win.document.createRange();
  9684. rng.setStart(start.dom(), soffset);
  9685. rng.setEnd(finish.dom(), foffset);
  9686. return rng;
  9687. };
  9688. var toRect = function (rect) {
  9689. return {
  9690. left: constant(rect.left),
  9691. top: constant(rect.top),
  9692. right: constant(rect.right),
  9693. bottom: constant(rect.bottom),
  9694. width: constant(rect.width),
  9695. height: constant(rect.height)
  9696. };
  9697. };
  9698. var getFirstRect = function (rng) {
  9699. var rects = rng.getClientRects();
  9700. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9701. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  9702. };
  9703. var adt$6 = Adt.generate([
  9704. {
  9705. ltr: [
  9706. 'start',
  9707. 'soffset',
  9708. 'finish',
  9709. 'foffset'
  9710. ]
  9711. },
  9712. {
  9713. rtl: [
  9714. 'start',
  9715. 'soffset',
  9716. 'finish',
  9717. 'foffset'
  9718. ]
  9719. }
  9720. ]);
  9721. var fromRange = function (win, type, range) {
  9722. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  9723. };
  9724. var getRanges = function (win, selection) {
  9725. return selection.match({
  9726. domRange: function (rng) {
  9727. return {
  9728. ltr: constant(rng),
  9729. rtl: Option.none
  9730. };
  9731. },
  9732. relative: function (startSitu, finishSitu) {
  9733. return {
  9734. ltr: cached(function () {
  9735. return relativeToNative(win, startSitu, finishSitu);
  9736. }),
  9737. rtl: cached(function () {
  9738. return Option.some(relativeToNative(win, finishSitu, startSitu));
  9739. })
  9740. };
  9741. },
  9742. exact: function (start, soffset, finish, foffset) {
  9743. return {
  9744. ltr: cached(function () {
  9745. return exactToNative(win, start, soffset, finish, foffset);
  9746. }),
  9747. rtl: cached(function () {
  9748. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  9749. })
  9750. };
  9751. }
  9752. });
  9753. };
  9754. var doDiagnose = function (win, ranges) {
  9755. var rng = ranges.ltr();
  9756. if (rng.collapsed) {
  9757. var reversed = ranges.rtl().filter(function (rev) {
  9758. return rev.collapsed === false;
  9759. });
  9760. return reversed.map(function (rev) {
  9761. return adt$6.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  9762. }).getOrThunk(function () {
  9763. return fromRange(win, adt$6.ltr, rng);
  9764. });
  9765. } else {
  9766. return fromRange(win, adt$6.ltr, rng);
  9767. }
  9768. };
  9769. var diagnose = function (win, selection) {
  9770. var ranges = getRanges(win, selection);
  9771. return doDiagnose(win, ranges);
  9772. };
  9773. var asLtrRange = function (win, selection) {
  9774. var diagnosis = diagnose(win, selection);
  9775. return diagnosis.match({
  9776. ltr: function (start, soffset, finish, foffset) {
  9777. var rng = win.document.createRange();
  9778. rng.setStart(start.dom(), soffset);
  9779. rng.setEnd(finish.dom(), foffset);
  9780. return rng;
  9781. },
  9782. rtl: function (start, soffset, finish, foffset) {
  9783. var rng = win.document.createRange();
  9784. rng.setStart(finish.dom(), foffset);
  9785. rng.setEnd(start.dom(), soffset);
  9786. return rng;
  9787. }
  9788. });
  9789. };
  9790. var ltr = adt$6.ltr;
  9791. var rtl = adt$6.rtl;
  9792. var beforeSpecial = function (element, offset) {
  9793. var name$1 = name(element);
  9794. if ('input' === name$1) {
  9795. return Situ.after(element);
  9796. } else if (!contains([
  9797. 'br',
  9798. 'img'
  9799. ], name$1)) {
  9800. return Situ.on(element, offset);
  9801. } else {
  9802. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9803. }
  9804. };
  9805. var preprocessExact = function (start, soffset, finish, foffset) {
  9806. var startSitu = beforeSpecial(start, soffset);
  9807. var finishSitu = beforeSpecial(finish, foffset);
  9808. return Selection.relative(startSitu, finishSitu);
  9809. };
  9810. var makeRange = function (start, soffset, finish, foffset) {
  9811. var doc = owner(start);
  9812. var rng = doc.dom().createRange();
  9813. rng.setStart(start.dom(), soffset);
  9814. rng.setEnd(finish.dom(), foffset);
  9815. return rng;
  9816. };
  9817. var after$2 = function (start, soffset, finish, foffset) {
  9818. var r = makeRange(start, soffset, finish, foffset);
  9819. var same = eq(start, finish) && soffset === foffset;
  9820. return r.collapsed && !same;
  9821. };
  9822. var doSetNativeRange = function (win, rng) {
  9823. Option.from(win.getSelection()).each(function (selection) {
  9824. selection.removeAllRanges();
  9825. selection.addRange(rng);
  9826. });
  9827. };
  9828. var doSetRange = function (win, start, soffset, finish, foffset) {
  9829. var rng = exactToNative(win, start, soffset, finish, foffset);
  9830. doSetNativeRange(win, rng);
  9831. };
  9832. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9833. selection.collapse(start.dom(), soffset);
  9834. selection.extend(finish.dom(), foffset);
  9835. };
  9836. var setRangeFromRelative = function (win, relative) {
  9837. return diagnose(win, relative).match({
  9838. ltr: function (start, soffset, finish, foffset) {
  9839. doSetRange(win, start, soffset, finish, foffset);
  9840. },
  9841. rtl: function (start, soffset, finish, foffset) {
  9842. var selection = win.getSelection();
  9843. if (selection.setBaseAndExtent) {
  9844. selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
  9845. } else if (selection.extend) {
  9846. try {
  9847. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9848. } catch (e) {
  9849. doSetRange(win, finish, foffset, start, soffset);
  9850. }
  9851. } else {
  9852. doSetRange(win, finish, foffset, start, soffset);
  9853. }
  9854. }
  9855. });
  9856. };
  9857. var setExact = function (win, start, soffset, finish, foffset) {
  9858. var relative = preprocessExact(start, soffset, finish, foffset);
  9859. setRangeFromRelative(win, relative);
  9860. };
  9861. var readRange = function (selection) {
  9862. if (selection.rangeCount > 0) {
  9863. var firstRng = selection.getRangeAt(0);
  9864. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9865. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  9866. } else {
  9867. return Option.none();
  9868. }
  9869. };
  9870. var doGetExact = function (selection) {
  9871. var anchor = Element.fromDom(selection.anchorNode);
  9872. var focus = Element.fromDom(selection.focusNode);
  9873. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  9874. };
  9875. var getExact = function (win) {
  9876. return Option.from(win.getSelection()).filter(function (sel) {
  9877. return sel.rangeCount > 0;
  9878. }).bind(doGetExact);
  9879. };
  9880. var get$c = function (win) {
  9881. return getExact(win).map(function (range) {
  9882. return Selection.exact(range.start(), range.soffset(), range.finish(), range.foffset());
  9883. });
  9884. };
  9885. var getFirstRect$1 = function (win, selection) {
  9886. var rng = asLtrRange(win, selection);
  9887. return getFirstRect(rng);
  9888. };
  9889. var clear$1 = function (win) {
  9890. var selection = win.getSelection();
  9891. selection.removeAllRanges();
  9892. };
  9893. var COLLAPSED_WIDTH = 2;
  9894. var collapsedRect = function (rect) {
  9895. return {
  9896. left: rect.left,
  9897. top: rect.top,
  9898. right: rect.right,
  9899. bottom: rect.bottom,
  9900. width: constant(COLLAPSED_WIDTH),
  9901. height: rect.height
  9902. };
  9903. };
  9904. var toRect$1 = function (rawRect) {
  9905. return {
  9906. left: constant(rawRect.left),
  9907. top: constant(rawRect.top),
  9908. right: constant(rawRect.right),
  9909. bottom: constant(rawRect.bottom),
  9910. width: constant(rawRect.width),
  9911. height: constant(rawRect.height)
  9912. };
  9913. };
  9914. var getRectsFromRange = function (range) {
  9915. if (!range.collapsed) {
  9916. return map$1(range.getClientRects(), toRect$1);
  9917. } else {
  9918. var start_1 = Element.fromDom(range.startContainer);
  9919. return parent(start_1).bind(function (parent) {
  9920. var selection = Selection.exact(start_1, range.startOffset, parent, getEnd(parent));
  9921. var optRect = getFirstRect$1(range.startContainer.ownerDocument.defaultView, selection);
  9922. return optRect.map(collapsedRect).map(pure);
  9923. }).getOr([]);
  9924. }
  9925. };
  9926. var getRectangles = function (cWin) {
  9927. var sel = cWin.getSelection();
  9928. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  9929. };
  9930. var autocompleteHack = function () {
  9931. return function (f) {
  9932. global$4.setTimeout(function () {
  9933. f();
  9934. }, 0);
  9935. };
  9936. };
  9937. var resume = function (cWin) {
  9938. cWin.focus();
  9939. var iBody = Element.fromDom(cWin.document.body);
  9940. var inInput = active().exists(function (elem) {
  9941. return contains([
  9942. 'input',
  9943. 'textarea'
  9944. ], name(elem));
  9945. });
  9946. var transaction = inInput ? autocompleteHack() : apply;
  9947. transaction(function () {
  9948. active().each(blur);
  9949. focus$1(iBody);
  9950. });
  9951. };
  9952. var EXTRA_SPACING = 50;
  9953. var data = 'data-' + resolve('last-outer-height');
  9954. var setLastHeight = function (cBody, value) {
  9955. set(cBody, data, value);
  9956. };
  9957. var getLastHeight = function (cBody) {
  9958. return safeParse(cBody, data);
  9959. };
  9960. var getBoundsFrom = function (rect) {
  9961. return {
  9962. top: constant(rect.top()),
  9963. bottom: constant(rect.top() + rect.height())
  9964. };
  9965. };
  9966. var getBounds$1 = function (cWin) {
  9967. var rects = getRectangles(cWin);
  9968. return rects.length > 0 ? Option.some(rects[0]).map(getBoundsFrom) : Option.none();
  9969. };
  9970. var findDelta = function (outerWindow, cBody) {
  9971. var last = getLastHeight(cBody);
  9972. var current = outerWindow.innerHeight;
  9973. return last > current ? Option.some(last - current) : Option.none();
  9974. };
  9975. var calculate = function (cWin, bounds, delta) {
  9976. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  9977. return isOutside ? Math.min(delta, bounds.bottom() - cWin.innerHeight + EXTRA_SPACING) : 0;
  9978. };
  9979. var setup$1 = function (outerWindow, cWin) {
  9980. var cBody = Element.fromDom(cWin.document.body);
  9981. var toEditing = function () {
  9982. resume(cWin);
  9983. };
  9984. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  9985. findDelta(outerWindow, cBody).each(function (delta) {
  9986. getBounds$1(cWin).each(function (bounds) {
  9987. var cScrollBy = calculate(cWin, bounds, delta);
  9988. if (cScrollBy !== 0) {
  9989. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  9990. }
  9991. });
  9992. });
  9993. setLastHeight(cBody, outerWindow.innerHeight);
  9994. });
  9995. setLastHeight(cBody, outerWindow.innerHeight);
  9996. var destroy = function () {
  9997. onResize.unbind();
  9998. };
  9999. return {
  10000. toEditing: toEditing,
  10001. destroy: destroy
  10002. };
  10003. };
  10004. var getBodyFromFrame = function (frame) {
  10005. return Option.some(Element.fromDom(frame.dom().contentWindow.document.body));
  10006. };
  10007. var getDocFromFrame = function (frame) {
  10008. return Option.some(Element.fromDom(frame.dom().contentWindow.document));
  10009. };
  10010. var getWinFromFrame = function (frame) {
  10011. return Option.from(frame.dom().contentWindow);
  10012. };
  10013. var getSelectionFromFrame = function (frame) {
  10014. var optWin = getWinFromFrame(frame);
  10015. return optWin.bind(getExact);
  10016. };
  10017. var getFrame = function (editor) {
  10018. return editor.getFrame();
  10019. };
  10020. var getOrDerive = function (name, f) {
  10021. return function (editor) {
  10022. var g = editor[name].getOrThunk(function () {
  10023. var frame = getFrame(editor);
  10024. return function () {
  10025. return f(frame);
  10026. };
  10027. });
  10028. return g();
  10029. };
  10030. };
  10031. var getOrListen = function (editor, doc, name, type) {
  10032. return editor[name].getOrThunk(function () {
  10033. return function (handler) {
  10034. return bind$3(doc, type, handler);
  10035. };
  10036. });
  10037. };
  10038. var toRect$2 = function (rect) {
  10039. return {
  10040. left: constant(rect.left),
  10041. top: constant(rect.top),
  10042. right: constant(rect.right),
  10043. bottom: constant(rect.bottom),
  10044. width: constant(rect.width),
  10045. height: constant(rect.height)
  10046. };
  10047. };
  10048. var getActiveApi = function (editor) {
  10049. var frame = getFrame(editor);
  10050. var tryFallbackBox = function (win) {
  10051. var isCollapsed = function (sel) {
  10052. return eq(sel.start(), sel.finish()) && sel.soffset() === sel.foffset();
  10053. };
  10054. var toStartRect = function (sel) {
  10055. var rect = sel.start().dom().getBoundingClientRect();
  10056. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect$2) : Option.none();
  10057. };
  10058. return getExact(win).filter(isCollapsed).bind(toStartRect);
  10059. };
  10060. return getBodyFromFrame(frame).bind(function (body) {
  10061. return getDocFromFrame(frame).bind(function (doc) {
  10062. return getWinFromFrame(frame).map(function (win) {
  10063. var html = Element.fromDom(doc.dom().documentElement);
  10064. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  10065. return function () {
  10066. return get$c(win).bind(function (sel) {
  10067. return getFirstRect$1(win, sel).orThunk(function () {
  10068. return tryFallbackBox(win);
  10069. });
  10070. });
  10071. };
  10072. });
  10073. var setSelection = editor.setSelection.getOrThunk(function () {
  10074. return function (start, soffset, finish, foffset) {
  10075. setExact(win, start, soffset, finish, foffset);
  10076. };
  10077. });
  10078. var clearSelection = editor.clearSelection.getOrThunk(function () {
  10079. return function () {
  10080. clear$1(win);
  10081. };
  10082. });
  10083. return {
  10084. body: constant(body),
  10085. doc: constant(doc),
  10086. win: constant(win),
  10087. html: constant(html),
  10088. getSelection: curry(getSelectionFromFrame, frame),
  10089. setSelection: setSelection,
  10090. clearSelection: clearSelection,
  10091. frame: constant(frame),
  10092. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  10093. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  10094. onDomChanged: editor.onDomChanged,
  10095. onScrollToCursor: editor.onScrollToCursor,
  10096. onScrollToElement: editor.onScrollToElement,
  10097. onToReading: editor.onToReading,
  10098. onToEditing: editor.onToEditing,
  10099. onToolbarScrollStart: editor.onToolbarScrollStart,
  10100. onTouchContent: editor.onTouchContent,
  10101. onTapContent: editor.onTapContent,
  10102. onTouchToolstrip: editor.onTouchToolstrip,
  10103. getCursorBox: getCursorBox
  10104. };
  10105. });
  10106. });
  10107. });
  10108. };
  10109. var getWin$1 = getOrDerive('getWin', getWinFromFrame);
  10110. var attr = 'data-ephox-mobile-fullscreen-style';
  10111. var siblingStyles = 'display:none!important;';
  10112. var ancestorPosition = 'position:absolute!important;';
  10113. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  10114. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  10115. var isAndroid = detect$3().os.isAndroid();
  10116. var matchColor = function (editorBody) {
  10117. var color = get$4(editorBody, 'background-color');
  10118. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  10119. };
  10120. var clobberStyles = function (container, editorBody) {
  10121. var gatherSibilings = function (element) {
  10122. return siblings$2(element, '*');
  10123. };
  10124. var clobber = function (clobberStyle) {
  10125. return function (element) {
  10126. var styles = get$1(element, 'style');
  10127. var backup = styles === undefined ? 'no-styles' : styles.trim();
  10128. if (backup === clobberStyle) {
  10129. return;
  10130. } else {
  10131. set(element, attr, backup);
  10132. set(element, 'style', clobberStyle);
  10133. }
  10134. };
  10135. };
  10136. var ancestors = ancestors$1(container, '*');
  10137. var siblings = bind(ancestors, gatherSibilings);
  10138. var bgColor = matchColor(editorBody);
  10139. each$1(siblings, clobber(siblingStyles));
  10140. each$1(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor));
  10141. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  10142. clobber(containerStyles + ancestorStyles + bgColor)(container);
  10143. };
  10144. var restoreStyles = function () {
  10145. var clobberedEls = all$2('[' + attr + ']');
  10146. each$1(clobberedEls, function (element) {
  10147. var restore = get$1(element, attr);
  10148. if (restore !== 'no-styles') {
  10149. set(element, 'style', restore);
  10150. } else {
  10151. remove$1(element, 'style');
  10152. }
  10153. remove$1(element, attr);
  10154. });
  10155. };
  10156. var tag = function () {
  10157. var head = first('head').getOrDie();
  10158. var nu = function () {
  10159. var meta = Element.fromTag('meta');
  10160. set(meta, 'name', 'viewport');
  10161. append(head, meta);
  10162. return meta;
  10163. };
  10164. var element = first('meta[name="viewport"]').getOrThunk(nu);
  10165. var backup = get$1(element, 'content');
  10166. var maximize = function () {
  10167. set(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  10168. };
  10169. var restore = function () {
  10170. if (backup !== undefined && backup !== null && backup.length > 0) {
  10171. set(element, 'content', backup);
  10172. } else {
  10173. set(element, 'content', 'user-scalable=yes');
  10174. }
  10175. };
  10176. return {
  10177. maximize: maximize,
  10178. restore: restore
  10179. };
  10180. };
  10181. var create$4 = function (platform, mask) {
  10182. var meta = tag();
  10183. var androidApi = api$2();
  10184. var androidEvents = api$2();
  10185. var enter = function () {
  10186. mask.hide();
  10187. add$2(platform.container, resolve('fullscreen-maximized'));
  10188. add$2(platform.container, resolve('android-maximized'));
  10189. meta.maximize();
  10190. add$2(platform.body, resolve('android-scroll-reload'));
  10191. androidApi.set(setup$1(platform.win, getWin$1(platform.editor).getOrDie('no')));
  10192. getActiveApi(platform.editor).each(function (editorApi) {
  10193. clobberStyles(platform.container, editorApi.body());
  10194. androidEvents.set(initEvents(editorApi, platform.toolstrip, platform.alloy));
  10195. });
  10196. };
  10197. var exit = function () {
  10198. meta.restore();
  10199. mask.show();
  10200. remove$4(platform.container, resolve('fullscreen-maximized'));
  10201. remove$4(platform.container, resolve('android-maximized'));
  10202. restoreStyles();
  10203. remove$4(platform.body, resolve('android-scroll-reload'));
  10204. androidEvents.clear();
  10205. androidApi.clear();
  10206. };
  10207. return {
  10208. enter: enter,
  10209. exit: exit
  10210. };
  10211. };
  10212. var first$1 = function (fn, rate) {
  10213. var timer = null;
  10214. var cancel = function () {
  10215. if (timer !== null) {
  10216. domGlobals.clearTimeout(timer);
  10217. timer = null;
  10218. }
  10219. };
  10220. var throttle = function () {
  10221. var args = [];
  10222. for (var _i = 0; _i < arguments.length; _i++) {
  10223. args[_i] = arguments[_i];
  10224. }
  10225. if (timer === null) {
  10226. timer = domGlobals.setTimeout(function () {
  10227. fn.apply(null, args);
  10228. timer = null;
  10229. }, rate);
  10230. }
  10231. };
  10232. return {
  10233. cancel: cancel,
  10234. throttle: throttle
  10235. };
  10236. };
  10237. var last = function (fn, rate) {
  10238. var timer = null;
  10239. var cancel = function () {
  10240. if (timer !== null) {
  10241. domGlobals.clearTimeout(timer);
  10242. timer = null;
  10243. }
  10244. };
  10245. var throttle = function () {
  10246. var args = [];
  10247. for (var _i = 0; _i < arguments.length; _i++) {
  10248. args[_i] = arguments[_i];
  10249. }
  10250. if (timer !== null) {
  10251. domGlobals.clearTimeout(timer);
  10252. }
  10253. timer = domGlobals.setTimeout(function () {
  10254. fn.apply(null, args);
  10255. timer = null;
  10256. }, rate);
  10257. };
  10258. return {
  10259. cancel: cancel,
  10260. throttle: throttle
  10261. };
  10262. };
  10263. var sketch$9 = function (onView, _translate) {
  10264. var memIcon = record(Container.sketch({
  10265. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10266. containerBehaviours: derive$1([Toggling.config({
  10267. toggleClass: resolve('mask-tap-icon-selected'),
  10268. toggleOnExecute: false
  10269. })])
  10270. }));
  10271. var onViewThrottle = first$1(onView, 200);
  10272. return Container.sketch({
  10273. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10274. components: [Container.sketch({
  10275. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10276. components: [Button.sketch({
  10277. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10278. components: [memIcon.asSpec()],
  10279. action: function (_button) {
  10280. onViewThrottle.throttle();
  10281. },
  10282. buttonBehaviours: derive$1([Toggling.config({ toggleClass: resolve('mask-tap-icon-selected') })])
  10283. })]
  10284. })]
  10285. });
  10286. };
  10287. var MobileSchema = objOf([
  10288. strictObjOf('editor', [
  10289. strict$1('getFrame'),
  10290. option('getBody'),
  10291. option('getDoc'),
  10292. option('getWin'),
  10293. option('getSelection'),
  10294. option('setSelection'),
  10295. option('clearSelection'),
  10296. option('cursorSaver'),
  10297. option('onKeyup'),
  10298. option('onNodeChanged'),
  10299. option('getCursorBox'),
  10300. strict$1('onDomChanged'),
  10301. defaulted$1('onTouchContent', noop),
  10302. defaulted$1('onTapContent', noop),
  10303. defaulted$1('onTouchToolstrip', noop),
  10304. defaulted$1('onScrollToCursor', constant({ unbind: noop })),
  10305. defaulted$1('onScrollToElement', constant({ unbind: noop })),
  10306. defaulted$1('onToEditing', constant({ unbind: noop })),
  10307. defaulted$1('onToReading', constant({ unbind: noop })),
  10308. defaulted$1('onToolbarScrollStart', identity)
  10309. ]),
  10310. strict$1('socket'),
  10311. strict$1('toolstrip'),
  10312. strict$1('dropup'),
  10313. strict$1('toolbar'),
  10314. strict$1('container'),
  10315. strict$1('alloy'),
  10316. state$1('win', function (spec) {
  10317. return owner(spec.socket).dom().defaultView;
  10318. }),
  10319. state$1('body', function (spec) {
  10320. return Element.fromDom(spec.socket.dom().ownerDocument.body);
  10321. }),
  10322. defaulted$1('translate', identity),
  10323. defaulted$1('setReadOnly', noop),
  10324. defaulted$1('readOnlyOnInit', constant(true))
  10325. ]);
  10326. var produce = function (raw) {
  10327. var mobile = asRawOrDie('Getting AndroidWebapp schema', MobileSchema, raw);
  10328. set$3(mobile.toolstrip, 'width', '100%');
  10329. var onTap = function () {
  10330. mobile.setReadOnly(mobile.readOnlyOnInit());
  10331. mode.enter();
  10332. };
  10333. var mask = build$1(sketch$9(onTap, mobile.translate));
  10334. mobile.alloy.add(mask);
  10335. var maskApi = {
  10336. show: function () {
  10337. mobile.alloy.add(mask);
  10338. },
  10339. hide: function () {
  10340. mobile.alloy.remove(mask);
  10341. }
  10342. };
  10343. append(mobile.container, mask.element());
  10344. var mode = create$4(mobile, maskApi);
  10345. return {
  10346. setReadOnly: mobile.setReadOnly,
  10347. refreshStructure: noop,
  10348. enter: mode.enter,
  10349. exit: mode.exit,
  10350. destroy: noop
  10351. };
  10352. };
  10353. var schema$e = constant([
  10354. strict$1('dom'),
  10355. defaulted$1('shell', true),
  10356. field$1('toolbarBehaviours', [Replacing])
  10357. ]);
  10358. var enhanceGroups = function () {
  10359. return { behaviours: derive$1([Replacing.config({})]) };
  10360. };
  10361. var parts$2 = constant([optional({
  10362. name: 'groups',
  10363. overrides: enhanceGroups
  10364. })]);
  10365. var factory$4 = function (detail, components, _spec, _externals) {
  10366. var setGroups = function (toolbar, groups) {
  10367. getGroupContainer(toolbar).fold(function () {
  10368. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10369. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10370. }, function (container) {
  10371. Replacing.set(container, groups);
  10372. });
  10373. };
  10374. var getGroupContainer = function (component) {
  10375. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  10376. };
  10377. var extra = detail.shell ? {
  10378. behaviours: [Replacing.config({})],
  10379. components: []
  10380. } : {
  10381. behaviours: [],
  10382. components: components
  10383. };
  10384. return {
  10385. uid: detail.uid,
  10386. dom: detail.dom,
  10387. components: extra.components,
  10388. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10389. apis: { setGroups: setGroups },
  10390. domModification: { attributes: { role: 'group' } }
  10391. };
  10392. };
  10393. var Toolbar = composite$1({
  10394. name: 'Toolbar',
  10395. configFields: schema$e(),
  10396. partFields: parts$2(),
  10397. factory: factory$4,
  10398. apis: {
  10399. setGroups: function (apis, toolbar, groups) {
  10400. apis.setGroups(toolbar, groups);
  10401. }
  10402. }
  10403. });
  10404. var schema$f = constant([
  10405. strict$1('items'),
  10406. markers(['itemSelector']),
  10407. field$1('tgroupBehaviours', [Keying])
  10408. ]);
  10409. var parts$3 = constant([group({
  10410. name: 'items',
  10411. unit: 'item'
  10412. })]);
  10413. var factory$5 = function (detail, components, _spec, _externals) {
  10414. return {
  10415. uid: detail.uid,
  10416. dom: detail.dom,
  10417. components: components,
  10418. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10419. mode: 'flow',
  10420. selector: detail.markers.itemSelector
  10421. })]),
  10422. domModification: { attributes: { role: 'toolbar' } }
  10423. };
  10424. };
  10425. var ToolbarGroup = composite$1({
  10426. name: 'ToolbarGroup',
  10427. configFields: schema$f(),
  10428. partFields: parts$3(),
  10429. factory: factory$5
  10430. });
  10431. var dataHorizontal = 'data-' + resolve('horizontal-scroll');
  10432. var canScrollVertically = function (container) {
  10433. container.dom().scrollTop = 1;
  10434. var result = container.dom().scrollTop !== 0;
  10435. container.dom().scrollTop = 0;
  10436. return result;
  10437. };
  10438. var canScrollHorizontally = function (container) {
  10439. container.dom().scrollLeft = 1;
  10440. var result = container.dom().scrollLeft !== 0;
  10441. container.dom().scrollLeft = 0;
  10442. return result;
  10443. };
  10444. var hasVerticalScroll = function (container) {
  10445. return container.dom().scrollTop > 0 || canScrollVertically(container);
  10446. };
  10447. var hasHorizontalScroll = function (container) {
  10448. return container.dom().scrollLeft > 0 || canScrollHorizontally(container);
  10449. };
  10450. var markAsHorizontal = function (container) {
  10451. set(container, dataHorizontal, 'true');
  10452. };
  10453. var hasScroll = function (container) {
  10454. return get$1(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10455. };
  10456. var exclusive = function (scope, selector) {
  10457. return bind$3(scope, 'touchmove', function (event) {
  10458. closest$2(event.target(), selector).filter(hasScroll).fold(function () {
  10459. event.raw().preventDefault();
  10460. }, noop);
  10461. });
  10462. };
  10463. function ScrollingToolbar () {
  10464. var makeGroup = function (gSpec) {
  10465. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10466. return {
  10467. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10468. tgroupBehaviours: derive$1([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, _simulatedEvent) {
  10469. set$3(component.element(), 'overflow-x', 'auto');
  10470. markAsHorizontal(component.element());
  10471. register(component.element());
  10472. })] : [])]),
  10473. components: [Container.sketch({ components: [ToolbarGroup.parts().items({})] })],
  10474. markers: { itemSelector: '.' + resolve('toolbar-group-item') },
  10475. items: gSpec.items
  10476. };
  10477. };
  10478. var toolbar = build$1(Toolbar.sketch({
  10479. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10480. components: [Toolbar.parts().groups({})],
  10481. toolbarBehaviours: derive$1([
  10482. Toggling.config({
  10483. toggleClass: resolve('context-toolbar'),
  10484. toggleOnExecute: false,
  10485. aria: { mode: 'none' }
  10486. }),
  10487. Keying.config({ mode: 'cyclic' })
  10488. ]),
  10489. shell: true
  10490. }));
  10491. var wrapper = build$1(Container.sketch({
  10492. dom: { classes: [resolve('toolstrip')] },
  10493. components: [premade$1(toolbar)],
  10494. containerBehaviours: derive$1([Toggling.config({
  10495. toggleClass: resolve('android-selection-context-toolbar'),
  10496. toggleOnExecute: false
  10497. })])
  10498. }));
  10499. var resetGroups = function () {
  10500. Toolbar.setGroups(toolbar, initGroups.get());
  10501. Toggling.off(toolbar);
  10502. };
  10503. var initGroups = Cell([]);
  10504. var setGroups = function (gs) {
  10505. initGroups.set(gs);
  10506. resetGroups();
  10507. };
  10508. var createGroups = function (gs) {
  10509. return map$1(gs, compose(ToolbarGroup.sketch, makeGroup));
  10510. };
  10511. var refresh = function () {
  10512. };
  10513. var setContextToolbar = function (gs) {
  10514. Toggling.on(toolbar);
  10515. Toolbar.setGroups(toolbar, gs);
  10516. };
  10517. var restoreToolbar = function () {
  10518. if (Toggling.isOn(toolbar)) {
  10519. resetGroups();
  10520. }
  10521. };
  10522. var focus = function () {
  10523. Keying.focusIn(toolbar);
  10524. };
  10525. return {
  10526. wrapper: constant(wrapper),
  10527. toolbar: constant(toolbar),
  10528. createGroups: createGroups,
  10529. setGroups: setGroups,
  10530. setContextToolbar: setContextToolbar,
  10531. restoreToolbar: restoreToolbar,
  10532. refresh: refresh,
  10533. focus: focus
  10534. };
  10535. }
  10536. var makeEditSwitch = function (webapp) {
  10537. return build$1(Button.sketch({
  10538. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10539. action: function () {
  10540. webapp.run(function (w) {
  10541. w.setReadOnly(false);
  10542. });
  10543. }
  10544. }));
  10545. };
  10546. var makeSocket = function () {
  10547. return build$1(Container.sketch({
  10548. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10549. components: [],
  10550. containerBehaviours: derive$1([Replacing.config({})])
  10551. }));
  10552. };
  10553. var showEdit = function (socket, switchToEdit) {
  10554. Replacing.append(socket, premade$1(switchToEdit));
  10555. };
  10556. var hideEdit = function (socket, switchToEdit) {
  10557. Replacing.remove(socket, switchToEdit);
  10558. };
  10559. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10560. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10561. swap(root);
  10562. var f = readOnly ? showEdit : hideEdit;
  10563. f(socket, switchToEdit);
  10564. };
  10565. var getAnimationRoot = function (component, slideConfig) {
  10566. return slideConfig.getAnimationRoot.fold(function () {
  10567. return component.element();
  10568. }, function (get) {
  10569. return get(component);
  10570. });
  10571. };
  10572. var getDimensionProperty = function (slideConfig) {
  10573. return slideConfig.dimension.property;
  10574. };
  10575. var getDimension = function (slideConfig, elem) {
  10576. return slideConfig.dimension.getDimension(elem);
  10577. };
  10578. var disableTransitions = function (component, slideConfig) {
  10579. var root = getAnimationRoot(component, slideConfig);
  10580. remove$6(root, [
  10581. slideConfig.shrinkingClass,
  10582. slideConfig.growingClass
  10583. ]);
  10584. };
  10585. var setShrunk = function (component, slideConfig) {
  10586. remove$4(component.element(), slideConfig.openClass);
  10587. add$2(component.element(), slideConfig.closedClass);
  10588. set$3(component.element(), getDimensionProperty(slideConfig), '0px');
  10589. reflow(component.element());
  10590. };
  10591. var setGrown = function (component, slideConfig) {
  10592. remove$4(component.element(), slideConfig.closedClass);
  10593. add$2(component.element(), slideConfig.openClass);
  10594. remove$5(component.element(), getDimensionProperty(slideConfig));
  10595. };
  10596. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10597. slideState.setCollapsed();
  10598. set$3(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  10599. reflow(component.element());
  10600. disableTransitions(component, slideConfig);
  10601. setShrunk(component, slideConfig);
  10602. slideConfig.onStartShrink(component);
  10603. slideConfig.onShrunk(component);
  10604. };
  10605. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10606. var size = calculatedSize.getOrThunk(function () {
  10607. return getDimension(slideConfig, component.element());
  10608. });
  10609. slideState.setCollapsed();
  10610. set$3(component.element(), getDimensionProperty(slideConfig), size);
  10611. reflow(component.element());
  10612. var root = getAnimationRoot(component, slideConfig);
  10613. remove$4(root, slideConfig.growingClass);
  10614. add$2(root, slideConfig.shrinkingClass);
  10615. setShrunk(component, slideConfig);
  10616. slideConfig.onStartShrink(component);
  10617. };
  10618. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10619. var size = getDimension(slideConfig, component.element());
  10620. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10621. shrinker(component, slideConfig, slideState, Option.some(size));
  10622. };
  10623. var doStartGrow = function (component, slideConfig, slideState) {
  10624. var root = getAnimationRoot(component, slideConfig);
  10625. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  10626. var beforeSize = getDimension(slideConfig, component.element());
  10627. setGrown(component, slideConfig);
  10628. var fullSize = getDimension(slideConfig, component.element());
  10629. var startPartialGrow = function () {
  10630. set$3(component.element(), getDimensionProperty(slideConfig), beforeSize);
  10631. reflow(component.element());
  10632. };
  10633. var startCompleteGrow = function () {
  10634. setShrunk(component, slideConfig);
  10635. };
  10636. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  10637. setStartSize();
  10638. remove$4(root, slideConfig.shrinkingClass);
  10639. add$2(root, slideConfig.growingClass);
  10640. setGrown(component, slideConfig);
  10641. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  10642. slideState.setExpanded();
  10643. slideConfig.onStartGrow(component);
  10644. };
  10645. var refresh = function (component, slideConfig, slideState) {
  10646. if (slideState.isExpanded()) {
  10647. remove$5(component.element(), getDimensionProperty(slideConfig));
  10648. var fullSize = getDimension(slideConfig, component.element());
  10649. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  10650. }
  10651. };
  10652. var grow = function (component, slideConfig, slideState) {
  10653. if (!slideState.isExpanded()) {
  10654. doStartGrow(component, slideConfig, slideState);
  10655. }
  10656. };
  10657. var shrink = function (component, slideConfig, slideState) {
  10658. if (slideState.isExpanded()) {
  10659. doStartSmartShrink(component, slideConfig, slideState);
  10660. }
  10661. };
  10662. var immediateShrink = function (component, slideConfig, slideState) {
  10663. if (slideState.isExpanded()) {
  10664. doImmediateShrink(component, slideConfig, slideState, Option.none());
  10665. }
  10666. };
  10667. var hasGrown = function (component, slideConfig, slideState) {
  10668. return slideState.isExpanded();
  10669. };
  10670. var hasShrunk = function (component, slideConfig, slideState) {
  10671. return slideState.isCollapsed();
  10672. };
  10673. var isGrowing = function (component, slideConfig, _slideState) {
  10674. var root = getAnimationRoot(component, slideConfig);
  10675. return has$2(root, slideConfig.growingClass) === true;
  10676. };
  10677. var isShrinking = function (component, slideConfig, _slideState) {
  10678. var root = getAnimationRoot(component, slideConfig);
  10679. return has$2(root, slideConfig.shrinkingClass) === true;
  10680. };
  10681. var isTransitioning = function (component, slideConfig, slideState) {
  10682. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  10683. };
  10684. var toggleGrow = function (component, slideConfig, slideState) {
  10685. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  10686. f(component, slideConfig, slideState);
  10687. };
  10688. var SlidingApis = /*#__PURE__*/Object.freeze({
  10689. __proto__: null,
  10690. refresh: refresh,
  10691. grow: grow,
  10692. shrink: shrink,
  10693. immediateShrink: immediateShrink,
  10694. hasGrown: hasGrown,
  10695. hasShrunk: hasShrunk,
  10696. isGrowing: isGrowing,
  10697. isShrinking: isShrinking,
  10698. isTransitioning: isTransitioning,
  10699. toggleGrow: toggleGrow,
  10700. disableTransitions: disableTransitions
  10701. });
  10702. var exhibit$5 = function (base, slideConfig, _slideState) {
  10703. var expanded = slideConfig.expanded;
  10704. return expanded ? nu$5({
  10705. classes: [slideConfig.openClass],
  10706. styles: {}
  10707. }) : nu$5({
  10708. classes: [slideConfig.closedClass],
  10709. styles: wrap$1(slideConfig.dimension.property, '0px')
  10710. });
  10711. };
  10712. var events$a = function (slideConfig, slideState) {
  10713. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  10714. var raw = simulatedEvent.event().raw();
  10715. if (raw.propertyName === slideConfig.dimension.property) {
  10716. disableTransitions(component, slideConfig);
  10717. if (slideState.isExpanded()) {
  10718. remove$5(component.element(), slideConfig.dimension.property);
  10719. }
  10720. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  10721. notify(component);
  10722. }
  10723. })]);
  10724. };
  10725. var ActiveSliding = /*#__PURE__*/Object.freeze({
  10726. __proto__: null,
  10727. exhibit: exhibit$5,
  10728. events: events$a
  10729. });
  10730. var SlidingSchema = [
  10731. strict$1('closedClass'),
  10732. strict$1('openClass'),
  10733. strict$1('shrinkingClass'),
  10734. strict$1('growingClass'),
  10735. option('getAnimationRoot'),
  10736. onHandler('onShrunk'),
  10737. onHandler('onStartShrink'),
  10738. onHandler('onGrown'),
  10739. onHandler('onStartGrow'),
  10740. defaulted$1('expanded', false),
  10741. strictOf('dimension', choose$1('property', {
  10742. width: [
  10743. output('property', 'width'),
  10744. output('getDimension', function (elem) {
  10745. return get$7(elem) + 'px';
  10746. })
  10747. ],
  10748. height: [
  10749. output('property', 'height'),
  10750. output('getDimension', function (elem) {
  10751. return get$5(elem) + 'px';
  10752. })
  10753. ]
  10754. }))
  10755. ];
  10756. var init$4 = function (spec) {
  10757. var state = Cell(spec.expanded);
  10758. var readState = function () {
  10759. return 'expanded: ' + state.get();
  10760. };
  10761. return nu$6({
  10762. isExpanded: function () {
  10763. return state.get() === true;
  10764. },
  10765. isCollapsed: function () {
  10766. return state.get() === false;
  10767. },
  10768. setCollapsed: curry(state.set, false),
  10769. setExpanded: curry(state.set, true),
  10770. readState: readState
  10771. });
  10772. };
  10773. var SlidingState = /*#__PURE__*/Object.freeze({
  10774. __proto__: null,
  10775. init: init$4
  10776. });
  10777. var Sliding = create$1({
  10778. fields: SlidingSchema,
  10779. name: 'sliding',
  10780. active: ActiveSliding,
  10781. apis: SlidingApis,
  10782. state: SlidingState
  10783. });
  10784. var build$2 = function (refresh, scrollIntoView) {
  10785. var dropup = build$1(Container.sketch({
  10786. dom: {
  10787. tag: 'div',
  10788. classes: [resolve('dropup')]
  10789. },
  10790. components: [],
  10791. containerBehaviours: derive$1([
  10792. Replacing.config({}),
  10793. Sliding.config({
  10794. closedClass: resolve('dropup-closed'),
  10795. openClass: resolve('dropup-open'),
  10796. shrinkingClass: resolve('dropup-shrinking'),
  10797. growingClass: resolve('dropup-growing'),
  10798. dimension: { property: 'height' },
  10799. onShrunk: function (component) {
  10800. refresh();
  10801. scrollIntoView();
  10802. Replacing.set(component, []);
  10803. },
  10804. onGrown: function (_component) {
  10805. refresh();
  10806. scrollIntoView();
  10807. }
  10808. }),
  10809. orientation(function (_component, _data) {
  10810. disappear(noop);
  10811. })
  10812. ])
  10813. }));
  10814. var appear = function (menu, update, component) {
  10815. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  10816. domGlobals.window.requestAnimationFrame(function () {
  10817. update(component);
  10818. Replacing.set(dropup, [menu()]);
  10819. Sliding.grow(dropup);
  10820. });
  10821. }
  10822. };
  10823. var disappear = function (onReadyToShrink) {
  10824. domGlobals.window.requestAnimationFrame(function () {
  10825. onReadyToShrink();
  10826. Sliding.shrink(dropup);
  10827. });
  10828. };
  10829. return {
  10830. appear: appear,
  10831. disappear: disappear,
  10832. component: constant(dropup),
  10833. element: dropup.element
  10834. };
  10835. };
  10836. var closest$3 = function (scope, selector, isRoot) {
  10837. return closest$2(scope, selector, isRoot).isSome();
  10838. };
  10839. var isDangerous = function (event) {
  10840. var keyEv = event.raw();
  10841. return keyEv.which === BACKSPACE()[0] && !contains([
  10842. 'input',
  10843. 'textarea'
  10844. ], name(event.target())) && !closest$3(event.target(), '[contenteditable="true"]');
  10845. };
  10846. var isFirefox = function () {
  10847. return detect$3().browser.isFirefox();
  10848. };
  10849. var settingsSchema = objOfOnly([
  10850. strictFunction('triggerEvent'),
  10851. defaulted$1('stopBackspace', true)
  10852. ]);
  10853. var bindFocus = function (container, handler) {
  10854. if (isFirefox()) {
  10855. return capture$1(container, 'focus', handler);
  10856. } else {
  10857. return bind$3(container, 'focusin', handler);
  10858. }
  10859. };
  10860. var bindBlur = function (container, handler) {
  10861. if (isFirefox()) {
  10862. return capture$1(container, 'blur', handler);
  10863. } else {
  10864. return bind$3(container, 'focusout', handler);
  10865. }
  10866. };
  10867. var setup$2 = function (container, rawSettings) {
  10868. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  10869. var pointerEvents = [
  10870. 'touchstart',
  10871. 'touchmove',
  10872. 'touchend',
  10873. 'touchcancel',
  10874. 'gesturestart',
  10875. 'mousedown',
  10876. 'mouseup',
  10877. 'mouseover',
  10878. 'mousemove',
  10879. 'mouseout',
  10880. 'click'
  10881. ];
  10882. var tapEvent = monitor(settings);
  10883. var simpleEvents = map$1(pointerEvents.concat([
  10884. 'selectstart',
  10885. 'input',
  10886. 'contextmenu',
  10887. 'change',
  10888. 'transitionend',
  10889. 'drag',
  10890. 'dragstart',
  10891. 'dragend',
  10892. 'dragenter',
  10893. 'dragleave',
  10894. 'dragover',
  10895. 'drop',
  10896. 'keyup'
  10897. ]), function (type) {
  10898. return bind$3(container, type, function (event) {
  10899. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  10900. if (tapStopped) {
  10901. event.kill();
  10902. }
  10903. });
  10904. var stopped = settings.triggerEvent(type, event);
  10905. if (stopped) {
  10906. event.kill();
  10907. }
  10908. });
  10909. });
  10910. var pasteTimeout = Cell(Option.none());
  10911. var onPaste = bind$3(container, 'paste', function (event) {
  10912. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  10913. if (tapStopped) {
  10914. event.kill();
  10915. }
  10916. });
  10917. var stopped = settings.triggerEvent('paste', event);
  10918. if (stopped) {
  10919. event.kill();
  10920. }
  10921. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  10922. settings.triggerEvent(postPaste(), event);
  10923. }, 0)));
  10924. });
  10925. var onKeydown = bind$3(container, 'keydown', function (event) {
  10926. var stopped = settings.triggerEvent('keydown', event);
  10927. if (stopped) {
  10928. event.kill();
  10929. } else if (settings.stopBackspace === true && isDangerous(event)) {
  10930. event.prevent();
  10931. }
  10932. });
  10933. var onFocusIn = bindFocus(container, function (event) {
  10934. var stopped = settings.triggerEvent('focusin', event);
  10935. if (stopped) {
  10936. event.kill();
  10937. }
  10938. });
  10939. var focusoutTimeout = Cell(Option.none());
  10940. var onFocusOut = bindBlur(container, function (event) {
  10941. var stopped = settings.triggerEvent('focusout', event);
  10942. if (stopped) {
  10943. event.kill();
  10944. }
  10945. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  10946. settings.triggerEvent(postBlur(), event);
  10947. }, 0)));
  10948. });
  10949. var unbind = function () {
  10950. each$1(simpleEvents, function (e) {
  10951. e.unbind();
  10952. });
  10953. onKeydown.unbind();
  10954. onFocusIn.unbind();
  10955. onFocusOut.unbind();
  10956. onPaste.unbind();
  10957. pasteTimeout.get().each(domGlobals.clearTimeout);
  10958. focusoutTimeout.get().each(domGlobals.clearTimeout);
  10959. };
  10960. return { unbind: unbind };
  10961. };
  10962. var derive$2 = function (rawEvent, rawTarget) {
  10963. var source = get(rawEvent, 'target').map(function (getTarget) {
  10964. return getTarget();
  10965. }).getOr(rawTarget);
  10966. return Cell(source);
  10967. };
  10968. var fromSource = function (event, source) {
  10969. var stopper = Cell(false);
  10970. var cutter = Cell(false);
  10971. var stop = function () {
  10972. stopper.set(true);
  10973. };
  10974. var cut = function () {
  10975. cutter.set(true);
  10976. };
  10977. return {
  10978. stop: stop,
  10979. cut: cut,
  10980. isStopped: stopper.get,
  10981. isCut: cutter.get,
  10982. event: constant(event),
  10983. setSource: source.set,
  10984. getSource: source.get
  10985. };
  10986. };
  10987. var fromExternal = function (event) {
  10988. var stopper = Cell(false);
  10989. var stop = function () {
  10990. stopper.set(true);
  10991. };
  10992. return {
  10993. stop: stop,
  10994. cut: noop,
  10995. isStopped: stopper.get,
  10996. isCut: constant(false),
  10997. event: constant(event),
  10998. setSource: die('Cannot set source of a broadcasted event'),
  10999. getSource: die('Cannot get source of a broadcasted event')
  11000. };
  11001. };
  11002. var adt$7 = Adt.generate([
  11003. { stopped: [] },
  11004. { resume: ['element'] },
  11005. { complete: [] }
  11006. ]);
  11007. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11008. var handler = lookup(eventType, target);
  11009. var simulatedEvent = fromSource(rawEvent, source);
  11010. return handler.fold(function () {
  11011. logger.logEventNoHandlers(eventType, target);
  11012. return adt$7.complete();
  11013. }, function (handlerInfo) {
  11014. var descHandler = handlerInfo.descHandler;
  11015. var eventHandler = getCurried(descHandler);
  11016. eventHandler(simulatedEvent);
  11017. if (simulatedEvent.isStopped()) {
  11018. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose());
  11019. return adt$7.stopped();
  11020. } else if (simulatedEvent.isCut()) {
  11021. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose());
  11022. return adt$7.complete();
  11023. } else {
  11024. return parent(handlerInfo.element).fold(function () {
  11025. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose());
  11026. return adt$7.complete();
  11027. }, function (parent) {
  11028. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose());
  11029. return adt$7.resume(parent);
  11030. });
  11031. }
  11032. });
  11033. };
  11034. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11035. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  11036. return true;
  11037. }, function (parent) {
  11038. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11039. }, function () {
  11040. return false;
  11041. });
  11042. };
  11043. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11044. var source = derive$2(rawEvent, target);
  11045. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11046. };
  11047. var broadcast = function (listeners, rawEvent, _logger) {
  11048. var simulatedEvent = fromExternal(rawEvent);
  11049. each$1(listeners, function (listener) {
  11050. var descHandler = listener.descHandler();
  11051. var handler = getCurried(descHandler);
  11052. handler(simulatedEvent);
  11053. });
  11054. return simulatedEvent.isStopped();
  11055. };
  11056. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11057. var rawTarget = rawEvent.target();
  11058. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  11059. };
  11060. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11061. var source = derive$2(rawEvent, rawTarget);
  11062. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11063. };
  11064. var eventHandler = function (element, descHandler) {
  11065. return {
  11066. element: element,
  11067. descHandler: descHandler
  11068. };
  11069. };
  11070. var broadcastHandler = function (id, handler) {
  11071. return {
  11072. id: constant(id),
  11073. descHandler: constant(handler)
  11074. };
  11075. };
  11076. function EventRegistry () {
  11077. var registry = {};
  11078. var registerId = function (extraArgs, id, events) {
  11079. each(events, function (v, k) {
  11080. var handlers = registry[k] !== undefined ? registry[k] : {};
  11081. handlers[id] = curryArgs(v, extraArgs);
  11082. registry[k] = handlers;
  11083. });
  11084. };
  11085. var findHandler = function (handlers, elem) {
  11086. return read$2(elem).fold(function () {
  11087. return Option.none();
  11088. }, function (id) {
  11089. return handlers.bind(function (h) {
  11090. return get(h, id);
  11091. }).map(function (descHandler) {
  11092. return eventHandler(elem, descHandler);
  11093. });
  11094. });
  11095. };
  11096. var filterByType = function (type) {
  11097. return get(registry, type).map(function (handlers) {
  11098. return mapToArray(handlers, function (f, id) {
  11099. return broadcastHandler(id, f);
  11100. });
  11101. }).getOr([]);
  11102. };
  11103. var find = function (isAboveRoot, type, target) {
  11104. var handlers = get(registry, type);
  11105. return closest(target, function (elem) {
  11106. return findHandler(handlers, elem);
  11107. }, isAboveRoot);
  11108. };
  11109. var unregisterId = function (id) {
  11110. each(registry, function (handlersById, _eventName) {
  11111. if (handlersById.hasOwnProperty(id)) {
  11112. delete handlersById[id];
  11113. }
  11114. });
  11115. };
  11116. return {
  11117. registerId: registerId,
  11118. unregisterId: unregisterId,
  11119. filterByType: filterByType,
  11120. find: find
  11121. };
  11122. }
  11123. function Registry () {
  11124. var events = EventRegistry();
  11125. var components = {};
  11126. var readOrTag = function (component) {
  11127. var elem = component.element();
  11128. return read$2(elem).fold(function () {
  11129. return write('uid-', component.element());
  11130. }, function (uid) {
  11131. return uid;
  11132. });
  11133. };
  11134. var failOnDuplicate = function (component, tagId) {
  11135. var conflict = components[tagId];
  11136. if (conflict === component) {
  11137. unregister(component);
  11138. } else {
  11139. 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');
  11140. }
  11141. };
  11142. var register = function (component) {
  11143. var tagId = readOrTag(component);
  11144. if (hasNonNullableKey(components, tagId)) {
  11145. failOnDuplicate(component, tagId);
  11146. }
  11147. var extraArgs = [component];
  11148. events.registerId(extraArgs, tagId, component.events());
  11149. components[tagId] = component;
  11150. };
  11151. var unregister = function (component) {
  11152. read$2(component.element()).each(function (tagId) {
  11153. delete components[tagId];
  11154. events.unregisterId(tagId);
  11155. });
  11156. };
  11157. var filter = function (type) {
  11158. return events.filterByType(type);
  11159. };
  11160. var find = function (isAboveRoot, type, target) {
  11161. return events.find(isAboveRoot, type, target);
  11162. };
  11163. var getById = function (id) {
  11164. return get(components, id);
  11165. };
  11166. return {
  11167. find: find,
  11168. filter: filter,
  11169. register: register,
  11170. unregister: unregister,
  11171. getById: getById
  11172. };
  11173. }
  11174. var takeover = function (root) {
  11175. var isAboveRoot = function (el) {
  11176. return parent(root.element()).fold(function () {
  11177. return true;
  11178. }, function (parent) {
  11179. return eq(el, parent);
  11180. });
  11181. };
  11182. var registry = Registry();
  11183. var lookup = function (eventName, target) {
  11184. return registry.find(isAboveRoot, eventName, target);
  11185. };
  11186. var domEvents = setup$2(root.element(), {
  11187. triggerEvent: function (eventName, event) {
  11188. return monitorEvent(eventName, event.target(), function (logger) {
  11189. return triggerUntilStopped(lookup, eventName, event, logger);
  11190. });
  11191. }
  11192. });
  11193. var systemApi = {
  11194. debugInfo: constant('real'),
  11195. triggerEvent: function (eventName, target, data) {
  11196. monitorEvent(eventName, target, function (logger) {
  11197. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11198. });
  11199. },
  11200. triggerFocus: function (target, originator) {
  11201. read$2(target).fold(function () {
  11202. focus$1(target);
  11203. }, function (_alloyId) {
  11204. monitorEvent(focus(), target, function (logger) {
  11205. triggerHandler(lookup, focus(), {
  11206. originator: constant(originator),
  11207. kill: noop,
  11208. prevent: noop,
  11209. target: constant(target)
  11210. }, target, logger);
  11211. return false;
  11212. });
  11213. });
  11214. },
  11215. triggerEscape: function (comp, simulatedEvent) {
  11216. systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
  11217. },
  11218. getByUid: function (uid) {
  11219. return getByUid(uid);
  11220. },
  11221. getByDom: function (elem) {
  11222. return getByDom(elem);
  11223. },
  11224. build: build$1,
  11225. addToGui: function (c) {
  11226. add(c);
  11227. },
  11228. removeFromGui: function (c) {
  11229. remove$1(c);
  11230. },
  11231. addToWorld: function (c) {
  11232. addToWorld(c);
  11233. },
  11234. removeFromWorld: function (c) {
  11235. removeFromWorld(c);
  11236. },
  11237. broadcast: function (message) {
  11238. broadcast$1(message);
  11239. },
  11240. broadcastOn: function (channels, message) {
  11241. broadcastOn(channels, message);
  11242. },
  11243. broadcastEvent: function (eventName, event) {
  11244. broadcastEvent(eventName, event);
  11245. },
  11246. isConnected: constant(true)
  11247. };
  11248. var addToWorld = function (component) {
  11249. component.connect(systemApi);
  11250. if (!isText(component.element())) {
  11251. registry.register(component);
  11252. each$1(component.components(), addToWorld);
  11253. systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
  11254. }
  11255. };
  11256. var removeFromWorld = function (component) {
  11257. if (!isText(component.element())) {
  11258. each$1(component.components(), removeFromWorld);
  11259. registry.unregister(component);
  11260. }
  11261. component.disconnect();
  11262. };
  11263. var add = function (component) {
  11264. attach$1(root, component);
  11265. };
  11266. var remove$1 = function (component) {
  11267. detach(component);
  11268. };
  11269. var destroy = function () {
  11270. domEvents.unbind();
  11271. remove(root.element());
  11272. };
  11273. var broadcastData = function (data) {
  11274. var receivers = registry.filter(receive());
  11275. each$1(receivers, function (receiver) {
  11276. var descHandler = receiver.descHandler();
  11277. var handler = getCurried(descHandler);
  11278. handler(data);
  11279. });
  11280. };
  11281. var broadcast$1 = function (message) {
  11282. broadcastData({
  11283. universal: constant(true),
  11284. data: constant(message)
  11285. });
  11286. };
  11287. var broadcastOn = function (channels, message) {
  11288. broadcastData({
  11289. universal: constant(false),
  11290. channels: constant(channels),
  11291. data: constant(message)
  11292. });
  11293. };
  11294. var broadcastEvent = function (eventName, event) {
  11295. var listeners = registry.filter(eventName);
  11296. return broadcast(listeners, event);
  11297. };
  11298. var getByUid = function (uid) {
  11299. return registry.getById(uid).fold(function () {
  11300. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11301. }, Result.value);
  11302. };
  11303. var getByDom = function (elem) {
  11304. var uid = read$2(elem).getOr('not found');
  11305. return getByUid(uid);
  11306. };
  11307. addToWorld(root);
  11308. return {
  11309. root: constant(root),
  11310. element: root.element,
  11311. destroy: destroy,
  11312. add: add,
  11313. remove: remove$1,
  11314. getByUid: getByUid,
  11315. getByDom: getByDom,
  11316. addToWorld: addToWorld,
  11317. removeFromWorld: removeFromWorld,
  11318. broadcast: broadcast$1,
  11319. broadcastOn: broadcastOn,
  11320. broadcastEvent: broadcastEvent
  11321. };
  11322. };
  11323. var READ_ONLY_MODE_CLASS = resolve('readonly-mode');
  11324. var EDIT_MODE_CLASS = resolve('edit-mode');
  11325. function OuterContainer (spec) {
  11326. var root = build$1(Container.sketch({
  11327. dom: { classes: [resolve('outer-container')].concat(spec.classes) },
  11328. containerBehaviours: derive$1([Swapping.config({
  11329. alpha: READ_ONLY_MODE_CLASS,
  11330. omega: EDIT_MODE_CLASS
  11331. })])
  11332. }));
  11333. return takeover(root);
  11334. }
  11335. function AndroidRealm (scrollIntoView) {
  11336. var alloy = OuterContainer({ classes: [resolve('android-container')] });
  11337. var toolbar = ScrollingToolbar();
  11338. var webapp = api$2();
  11339. var switchToEdit = makeEditSwitch(webapp);
  11340. var socket = makeSocket();
  11341. var dropup = build$2(noop, scrollIntoView);
  11342. alloy.add(toolbar.wrapper());
  11343. alloy.add(socket);
  11344. alloy.add(dropup.component());
  11345. var setToolbarGroups = function (rawGroups) {
  11346. var groups = toolbar.createGroups(rawGroups);
  11347. toolbar.setGroups(groups);
  11348. };
  11349. var setContextToolbar = function (rawGroups) {
  11350. var groups = toolbar.createGroups(rawGroups);
  11351. toolbar.setContextToolbar(groups);
  11352. };
  11353. var focusToolbar = function () {
  11354. toolbar.focus();
  11355. };
  11356. var restoreToolbar = function () {
  11357. toolbar.restoreToolbar();
  11358. };
  11359. var init = function (spec) {
  11360. webapp.set(produce(spec));
  11361. };
  11362. var exit = function () {
  11363. webapp.run(function (w) {
  11364. w.exit();
  11365. Replacing.remove(socket, switchToEdit);
  11366. });
  11367. };
  11368. var updateMode$1 = function (readOnly) {
  11369. updateMode(socket, switchToEdit, readOnly, alloy.root());
  11370. };
  11371. return {
  11372. system: constant(alloy),
  11373. element: alloy.element,
  11374. init: init,
  11375. exit: exit,
  11376. setToolbarGroups: setToolbarGroups,
  11377. setContextToolbar: setContextToolbar,
  11378. focusToolbar: focusToolbar,
  11379. restoreToolbar: restoreToolbar,
  11380. updateMode: updateMode$1,
  11381. socket: constant(socket),
  11382. dropup: constant(dropup)
  11383. };
  11384. }
  11385. var input$1 = function (parent, operation) {
  11386. var input = Element.fromTag('input');
  11387. setAll$1(input, {
  11388. opacity: '0',
  11389. position: 'absolute',
  11390. top: '-1000px',
  11391. left: '-1000px'
  11392. });
  11393. append(parent, input);
  11394. focus$1(input);
  11395. operation(input);
  11396. remove(input);
  11397. };
  11398. var refresh$1 = function (winScope) {
  11399. var sel = winScope.getSelection();
  11400. if (sel.rangeCount > 0) {
  11401. var br = sel.getRangeAt(0);
  11402. var r = winScope.document.createRange();
  11403. r.setStart(br.startContainer, br.startOffset);
  11404. r.setEnd(br.endContainer, br.endOffset);
  11405. sel.removeAllRanges();
  11406. sel.addRange(r);
  11407. }
  11408. };
  11409. var resume$1 = function (cWin, frame) {
  11410. active().each(function (active) {
  11411. if (!eq(active, frame)) {
  11412. blur(active);
  11413. }
  11414. });
  11415. cWin.focus();
  11416. focus$1(Element.fromDom(cWin.document.body));
  11417. refresh$1(cWin);
  11418. };
  11419. var stubborn = function (outerBody, cWin, page, frame) {
  11420. var toEditing = function () {
  11421. resume$1(cWin, frame);
  11422. };
  11423. var toReading = function () {
  11424. input$1(outerBody, blur);
  11425. };
  11426. var captureInput = bind$3(page, 'keydown', function (evt) {
  11427. if (!contains([
  11428. 'input',
  11429. 'textarea'
  11430. ], name(evt.target()))) {
  11431. toEditing();
  11432. }
  11433. });
  11434. var onToolbarTouch = function () {
  11435. };
  11436. var destroy = function () {
  11437. captureInput.unbind();
  11438. };
  11439. return {
  11440. toReading: toReading,
  11441. toEditing: toEditing,
  11442. onToolbarTouch: onToolbarTouch,
  11443. destroy: destroy
  11444. };
  11445. };
  11446. var initEvents$1 = function (editorApi, iosApi, toolstrip, socket, _dropup) {
  11447. var saveSelectionFirst = function () {
  11448. iosApi.run(function (api) {
  11449. api.highlightSelection();
  11450. });
  11451. };
  11452. var refreshIosSelection = function () {
  11453. iosApi.run(function (api) {
  11454. api.refreshSelection();
  11455. });
  11456. };
  11457. var scrollToY = function (yTop, height) {
  11458. var y = yTop - socket.dom().scrollTop;
  11459. iosApi.run(function (api) {
  11460. api.scrollIntoView(y, y + height);
  11461. });
  11462. };
  11463. var scrollToElement = function (_target) {
  11464. scrollToY(iosApi, socket);
  11465. };
  11466. var scrollToCursor = function () {
  11467. editorApi.getCursorBox().each(function (box) {
  11468. scrollToY(box.top(), box.height());
  11469. });
  11470. };
  11471. var clearSelection = function () {
  11472. iosApi.run(function (api) {
  11473. api.clearSelection();
  11474. });
  11475. };
  11476. var clearAndRefresh = function () {
  11477. clearSelection();
  11478. refreshThrottle.throttle();
  11479. };
  11480. var refreshView = function () {
  11481. scrollToCursor();
  11482. iosApi.run(function (api) {
  11483. api.syncHeight();
  11484. });
  11485. };
  11486. var reposition = function () {
  11487. var toolbarHeight = get$5(toolstrip);
  11488. iosApi.run(function (api) {
  11489. api.setViewportOffset(toolbarHeight);
  11490. });
  11491. refreshIosSelection();
  11492. refreshView();
  11493. };
  11494. var toEditing = function () {
  11495. iosApi.run(function (api) {
  11496. api.toEditing();
  11497. });
  11498. };
  11499. var toReading = function () {
  11500. iosApi.run(function (api) {
  11501. api.toReading();
  11502. });
  11503. };
  11504. var onToolbarTouch = function (event) {
  11505. iosApi.run(function (api) {
  11506. api.onToolbarTouch(event);
  11507. });
  11508. };
  11509. var tapping = monitor$1(editorApi);
  11510. var refreshThrottle = last(refreshView, 300);
  11511. var listeners = [
  11512. editorApi.onKeyup(clearAndRefresh),
  11513. editorApi.onNodeChanged(refreshIosSelection),
  11514. editorApi.onDomChanged(refreshThrottle.throttle),
  11515. editorApi.onDomChanged(refreshIosSelection),
  11516. editorApi.onScrollToCursor(function (tinyEvent) {
  11517. tinyEvent.preventDefault();
  11518. refreshThrottle.throttle();
  11519. }),
  11520. editorApi.onScrollToElement(function (event) {
  11521. scrollToElement(event.element());
  11522. }),
  11523. editorApi.onToEditing(toEditing),
  11524. editorApi.onToReading(toReading),
  11525. bind$3(editorApi.doc(), 'touchend', function (touchEvent) {
  11526. if (eq(editorApi.html(), touchEvent.target()) || eq(editorApi.body(), touchEvent.target())) ;
  11527. }),
  11528. bind$3(toolstrip, 'transitionend', function (transitionEvent) {
  11529. if (transitionEvent.raw().propertyName === 'height') {
  11530. reposition();
  11531. }
  11532. }),
  11533. capture$1(toolstrip, 'touchstart', function (touchEvent) {
  11534. saveSelectionFirst();
  11535. onToolbarTouch(touchEvent);
  11536. editorApi.onTouchToolstrip();
  11537. }),
  11538. bind$3(editorApi.body(), 'touchstart', function (evt) {
  11539. clearSelection();
  11540. editorApi.onTouchContent();
  11541. tapping.fireTouchstart(evt);
  11542. }),
  11543. tapping.onTouchmove(),
  11544. tapping.onTouchend(),
  11545. bind$3(editorApi.body(), 'click', function (event) {
  11546. event.kill();
  11547. }),
  11548. bind$3(toolstrip, 'touchmove', function () {
  11549. editorApi.onToolbarScrollStart();
  11550. })
  11551. ];
  11552. var destroy = function () {
  11553. each$1(listeners, function (l) {
  11554. l.unbind();
  11555. });
  11556. };
  11557. return { destroy: destroy };
  11558. };
  11559. function FakeSelection (win, frame) {
  11560. var doc = win.document;
  11561. var container = Element.fromTag('div');
  11562. add$2(container, resolve('unfocused-selections'));
  11563. append(Element.fromDom(doc.documentElement), container);
  11564. var onTouch = bind$3(container, 'touchstart', function (event) {
  11565. event.prevent();
  11566. resume$1(win, frame);
  11567. clear();
  11568. });
  11569. var make = function (rectangle) {
  11570. var span = Element.fromTag('span');
  11571. add$3(span, [
  11572. resolve('layer-editor'),
  11573. resolve('unfocused-selection')
  11574. ]);
  11575. setAll$1(span, {
  11576. left: rectangle.left() + 'px',
  11577. top: rectangle.top() + 'px',
  11578. width: rectangle.width() + 'px',
  11579. height: rectangle.height() + 'px'
  11580. });
  11581. return span;
  11582. };
  11583. var update = function () {
  11584. clear();
  11585. var rectangles = getRectangles(win);
  11586. var spans = map$1(rectangles, make);
  11587. append$1(container, spans);
  11588. };
  11589. var clear = function () {
  11590. empty(container);
  11591. };
  11592. var destroy = function () {
  11593. onTouch.unbind();
  11594. remove(container);
  11595. };
  11596. var isActive = function () {
  11597. return children(container).length > 0;
  11598. };
  11599. return {
  11600. update: update,
  11601. isActive: isActive,
  11602. destroy: destroy,
  11603. clear: clear
  11604. };
  11605. }
  11606. var exports$1 = {}, module = { exports: exports$1 };
  11607. (function (define, exports, module, require) {
  11608. (function (f) {
  11609. if (typeof exports === 'object' && typeof module !== 'undefined') {
  11610. module.exports = f();
  11611. } else if (typeof define === 'function' && define.amd) {
  11612. define([], f);
  11613. } else {
  11614. var g;
  11615. if (typeof window !== 'undefined') {
  11616. g = window;
  11617. } else if (typeof global !== 'undefined') {
  11618. g = global;
  11619. } else if (typeof self !== 'undefined') {
  11620. g = self;
  11621. } else {
  11622. g = this;
  11623. }
  11624. g.EphoxContactWrapper = f();
  11625. }
  11626. }(function () {
  11627. return function () {
  11628. function r(e, n, t) {
  11629. function o(i, f) {
  11630. if (!n[i]) {
  11631. if (!e[i]) {
  11632. var c = 'function' == typeof require && require;
  11633. if (!f && c)
  11634. return c(i, !0);
  11635. if (u)
  11636. return u(i, !0);
  11637. var a = new Error('Cannot find module \'' + i + '\'');
  11638. throw a.code = 'MODULE_NOT_FOUND', a;
  11639. }
  11640. var p = n[i] = { exports: {} };
  11641. e[i][0].call(p.exports, function (r) {
  11642. var n = e[i][1][r];
  11643. return o(n || r);
  11644. }, p, p.exports, r, e, n, t);
  11645. }
  11646. return n[i].exports;
  11647. }
  11648. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  11649. o(t[i]);
  11650. return o;
  11651. }
  11652. return r;
  11653. }()({
  11654. 1: [
  11655. function (require, module, exports) {
  11656. var process = module.exports = {};
  11657. var cachedSetTimeout;
  11658. var cachedClearTimeout;
  11659. function defaultSetTimout() {
  11660. throw new Error('setTimeout has not been defined');
  11661. }
  11662. function defaultClearTimeout() {
  11663. throw new Error('clearTimeout has not been defined');
  11664. }
  11665. (function () {
  11666. try {
  11667. if (typeof setTimeout === 'function') {
  11668. cachedSetTimeout = setTimeout;
  11669. } else {
  11670. cachedSetTimeout = defaultSetTimout;
  11671. }
  11672. } catch (e) {
  11673. cachedSetTimeout = defaultSetTimout;
  11674. }
  11675. try {
  11676. if (typeof clearTimeout === 'function') {
  11677. cachedClearTimeout = clearTimeout;
  11678. } else {
  11679. cachedClearTimeout = defaultClearTimeout;
  11680. }
  11681. } catch (e) {
  11682. cachedClearTimeout = defaultClearTimeout;
  11683. }
  11684. }());
  11685. function runTimeout(fun) {
  11686. if (cachedSetTimeout === setTimeout) {
  11687. return setTimeout(fun, 0);
  11688. }
  11689. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11690. cachedSetTimeout = setTimeout;
  11691. return setTimeout(fun, 0);
  11692. }
  11693. try {
  11694. return cachedSetTimeout(fun, 0);
  11695. } catch (e) {
  11696. try {
  11697. return cachedSetTimeout.call(null, fun, 0);
  11698. } catch (e) {
  11699. return cachedSetTimeout.call(this, fun, 0);
  11700. }
  11701. }
  11702. }
  11703. function runClearTimeout(marker) {
  11704. if (cachedClearTimeout === clearTimeout) {
  11705. return clearTimeout(marker);
  11706. }
  11707. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11708. cachedClearTimeout = clearTimeout;
  11709. return clearTimeout(marker);
  11710. }
  11711. try {
  11712. return cachedClearTimeout(marker);
  11713. } catch (e) {
  11714. try {
  11715. return cachedClearTimeout.call(null, marker);
  11716. } catch (e) {
  11717. return cachedClearTimeout.call(this, marker);
  11718. }
  11719. }
  11720. }
  11721. var queue = [];
  11722. var draining = false;
  11723. var currentQueue;
  11724. var queueIndex = -1;
  11725. function cleanUpNextTick() {
  11726. if (!draining || !currentQueue) {
  11727. return;
  11728. }
  11729. draining = false;
  11730. if (currentQueue.length) {
  11731. queue = currentQueue.concat(queue);
  11732. } else {
  11733. queueIndex = -1;
  11734. }
  11735. if (queue.length) {
  11736. drainQueue();
  11737. }
  11738. }
  11739. function drainQueue() {
  11740. if (draining) {
  11741. return;
  11742. }
  11743. var timeout = runTimeout(cleanUpNextTick);
  11744. draining = true;
  11745. var len = queue.length;
  11746. while (len) {
  11747. currentQueue = queue;
  11748. queue = [];
  11749. while (++queueIndex < len) {
  11750. if (currentQueue) {
  11751. currentQueue[queueIndex].run();
  11752. }
  11753. }
  11754. queueIndex = -1;
  11755. len = queue.length;
  11756. }
  11757. currentQueue = null;
  11758. draining = false;
  11759. runClearTimeout(timeout);
  11760. }
  11761. process.nextTick = function (fun) {
  11762. var args = new Array(arguments.length - 1);
  11763. if (arguments.length > 1) {
  11764. for (var i = 1; i < arguments.length; i++) {
  11765. args[i - 1] = arguments[i];
  11766. }
  11767. }
  11768. queue.push(new Item(fun, args));
  11769. if (queue.length === 1 && !draining) {
  11770. runTimeout(drainQueue);
  11771. }
  11772. };
  11773. function Item(fun, array) {
  11774. this.fun = fun;
  11775. this.array = array;
  11776. }
  11777. Item.prototype.run = function () {
  11778. this.fun.apply(null, this.array);
  11779. };
  11780. process.title = 'browser';
  11781. process.browser = true;
  11782. process.env = {};
  11783. process.argv = [];
  11784. process.version = '';
  11785. process.versions = {};
  11786. function noop() {
  11787. }
  11788. process.on = noop;
  11789. process.addListener = noop;
  11790. process.once = noop;
  11791. process.off = noop;
  11792. process.removeListener = noop;
  11793. process.removeAllListeners = noop;
  11794. process.emit = noop;
  11795. process.prependListener = noop;
  11796. process.prependOnceListener = noop;
  11797. process.listeners = function (name) {
  11798. return [];
  11799. };
  11800. process.binding = function (name) {
  11801. throw new Error('process.binding is not supported');
  11802. };
  11803. process.cwd = function () {
  11804. return '/';
  11805. };
  11806. process.chdir = function (dir) {
  11807. throw new Error('process.chdir is not supported');
  11808. };
  11809. process.umask = function () {
  11810. return 0;
  11811. };
  11812. },
  11813. {}
  11814. ],
  11815. 2: [
  11816. function (require, module, exports) {
  11817. (function (setImmediate) {
  11818. (function (root) {
  11819. var setTimeoutFunc = setTimeout;
  11820. function noop() {
  11821. }
  11822. function bind(fn, thisArg) {
  11823. return function () {
  11824. fn.apply(thisArg, arguments);
  11825. };
  11826. }
  11827. function Promise(fn) {
  11828. if (typeof this !== 'object')
  11829. throw new TypeError('Promises must be constructed via new');
  11830. if (typeof fn !== 'function')
  11831. throw new TypeError('not a function');
  11832. this._state = 0;
  11833. this._handled = false;
  11834. this._value = undefined;
  11835. this._deferreds = [];
  11836. doResolve(fn, this);
  11837. }
  11838. function handle(self, deferred) {
  11839. while (self._state === 3) {
  11840. self = self._value;
  11841. }
  11842. if (self._state === 0) {
  11843. self._deferreds.push(deferred);
  11844. return;
  11845. }
  11846. self._handled = true;
  11847. Promise._immediateFn(function () {
  11848. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  11849. if (cb === null) {
  11850. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  11851. return;
  11852. }
  11853. var ret;
  11854. try {
  11855. ret = cb(self._value);
  11856. } catch (e) {
  11857. reject(deferred.promise, e);
  11858. return;
  11859. }
  11860. resolve(deferred.promise, ret);
  11861. });
  11862. }
  11863. function resolve(self, newValue) {
  11864. try {
  11865. if (newValue === self)
  11866. throw new TypeError('A promise cannot be resolved with itself.');
  11867. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  11868. var then = newValue.then;
  11869. if (newValue instanceof Promise) {
  11870. self._state = 3;
  11871. self._value = newValue;
  11872. finale(self);
  11873. return;
  11874. } else if (typeof then === 'function') {
  11875. doResolve(bind(then, newValue), self);
  11876. return;
  11877. }
  11878. }
  11879. self._state = 1;
  11880. self._value = newValue;
  11881. finale(self);
  11882. } catch (e) {
  11883. reject(self, e);
  11884. }
  11885. }
  11886. function reject(self, newValue) {
  11887. self._state = 2;
  11888. self._value = newValue;
  11889. finale(self);
  11890. }
  11891. function finale(self) {
  11892. if (self._state === 2 && self._deferreds.length === 0) {
  11893. Promise._immediateFn(function () {
  11894. if (!self._handled) {
  11895. Promise._unhandledRejectionFn(self._value);
  11896. }
  11897. });
  11898. }
  11899. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  11900. handle(self, self._deferreds[i]);
  11901. }
  11902. self._deferreds = null;
  11903. }
  11904. function Handler(onFulfilled, onRejected, promise) {
  11905. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  11906. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  11907. this.promise = promise;
  11908. }
  11909. function doResolve(fn, self) {
  11910. var done = false;
  11911. try {
  11912. fn(function (value) {
  11913. if (done)
  11914. return;
  11915. done = true;
  11916. resolve(self, value);
  11917. }, function (reason) {
  11918. if (done)
  11919. return;
  11920. done = true;
  11921. reject(self, reason);
  11922. });
  11923. } catch (ex) {
  11924. if (done)
  11925. return;
  11926. done = true;
  11927. reject(self, ex);
  11928. }
  11929. }
  11930. Promise.prototype['catch'] = function (onRejected) {
  11931. return this.then(null, onRejected);
  11932. };
  11933. Promise.prototype.then = function (onFulfilled, onRejected) {
  11934. var prom = new this.constructor(noop);
  11935. handle(this, new Handler(onFulfilled, onRejected, prom));
  11936. return prom;
  11937. };
  11938. Promise.all = function (arr) {
  11939. var args = Array.prototype.slice.call(arr);
  11940. return new Promise(function (resolve, reject) {
  11941. if (args.length === 0)
  11942. return resolve([]);
  11943. var remaining = args.length;
  11944. function res(i, val) {
  11945. try {
  11946. if (val && (typeof val === 'object' || typeof val === 'function')) {
  11947. var then = val.then;
  11948. if (typeof then === 'function') {
  11949. then.call(val, function (val) {
  11950. res(i, val);
  11951. }, reject);
  11952. return;
  11953. }
  11954. }
  11955. args[i] = val;
  11956. if (--remaining === 0) {
  11957. resolve(args);
  11958. }
  11959. } catch (ex) {
  11960. reject(ex);
  11961. }
  11962. }
  11963. for (var i = 0; i < args.length; i++) {
  11964. res(i, args[i]);
  11965. }
  11966. });
  11967. };
  11968. Promise.resolve = function (value) {
  11969. if (value && typeof value === 'object' && value.constructor === Promise) {
  11970. return value;
  11971. }
  11972. return new Promise(function (resolve) {
  11973. resolve(value);
  11974. });
  11975. };
  11976. Promise.reject = function (value) {
  11977. return new Promise(function (resolve, reject) {
  11978. reject(value);
  11979. });
  11980. };
  11981. Promise.race = function (values) {
  11982. return new Promise(function (resolve, reject) {
  11983. for (var i = 0, len = values.length; i < len; i++) {
  11984. values[i].then(resolve, reject);
  11985. }
  11986. });
  11987. };
  11988. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  11989. setImmediate(fn);
  11990. } : function (fn) {
  11991. setTimeoutFunc(fn, 0);
  11992. };
  11993. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  11994. if (typeof console !== 'undefined' && console) {
  11995. console.warn('Possible Unhandled Promise Rejection:', err);
  11996. }
  11997. };
  11998. Promise._setImmediateFn = function _setImmediateFn(fn) {
  11999. Promise._immediateFn = fn;
  12000. };
  12001. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  12002. Promise._unhandledRejectionFn = fn;
  12003. };
  12004. if (typeof module !== 'undefined' && module.exports) {
  12005. module.exports = Promise;
  12006. } else if (!root.Promise) {
  12007. root.Promise = Promise;
  12008. }
  12009. }(this));
  12010. }.call(this, require('timers').setImmediate));
  12011. },
  12012. { 'timers': 3 }
  12013. ],
  12014. 3: [
  12015. function (require, module, exports) {
  12016. (function (setImmediate, clearImmediate) {
  12017. var nextTick = require('process/browser.js').nextTick;
  12018. var apply = Function.prototype.apply;
  12019. var slice = Array.prototype.slice;
  12020. var immediateIds = {};
  12021. var nextImmediateId = 0;
  12022. exports.setTimeout = function () {
  12023. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  12024. };
  12025. exports.setInterval = function () {
  12026. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12027. };
  12028. exports.clearTimeout = exports.clearInterval = function (timeout) {
  12029. timeout.close();
  12030. };
  12031. function Timeout(id, clearFn) {
  12032. this._id = id;
  12033. this._clearFn = clearFn;
  12034. }
  12035. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  12036. };
  12037. Timeout.prototype.close = function () {
  12038. this._clearFn.call(window, this._id);
  12039. };
  12040. exports.enroll = function (item, msecs) {
  12041. clearTimeout(item._idleTimeoutId);
  12042. item._idleTimeout = msecs;
  12043. };
  12044. exports.unenroll = function (item) {
  12045. clearTimeout(item._idleTimeoutId);
  12046. item._idleTimeout = -1;
  12047. };
  12048. exports._unrefActive = exports.active = function (item) {
  12049. clearTimeout(item._idleTimeoutId);
  12050. var msecs = item._idleTimeout;
  12051. if (msecs >= 0) {
  12052. item._idleTimeoutId = setTimeout(function onTimeout() {
  12053. if (item._onTimeout)
  12054. item._onTimeout();
  12055. }, msecs);
  12056. }
  12057. };
  12058. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  12059. var id = nextImmediateId++;
  12060. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  12061. immediateIds[id] = true;
  12062. nextTick(function onNextTick() {
  12063. if (immediateIds[id]) {
  12064. if (args) {
  12065. fn.apply(null, args);
  12066. } else {
  12067. fn.call(null);
  12068. }
  12069. exports.clearImmediate(id);
  12070. }
  12071. });
  12072. return id;
  12073. };
  12074. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  12075. delete immediateIds[id];
  12076. };
  12077. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  12078. },
  12079. {
  12080. 'process/browser.js': 1,
  12081. 'timers': 3
  12082. }
  12083. ],
  12084. 4: [
  12085. function (require, module, exports) {
  12086. var promisePolyfill = require('promise-polyfill');
  12087. var Global = function () {
  12088. if (typeof window !== 'undefined') {
  12089. return window;
  12090. } else {
  12091. return Function('return this;')();
  12092. }
  12093. }();
  12094. module.exports = { boltExport: Global.Promise || promisePolyfill };
  12095. },
  12096. { 'promise-polyfill': 2 }
  12097. ]
  12098. }, {}, [4])(4);
  12099. }));
  12100. }(undefined, exports$1, module, undefined));
  12101. var Promise$1 = module.exports.boltExport;
  12102. var nu$7 = function (baseFn) {
  12103. var data = Option.none();
  12104. var callbacks = [];
  12105. var map = function (f) {
  12106. return nu$7(function (nCallback) {
  12107. get(function (data) {
  12108. nCallback(f(data));
  12109. });
  12110. });
  12111. };
  12112. var get = function (nCallback) {
  12113. if (isReady()) {
  12114. call(nCallback);
  12115. } else {
  12116. callbacks.push(nCallback);
  12117. }
  12118. };
  12119. var set = function (x) {
  12120. data = Option.some(x);
  12121. run(callbacks);
  12122. callbacks = [];
  12123. };
  12124. var isReady = function () {
  12125. return data.isSome();
  12126. };
  12127. var run = function (cbs) {
  12128. each$1(cbs, call);
  12129. };
  12130. var call = function (cb) {
  12131. data.each(function (x) {
  12132. domGlobals.setTimeout(function () {
  12133. cb(x);
  12134. }, 0);
  12135. });
  12136. };
  12137. baseFn(set);
  12138. return {
  12139. get: get,
  12140. map: map,
  12141. isReady: isReady
  12142. };
  12143. };
  12144. var pure$1 = function (a) {
  12145. return nu$7(function (callback) {
  12146. callback(a);
  12147. });
  12148. };
  12149. var LazyValue = {
  12150. nu: nu$7,
  12151. pure: pure$1
  12152. };
  12153. var errorReporter = function (err) {
  12154. domGlobals.setTimeout(function () {
  12155. throw err;
  12156. }, 0);
  12157. };
  12158. var make$4 = function (run) {
  12159. var get = function (callback) {
  12160. run().then(callback, errorReporter);
  12161. };
  12162. var map = function (fab) {
  12163. return make$4(function () {
  12164. return run().then(fab);
  12165. });
  12166. };
  12167. var bind = function (aFutureB) {
  12168. return make$4(function () {
  12169. return run().then(function (v) {
  12170. return aFutureB(v).toPromise();
  12171. });
  12172. });
  12173. };
  12174. var anonBind = function (futureB) {
  12175. return make$4(function () {
  12176. return run().then(function () {
  12177. return futureB.toPromise();
  12178. });
  12179. });
  12180. };
  12181. var toLazy = function () {
  12182. return LazyValue.nu(get);
  12183. };
  12184. var toCached = function () {
  12185. var cache = null;
  12186. return make$4(function () {
  12187. if (cache === null) {
  12188. cache = run();
  12189. }
  12190. return cache;
  12191. });
  12192. };
  12193. var toPromise = run;
  12194. return {
  12195. map: map,
  12196. bind: bind,
  12197. anonBind: anonBind,
  12198. toLazy: toLazy,
  12199. toCached: toCached,
  12200. toPromise: toPromise,
  12201. get: get
  12202. };
  12203. };
  12204. var nu$8 = function (baseFn) {
  12205. return make$4(function () {
  12206. return new Promise$1(baseFn);
  12207. });
  12208. };
  12209. var pure$2 = function (a) {
  12210. return make$4(function () {
  12211. return Promise$1.resolve(a);
  12212. });
  12213. };
  12214. var Future = {
  12215. nu: nu$8,
  12216. pure: pure$2
  12217. };
  12218. var adjust = function (value, destination, amount) {
  12219. if (Math.abs(value - destination) <= amount) {
  12220. return Option.none();
  12221. } else if (value < destination) {
  12222. return Option.some(value + amount);
  12223. } else {
  12224. return Option.some(value - amount);
  12225. }
  12226. };
  12227. var create$5 = function () {
  12228. var interval = null;
  12229. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  12230. var finished = false;
  12231. var finish = function (v) {
  12232. finished = true;
  12233. doFinish(v);
  12234. };
  12235. global$4.clearInterval(interval);
  12236. var abort = function (v) {
  12237. global$4.clearInterval(interval);
  12238. finish(v);
  12239. };
  12240. interval = global$4.setInterval(function () {
  12241. var value = getCurrent();
  12242. adjust(value, destination, amount).fold(function () {
  12243. global$4.clearInterval(interval);
  12244. finish(destination);
  12245. }, function (s) {
  12246. increment(s, abort);
  12247. if (!finished) {
  12248. var newValue = getCurrent();
  12249. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  12250. global$4.clearInterval(interval);
  12251. finish(destination);
  12252. }
  12253. }
  12254. });
  12255. }, rate);
  12256. };
  12257. return { animate: animate };
  12258. };
  12259. var findDevice = function (deviceWidth, deviceHeight) {
  12260. var devices = [
  12261. {
  12262. width: 320,
  12263. height: 480,
  12264. keyboard: {
  12265. portrait: 300,
  12266. landscape: 240
  12267. }
  12268. },
  12269. {
  12270. width: 320,
  12271. height: 568,
  12272. keyboard: {
  12273. portrait: 300,
  12274. landscape: 240
  12275. }
  12276. },
  12277. {
  12278. width: 375,
  12279. height: 667,
  12280. keyboard: {
  12281. portrait: 305,
  12282. landscape: 240
  12283. }
  12284. },
  12285. {
  12286. width: 414,
  12287. height: 736,
  12288. keyboard: {
  12289. portrait: 320,
  12290. landscape: 240
  12291. }
  12292. },
  12293. {
  12294. width: 768,
  12295. height: 1024,
  12296. keyboard: {
  12297. portrait: 320,
  12298. landscape: 400
  12299. }
  12300. },
  12301. {
  12302. width: 1024,
  12303. height: 1366,
  12304. keyboard: {
  12305. portrait: 380,
  12306. landscape: 460
  12307. }
  12308. }
  12309. ];
  12310. return findMap(devices, function (device) {
  12311. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  12312. }).getOr({
  12313. portrait: deviceHeight / 5,
  12314. landscape: deviceWidth / 4
  12315. });
  12316. };
  12317. var softKeyboardLimits = function (outerWindow) {
  12318. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  12319. };
  12320. var accountableKeyboardHeight = function (outerWindow) {
  12321. var portrait = get$b(outerWindow).isPortrait();
  12322. var limits = softKeyboardLimits(outerWindow);
  12323. var keyboard = portrait ? limits.portrait : limits.landscape;
  12324. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  12325. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  12326. };
  12327. var getGreenzone = function (socket, dropup) {
  12328. var outerWindow = owner(socket).dom().defaultView;
  12329. var viewportHeight = get$5(socket) + get$5(dropup);
  12330. var acc = accountableKeyboardHeight(outerWindow);
  12331. return viewportHeight - acc;
  12332. };
  12333. var updatePadding = function (contentBody, socket, dropup) {
  12334. var greenzoneHeight = getGreenzone(socket, dropup);
  12335. var deltaHeight = get$5(socket) + get$5(dropup) - greenzoneHeight;
  12336. set$3(contentBody, 'padding-bottom', deltaHeight + 'px');
  12337. };
  12338. var fixture = Adt.generate([
  12339. {
  12340. fixed: [
  12341. 'element',
  12342. 'property',
  12343. 'offsetY'
  12344. ]
  12345. },
  12346. {
  12347. scroller: [
  12348. 'element',
  12349. 'offsetY'
  12350. ]
  12351. }
  12352. ]);
  12353. var yFixedData = 'data-' + resolve('position-y-fixed');
  12354. var yFixedProperty = 'data-' + resolve('y-property');
  12355. var yScrollingData = 'data-' + resolve('scrolling');
  12356. var windowSizeData = 'data-' + resolve('last-window-height');
  12357. var getYFixedData = function (element) {
  12358. return safeParse(element, yFixedData);
  12359. };
  12360. var getYFixedProperty = function (element) {
  12361. return get$1(element, yFixedProperty);
  12362. };
  12363. var getLastWindowSize = function (element) {
  12364. return safeParse(element, windowSizeData);
  12365. };
  12366. var classifyFixed = function (element, offsetY) {
  12367. var prop = getYFixedProperty(element);
  12368. return fixture.fixed(element, prop, offsetY);
  12369. };
  12370. var classifyScrolling = function (element, offsetY) {
  12371. return fixture.scroller(element, offsetY);
  12372. };
  12373. var classify = function (element) {
  12374. var offsetY = getYFixedData(element);
  12375. var classifier = get$1(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  12376. return classifier(element, offsetY);
  12377. };
  12378. var findFixtures = function (container) {
  12379. var candidates = descendants(container, '[' + yFixedData + ']');
  12380. return map$1(candidates, classify);
  12381. };
  12382. var takeoverToolbar = function (toolbar) {
  12383. var oldToolbarStyle = get$1(toolbar, 'style');
  12384. setAll$1(toolbar, {
  12385. position: 'absolute',
  12386. top: '0px'
  12387. });
  12388. set(toolbar, yFixedData, '0px');
  12389. set(toolbar, yFixedProperty, 'top');
  12390. var restore = function () {
  12391. set(toolbar, 'style', oldToolbarStyle || '');
  12392. remove$1(toolbar, yFixedData);
  12393. remove$1(toolbar, yFixedProperty);
  12394. };
  12395. return { restore: restore };
  12396. };
  12397. var takeoverViewport = function (toolbarHeight, height, viewport) {
  12398. var oldViewportStyle = get$1(viewport, 'style');
  12399. register(viewport);
  12400. setAll$1(viewport, {
  12401. position: 'absolute',
  12402. height: height + 'px',
  12403. width: '100%',
  12404. top: toolbarHeight + 'px'
  12405. });
  12406. set(viewport, yFixedData, toolbarHeight + 'px');
  12407. set(viewport, yScrollingData, 'true');
  12408. set(viewport, yFixedProperty, 'top');
  12409. var restore = function () {
  12410. deregister(viewport);
  12411. set(viewport, 'style', oldViewportStyle || '');
  12412. remove$1(viewport, yFixedData);
  12413. remove$1(viewport, yScrollingData);
  12414. remove$1(viewport, yFixedProperty);
  12415. };
  12416. return { restore: restore };
  12417. };
  12418. var takeoverDropup = function (dropup) {
  12419. var oldDropupStyle = get$1(dropup, 'style');
  12420. setAll$1(dropup, {
  12421. position: 'absolute',
  12422. bottom: '0px'
  12423. });
  12424. set(dropup, yFixedData, '0px');
  12425. set(dropup, yFixedProperty, 'bottom');
  12426. var restore = function () {
  12427. set(dropup, 'style', oldDropupStyle || '');
  12428. remove$1(dropup, yFixedData);
  12429. remove$1(dropup, yFixedProperty);
  12430. };
  12431. return { restore: restore };
  12432. };
  12433. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12434. var outerWindow = owner(viewport).dom().defaultView;
  12435. var winH = outerWindow.innerHeight;
  12436. set(viewport, windowSizeData, winH + 'px');
  12437. return winH - toolbarHeight - dropupHeight;
  12438. };
  12439. var takeover$1 = function (viewport, contentBody, toolbar, dropup) {
  12440. var outerWindow = owner(viewport).dom().defaultView;
  12441. var toolbarSetup = takeoverToolbar(toolbar);
  12442. var toolbarHeight = get$5(toolbar);
  12443. var dropupHeight = get$5(dropup);
  12444. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12445. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12446. var dropupSetup = takeoverDropup(dropup);
  12447. var isActive = true;
  12448. var restore = function () {
  12449. isActive = false;
  12450. toolbarSetup.restore();
  12451. viewportSetup.restore();
  12452. dropupSetup.restore();
  12453. };
  12454. var isExpanding = function () {
  12455. var currentWinHeight = outerWindow.innerHeight;
  12456. var lastWinHeight = getLastWindowSize(viewport);
  12457. return currentWinHeight > lastWinHeight;
  12458. };
  12459. var refresh = function () {
  12460. if (isActive) {
  12461. var newToolbarHeight = get$5(toolbar);
  12462. var dropupHeight_1 = get$5(dropup);
  12463. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12464. set(viewport, yFixedData, newToolbarHeight + 'px');
  12465. set$3(viewport, 'height', newHeight + 'px');
  12466. updatePadding(contentBody, viewport, dropup);
  12467. }
  12468. };
  12469. var setViewportOffset = function (newYOffset) {
  12470. var offsetPx = newYOffset + 'px';
  12471. set(viewport, yFixedData, offsetPx);
  12472. refresh();
  12473. };
  12474. updatePadding(contentBody, viewport, dropup);
  12475. return {
  12476. setViewportOffset: setViewportOffset,
  12477. isExpanding: isExpanding,
  12478. isShrinking: not(isExpanding),
  12479. refresh: refresh,
  12480. restore: restore
  12481. };
  12482. };
  12483. var animator = create$5();
  12484. var ANIMATION_STEP = 15;
  12485. var NUM_TOP_ANIMATION_FRAMES = 10;
  12486. var ANIMATION_RATE = 10;
  12487. var lastScroll = 'data-' + resolve('last-scroll-top');
  12488. var getTop = function (element) {
  12489. var raw = getRaw(element, 'top').getOr('0');
  12490. return parseInt(raw, 10);
  12491. };
  12492. var getScrollTop = function (element) {
  12493. return parseInt(element.dom().scrollTop, 10);
  12494. };
  12495. var moveScrollAndTop = function (element, destination, finalTop) {
  12496. return Future.nu(function (callback) {
  12497. var getCurrent = curry(getScrollTop, element);
  12498. var update = function (newScroll) {
  12499. element.dom().scrollTop = newScroll;
  12500. set$3(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12501. };
  12502. var finish = function () {
  12503. element.dom().scrollTop = destination;
  12504. set$3(element, 'top', finalTop + 'px');
  12505. callback(destination);
  12506. };
  12507. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12508. });
  12509. };
  12510. var moveOnlyScroll = function (element, destination) {
  12511. return Future.nu(function (callback) {
  12512. var getCurrent = curry(getScrollTop, element);
  12513. set(element, lastScroll, getCurrent());
  12514. var update = function (newScroll, abort) {
  12515. var previous = safeParse(element, lastScroll);
  12516. if (previous !== element.dom().scrollTop) {
  12517. abort(element.dom().scrollTop);
  12518. } else {
  12519. element.dom().scrollTop = newScroll;
  12520. set(element, lastScroll, newScroll);
  12521. }
  12522. };
  12523. var finish = function () {
  12524. element.dom().scrollTop = destination;
  12525. set(element, lastScroll, destination);
  12526. callback(destination);
  12527. };
  12528. var distance = Math.abs(destination - getCurrent());
  12529. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12530. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12531. });
  12532. };
  12533. var moveOnlyTop = function (element, destination) {
  12534. return Future.nu(function (callback) {
  12535. var getCurrent = curry(getTop, element);
  12536. var update = function (newTop) {
  12537. set$3(element, 'top', newTop + 'px');
  12538. };
  12539. var finish = function () {
  12540. update(destination);
  12541. callback(destination);
  12542. };
  12543. var distance = Math.abs(destination - getCurrent());
  12544. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12545. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12546. });
  12547. };
  12548. var updateTop = function (element, amount) {
  12549. var newTop = amount + getYFixedData(element) + 'px';
  12550. set$3(element, 'top', newTop);
  12551. };
  12552. var moveWindowScroll = function (toolbar, viewport, destY) {
  12553. var outerWindow = owner(toolbar).dom().defaultView;
  12554. return Future.nu(function (callback) {
  12555. updateTop(toolbar, destY);
  12556. updateTop(viewport, destY);
  12557. outerWindow.scrollTo(0, destY);
  12558. callback(destY);
  12559. });
  12560. };
  12561. function BackgroundActivity (doAction) {
  12562. var action = Cell(LazyValue.pure({}));
  12563. var start = function (value) {
  12564. var future = LazyValue.nu(function (callback) {
  12565. return doAction(value).get(callback);
  12566. });
  12567. action.set(future);
  12568. };
  12569. var idle = function (g) {
  12570. action.get().get(function () {
  12571. g();
  12572. });
  12573. };
  12574. return {
  12575. start: start,
  12576. idle: idle
  12577. };
  12578. }
  12579. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12580. var greenzone = getGreenzone(socket, dropup);
  12581. var refreshCursor = curry(refresh$1, cWin);
  12582. if (top > greenzone || bottom > greenzone) {
  12583. moveOnlyScroll(socket, socket.dom().scrollTop - greenzone + bottom).get(refreshCursor);
  12584. } else if (top < 0) {
  12585. moveOnlyScroll(socket, socket.dom().scrollTop + top).get(refreshCursor);
  12586. }
  12587. };
  12588. var par = function (asyncValues, nu) {
  12589. return nu(function (callback) {
  12590. var r = [];
  12591. var count = 0;
  12592. var cb = function (i) {
  12593. return function (value) {
  12594. r[i] = value;
  12595. count++;
  12596. if (count >= asyncValues.length) {
  12597. callback(r);
  12598. }
  12599. };
  12600. };
  12601. if (asyncValues.length === 0) {
  12602. callback([]);
  12603. } else {
  12604. each$1(asyncValues, function (asyncValue, i) {
  12605. asyncValue.get(cb(i));
  12606. });
  12607. }
  12608. });
  12609. };
  12610. var par$1 = function (futures) {
  12611. return par(futures, Future.nu);
  12612. };
  12613. var updateFixed = function (element, property, winY, offsetY) {
  12614. var destination = winY + offsetY;
  12615. set$3(element, property, destination + 'px');
  12616. return Future.pure(offsetY);
  12617. };
  12618. var updateScrollingFixed = function (element, winY, offsetY) {
  12619. var destTop = winY + offsetY;
  12620. var oldProp = getRaw(element, 'top').getOr(offsetY);
  12621. var delta = destTop - parseInt(oldProp, 10);
  12622. var destScroll = element.dom().scrollTop + delta;
  12623. return moveScrollAndTop(element, destScroll, destTop);
  12624. };
  12625. var updateFixture = function (fixture, winY) {
  12626. return fixture.fold(function (element, property, offsetY) {
  12627. return updateFixed(element, property, winY, offsetY);
  12628. }, function (element, offsetY) {
  12629. return updateScrollingFixed(element, winY, offsetY);
  12630. });
  12631. };
  12632. var updatePositions = function (container, winY) {
  12633. var fixtures = findFixtures(container);
  12634. var updates = map$1(fixtures, function (fixture) {
  12635. return updateFixture(fixture, winY);
  12636. });
  12637. return par$1(updates);
  12638. };
  12639. var VIEW_MARGIN = 5;
  12640. var register$2 = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  12641. var scroller = BackgroundActivity(function (y) {
  12642. return moveWindowScroll(toolstrip, socket, y);
  12643. });
  12644. var scrollBounds = function () {
  12645. var rects = getRectangles(cWin);
  12646. return Option.from(rects[0]).bind(function (rect) {
  12647. var viewTop = rect.top() - socket.dom().scrollTop;
  12648. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  12649. return outside ? Option.some({
  12650. top: constant(viewTop),
  12651. bottom: constant(viewTop + rect.height())
  12652. }) : Option.none();
  12653. });
  12654. };
  12655. var scrollThrottle = last(function () {
  12656. scroller.idle(function () {
  12657. updatePositions(container, outerWindow.pageYOffset).get(function () {
  12658. var extraScroll = scrollBounds();
  12659. extraScroll.each(function (extra) {
  12660. socket.dom().scrollTop = socket.dom().scrollTop + extra.top();
  12661. });
  12662. scroller.start(0);
  12663. structure.refresh();
  12664. });
  12665. });
  12666. }, 1000);
  12667. var onScroll = bind$3(Element.fromDom(outerWindow), 'scroll', function () {
  12668. if (outerWindow.pageYOffset < 0) {
  12669. return;
  12670. }
  12671. scrollThrottle.throttle();
  12672. });
  12673. updatePositions(container, outerWindow.pageYOffset).get(identity);
  12674. return { unbind: onScroll.unbind };
  12675. };
  12676. var setup$3 = function (bag) {
  12677. var cWin = bag.cWin;
  12678. var ceBody = bag.ceBody;
  12679. var socket = bag.socket;
  12680. var toolstrip = bag.toolstrip;
  12681. var contentElement = bag.contentElement;
  12682. var keyboardType = bag.keyboardType;
  12683. var outerWindow = bag.outerWindow;
  12684. var dropup = bag.dropup;
  12685. var outerBody = bag.outerBody;
  12686. var structure = takeover$1(socket, ceBody, toolstrip, dropup);
  12687. var keyboardModel = keyboardType(outerBody, cWin, body(), contentElement);
  12688. var toEditing = function () {
  12689. keyboardModel.toEditing();
  12690. clearSelection();
  12691. };
  12692. var toReading = function () {
  12693. keyboardModel.toReading();
  12694. };
  12695. var onToolbarTouch = function (_event) {
  12696. keyboardModel.onToolbarTouch();
  12697. };
  12698. var onOrientation = onChange(outerWindow, {
  12699. onChange: noop,
  12700. onReady: structure.refresh
  12701. });
  12702. onOrientation.onAdjustment(function () {
  12703. structure.refresh();
  12704. });
  12705. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  12706. if (structure.isExpanding()) {
  12707. structure.refresh();
  12708. }
  12709. });
  12710. var onScroll = register$2(toolstrip, socket, outerBody, outerWindow, structure, cWin);
  12711. var unfocusedSelection = FakeSelection(cWin, contentElement);
  12712. var refreshSelection = function () {
  12713. if (unfocusedSelection.isActive()) {
  12714. unfocusedSelection.update();
  12715. }
  12716. };
  12717. var highlightSelection = function () {
  12718. unfocusedSelection.update();
  12719. };
  12720. var clearSelection = function () {
  12721. unfocusedSelection.clear();
  12722. };
  12723. var scrollIntoView$1 = function (top, bottom) {
  12724. scrollIntoView(cWin, socket, dropup, top, bottom);
  12725. };
  12726. var syncHeight = function () {
  12727. set$3(contentElement, 'height', contentElement.dom().contentWindow.document.body.scrollHeight + 'px');
  12728. };
  12729. var setViewportOffset = function (newYOffset) {
  12730. structure.setViewportOffset(newYOffset);
  12731. moveOnlyTop(socket, newYOffset).get(identity);
  12732. };
  12733. var destroy = function () {
  12734. structure.restore();
  12735. onOrientation.destroy();
  12736. onScroll.unbind();
  12737. onResize.unbind();
  12738. keyboardModel.destroy();
  12739. unfocusedSelection.destroy();
  12740. input$1(body(), blur);
  12741. };
  12742. return {
  12743. toEditing: toEditing,
  12744. toReading: toReading,
  12745. onToolbarTouch: onToolbarTouch,
  12746. refreshSelection: refreshSelection,
  12747. clearSelection: clearSelection,
  12748. highlightSelection: highlightSelection,
  12749. scrollIntoView: scrollIntoView$1,
  12750. updateToolbarPadding: noop,
  12751. setViewportOffset: setViewportOffset,
  12752. syncHeight: syncHeight,
  12753. refreshStructure: structure.refresh,
  12754. destroy: destroy
  12755. };
  12756. };
  12757. var create$6 = function (platform, mask) {
  12758. var meta = tag();
  12759. var priorState = value$2();
  12760. var scrollEvents = value$2();
  12761. var iosApi = api$2();
  12762. var iosEvents = api$2();
  12763. var enter = function () {
  12764. mask.hide();
  12765. var doc = Element.fromDom(domGlobals.document);
  12766. getActiveApi(platform.editor).each(function (editorApi) {
  12767. priorState.set({
  12768. socketHeight: getRaw(platform.socket, 'height'),
  12769. iframeHeight: getRaw(editorApi.frame(), 'height'),
  12770. outerScroll: domGlobals.document.body.scrollTop
  12771. });
  12772. scrollEvents.set({ exclusives: exclusive(doc, '.' + scrollable) });
  12773. add$2(platform.container, resolve('fullscreen-maximized'));
  12774. clobberStyles(platform.container, editorApi.body());
  12775. meta.maximize();
  12776. set$3(platform.socket, 'overflow', 'scroll');
  12777. set$3(platform.socket, '-webkit-overflow-scrolling', 'touch');
  12778. focus$1(editorApi.body());
  12779. iosApi.set(setup$3({
  12780. cWin: editorApi.win(),
  12781. ceBody: editorApi.body(),
  12782. socket: platform.socket,
  12783. toolstrip: platform.toolstrip,
  12784. dropup: platform.dropup.element(),
  12785. contentElement: editorApi.frame(),
  12786. outerBody: platform.body,
  12787. outerWindow: platform.win,
  12788. keyboardType: stubborn
  12789. }));
  12790. iosApi.run(function (api) {
  12791. api.syncHeight();
  12792. });
  12793. iosEvents.set(initEvents$1(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  12794. });
  12795. };
  12796. var exit = function () {
  12797. meta.restore();
  12798. iosEvents.clear();
  12799. iosApi.clear();
  12800. mask.show();
  12801. priorState.on(function (s) {
  12802. s.socketHeight.each(function (h) {
  12803. set$3(platform.socket, 'height', h);
  12804. });
  12805. s.iframeHeight.each(function (h) {
  12806. set$3(platform.editor.getFrame(), 'height', h);
  12807. });
  12808. domGlobals.document.body.scrollTop = s.scrollTop;
  12809. });
  12810. priorState.clear();
  12811. scrollEvents.on(function (s) {
  12812. s.exclusives.unbind();
  12813. });
  12814. scrollEvents.clear();
  12815. remove$4(platform.container, resolve('fullscreen-maximized'));
  12816. restoreStyles();
  12817. deregister(platform.toolbar);
  12818. remove$5(platform.socket, 'overflow');
  12819. remove$5(platform.socket, '-webkit-overflow-scrolling');
  12820. blur(platform.editor.getFrame());
  12821. getActiveApi(platform.editor).each(function (editorApi) {
  12822. editorApi.clearSelection();
  12823. });
  12824. };
  12825. var refreshStructure = function () {
  12826. iosApi.run(function (api) {
  12827. api.refreshStructure();
  12828. });
  12829. };
  12830. return {
  12831. enter: enter,
  12832. refreshStructure: refreshStructure,
  12833. exit: exit
  12834. };
  12835. };
  12836. var produce$1 = function (raw) {
  12837. var mobile = asRawOrDie('Getting IosWebapp schema', MobileSchema, raw);
  12838. set$3(mobile.toolstrip, 'width', '100%');
  12839. set$3(mobile.container, 'position', 'relative');
  12840. var onView = function () {
  12841. mobile.setReadOnly(mobile.readOnlyOnInit());
  12842. mode.enter();
  12843. };
  12844. var mask = build$1(sketch$9(onView, mobile.translate));
  12845. mobile.alloy.add(mask);
  12846. var maskApi = {
  12847. show: function () {
  12848. mobile.alloy.add(mask);
  12849. },
  12850. hide: function () {
  12851. mobile.alloy.remove(mask);
  12852. }
  12853. };
  12854. var mode = create$6(mobile, maskApi);
  12855. return {
  12856. setReadOnly: mobile.setReadOnly,
  12857. refreshStructure: mode.refreshStructure,
  12858. enter: mode.enter,
  12859. exit: mode.exit,
  12860. destroy: noop
  12861. };
  12862. };
  12863. function IosRealm (scrollIntoView) {
  12864. var alloy = OuterContainer({ classes: [resolve('ios-container')] });
  12865. var toolbar = ScrollingToolbar();
  12866. var webapp = api$2();
  12867. var switchToEdit = makeEditSwitch(webapp);
  12868. var socket = makeSocket();
  12869. var dropup = build$2(function () {
  12870. webapp.run(function (w) {
  12871. w.refreshStructure();
  12872. });
  12873. }, scrollIntoView);
  12874. alloy.add(toolbar.wrapper());
  12875. alloy.add(socket);
  12876. alloy.add(dropup.component());
  12877. var setToolbarGroups = function (rawGroups) {
  12878. var groups = toolbar.createGroups(rawGroups);
  12879. toolbar.setGroups(groups);
  12880. };
  12881. var setContextToolbar = function (rawGroups) {
  12882. var groups = toolbar.createGroups(rawGroups);
  12883. toolbar.setContextToolbar(groups);
  12884. };
  12885. var focusToolbar = function () {
  12886. toolbar.focus();
  12887. };
  12888. var restoreToolbar = function () {
  12889. toolbar.restoreToolbar();
  12890. };
  12891. var init = function (spec) {
  12892. webapp.set(produce$1(spec));
  12893. };
  12894. var exit = function () {
  12895. webapp.run(function (w) {
  12896. Replacing.remove(socket, switchToEdit);
  12897. w.exit();
  12898. });
  12899. };
  12900. var updateMode$1 = function (readOnly) {
  12901. updateMode(socket, switchToEdit, readOnly, alloy.root());
  12902. };
  12903. return {
  12904. system: constant(alloy),
  12905. element: alloy.element,
  12906. init: init,
  12907. exit: exit,
  12908. setToolbarGroups: setToolbarGroups,
  12909. setContextToolbar: setContextToolbar,
  12910. focusToolbar: focusToolbar,
  12911. restoreToolbar: restoreToolbar,
  12912. updateMode: updateMode$1,
  12913. socket: constant(socket),
  12914. dropup: constant(dropup)
  12915. };
  12916. }
  12917. var global$5 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12918. var derive$3 = function (editor) {
  12919. var base = get(editor.settings, 'skin_url').fold(function () {
  12920. return global$5.baseURL + '/skins/ui/oxide';
  12921. }, function (url) {
  12922. return url;
  12923. });
  12924. return {
  12925. content: base + '/content.mobile.min.css',
  12926. ui: base + '/skin.mobile.min.css'
  12927. };
  12928. };
  12929. var fireChange = function (realm, command, state) {
  12930. realm.system().broadcastOn([formatChanged], {
  12931. command: command,
  12932. state: state
  12933. });
  12934. };
  12935. var init$5 = function (realm, editor) {
  12936. var allFormats = keys(editor.formatter.get());
  12937. each$1(allFormats, function (command) {
  12938. editor.formatter.formatChanged(command, function (state) {
  12939. fireChange(realm, command, state);
  12940. });
  12941. });
  12942. each$1([
  12943. 'ul',
  12944. 'ol'
  12945. ], function (command) {
  12946. editor.selection.selectorChanged(command, function (state, _data) {
  12947. fireChange(realm, command, state);
  12948. });
  12949. });
  12950. };
  12951. var fireSkinLoaded = function (editor) {
  12952. return function () {
  12953. var done = function () {
  12954. editor._skinLoaded = true;
  12955. editor.fire('SkinLoaded');
  12956. };
  12957. if (editor.initialized) {
  12958. done();
  12959. } else {
  12960. editor.on('init', done);
  12961. }
  12962. };
  12963. };
  12964. var READING = 'toReading';
  12965. var EDITING = 'toEditing';
  12966. var renderMobileTheme = function (editor) {
  12967. var renderUI = function () {
  12968. var targetNode = editor.getElement();
  12969. var cssUrls = derive$3(editor);
  12970. if (isSkinDisabled(editor) === false) {
  12971. editor.contentCSS.push(cssUrls.content);
  12972. global$1.DOM.styleSheetLoader.load(cssUrls.ui, fireSkinLoaded(editor));
  12973. } else {
  12974. fireSkinLoaded(editor)();
  12975. }
  12976. var doScrollIntoView = function () {
  12977. editor.fire('ScrollIntoView');
  12978. };
  12979. var realm = detect$3().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  12980. var original = Element.fromDom(targetNode);
  12981. attachSystemAfter(original, realm.system());
  12982. var findFocusIn = function (elem) {
  12983. return search(elem).bind(function (focused) {
  12984. return realm.system().getByDom(focused).toOption();
  12985. });
  12986. };
  12987. var outerWindow = targetNode.ownerDocument.defaultView;
  12988. var orientation = onChange(outerWindow, {
  12989. onChange: function () {
  12990. var alloy = realm.system();
  12991. alloy.broadcastOn([orientationChanged], { width: getActualWidth(outerWindow) });
  12992. },
  12993. onReady: noop
  12994. });
  12995. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  12996. if (ro === false) {
  12997. editor.selection.collapse();
  12998. }
  12999. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  13000. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  13001. editor.setMode(ro === true ? 'readonly' : 'design');
  13002. editor.fire(ro === true ? READING : EDITING);
  13003. realm.updateMode(ro);
  13004. };
  13005. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  13006. var dynamic = dynamicGroup.get();
  13007. var toolbars = {
  13008. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  13009. main: dynamic.backToMask.concat(mainGroups.get())
  13010. };
  13011. return toolbars;
  13012. };
  13013. var bindHandler = function (label, handler) {
  13014. editor.on(label, handler);
  13015. return {
  13016. unbind: function () {
  13017. editor.off(label);
  13018. }
  13019. };
  13020. };
  13021. editor.on('init', function () {
  13022. realm.init({
  13023. editor: {
  13024. getFrame: function () {
  13025. return Element.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  13026. },
  13027. onDomChanged: function () {
  13028. return { unbind: noop };
  13029. },
  13030. onToReading: function (handler) {
  13031. return bindHandler(READING, handler);
  13032. },
  13033. onToEditing: function (handler) {
  13034. return bindHandler(EDITING, handler);
  13035. },
  13036. onScrollToCursor: function (handler) {
  13037. editor.on('ScrollIntoView', function (tinyEvent) {
  13038. handler(tinyEvent);
  13039. });
  13040. var unbind = function () {
  13041. editor.off('ScrollIntoView');
  13042. orientation.destroy();
  13043. };
  13044. return { unbind: unbind };
  13045. },
  13046. onTouchToolstrip: function () {
  13047. hideDropup();
  13048. },
  13049. onTouchContent: function () {
  13050. var toolbar = Element.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar')));
  13051. findFocusIn(toolbar).each(emitExecute);
  13052. realm.restoreToolbar();
  13053. hideDropup();
  13054. },
  13055. onTapContent: function (evt) {
  13056. var target = evt.target();
  13057. if (name(target) === 'img') {
  13058. editor.selection.select(target.dom());
  13059. evt.kill();
  13060. } else if (name(target) === 'a') {
  13061. var component = realm.system().getByDom(Element.fromDom(editor.editorContainer));
  13062. component.each(function (container) {
  13063. if (Swapping.isAlpha(container)) {
  13064. openLink(target.dom());
  13065. }
  13066. });
  13067. }
  13068. }
  13069. },
  13070. container: Element.fromDom(editor.editorContainer),
  13071. socket: Element.fromDom(editor.contentAreaContainer),
  13072. toolstrip: Element.fromDom(editor.editorContainer.querySelector('.' + resolve('toolstrip'))),
  13073. toolbar: Element.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))),
  13074. dropup: realm.dropup(),
  13075. alloy: realm.system(),
  13076. translate: noop,
  13077. setReadOnly: function (ro) {
  13078. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  13079. },
  13080. readOnlyOnInit: function () {
  13081. return readOnlyOnInit();
  13082. }
  13083. });
  13084. var hideDropup = function () {
  13085. realm.dropup().disappear(function () {
  13086. realm.system().broadcastOn([dropupDismissed], {});
  13087. });
  13088. };
  13089. var backToMaskGroup = {
  13090. label: 'The first group',
  13091. scrollable: false,
  13092. items: [forToolbar('back', function () {
  13093. editor.selection.collapse();
  13094. realm.exit();
  13095. }, {}, editor)]
  13096. };
  13097. var backToReadOnlyGroup = {
  13098. label: 'Back to read only',
  13099. scrollable: false,
  13100. items: [forToolbar('readonly-back', function () {
  13101. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  13102. }, {}, editor)]
  13103. };
  13104. var readOnlyGroup = {
  13105. label: 'The read only mode group',
  13106. scrollable: true,
  13107. items: []
  13108. };
  13109. var features = setup(realm, editor);
  13110. var items = detect$4(editor.settings, features);
  13111. var actionGroup = {
  13112. label: 'the action group',
  13113. scrollable: true,
  13114. items: items
  13115. };
  13116. var extraGroup = {
  13117. label: 'The extra group',
  13118. scrollable: false,
  13119. items: []
  13120. };
  13121. var mainGroups = Cell([
  13122. actionGroup,
  13123. extraGroup
  13124. ]);
  13125. var readOnlyGroups = Cell([
  13126. readOnlyGroup,
  13127. extraGroup
  13128. ]);
  13129. var dynamicGroup = Cell({
  13130. backToMask: [backToMaskGroup],
  13131. backToReadOnly: [backToReadOnlyGroup]
  13132. });
  13133. init$5(realm, editor);
  13134. });
  13135. editor.on('remove', function () {
  13136. realm.exit();
  13137. });
  13138. editor.on('detach', function () {
  13139. detachSystem(realm.system());
  13140. realm.system().destroy();
  13141. });
  13142. return {
  13143. iframeContainer: realm.socket().element().dom(),
  13144. editorContainer: realm.element().dom()
  13145. };
  13146. };
  13147. return {
  13148. getNotificationManagerImpl: function () {
  13149. return {
  13150. open: constant({
  13151. progressBar: { value: noop },
  13152. close: noop,
  13153. text: noop,
  13154. getEl: constant(null),
  13155. moveTo: noop,
  13156. moveRel: noop,
  13157. settings: {}
  13158. }),
  13159. close: noop,
  13160. reposition: noop,
  13161. getArgs: constant({})
  13162. };
  13163. },
  13164. renderUI: renderUI
  13165. };
  13166. };
  13167. function Theme () {
  13168. global$2.add('mobile', renderMobileTheme);
  13169. }
  13170. Theme();
  13171. }(window));