theme.js 463 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356
  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.0.7 (2019-06-05)
  8. */
  9. (function () {
  10. var mobile = (function (domGlobals) {
  11. 'use strict';
  12. var extendStatics = function (d, b) {
  13. extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  14. d.__proto__ = b;
  15. } || function (d, b) {
  16. for (var p in b)
  17. if (b.hasOwnProperty(p))
  18. d[p] = b[p];
  19. };
  20. return extendStatics(d, b);
  21. };
  22. function __extends(d, b) {
  23. extendStatics(d, b);
  24. function __() {
  25. this.constructor = d;
  26. }
  27. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  28. }
  29. var __assign = function () {
  30. __assign = Object.assign || function __assign(t) {
  31. for (var s, i = 1, n = arguments.length; i < n; i++) {
  32. s = arguments[i];
  33. for (var p in s)
  34. if (Object.prototype.hasOwnProperty.call(s, p))
  35. t[p] = s[p];
  36. }
  37. return t;
  38. };
  39. return __assign.apply(this, arguments);
  40. };
  41. function __rest(s, e) {
  42. var t = {};
  43. for (var p in s)
  44. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  45. t[p] = s[p];
  46. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  47. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++)
  48. if (e.indexOf(p[i]) < 0)
  49. t[p[i]] = s[p[i]];
  50. return t;
  51. }
  52. function __decorate(decorators, target, key, desc) {
  53. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  54. if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function')
  55. r = Reflect.decorate(decorators, target, key, desc);
  56. else
  57. for (var i = decorators.length - 1; i >= 0; i--)
  58. if (d = decorators[i])
  59. r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  60. return c > 3 && r && Object.defineProperty(target, key, r), r;
  61. }
  62. function __param(paramIndex, decorator) {
  63. return function (target, key) {
  64. decorator(target, key, paramIndex);
  65. };
  66. }
  67. function __metadata(metadataKey, metadataValue) {
  68. if (typeof Reflect === 'object' && typeof Reflect.metadata === 'function')
  69. return Reflect.metadata(metadataKey, metadataValue);
  70. }
  71. function __awaiter(thisArg, _arguments, P, generator) {
  72. return new (P || (P = Promise))(function (resolve, reject) {
  73. function fulfilled(value) {
  74. try {
  75. step(generator.next(value));
  76. } catch (e) {
  77. reject(e);
  78. }
  79. }
  80. function rejected(value) {
  81. try {
  82. step(generator['throw'](value));
  83. } catch (e) {
  84. reject(e);
  85. }
  86. }
  87. function step(result) {
  88. result.done ? resolve(result.value) : new P(function (resolve) {
  89. resolve(result.value);
  90. }).then(fulfilled, rejected);
  91. }
  92. step((generator = generator.apply(thisArg, _arguments || [])).next());
  93. });
  94. }
  95. function __generator(thisArg, body) {
  96. var _ = {
  97. label: 0,
  98. sent: function () {
  99. if (t[0] & 1)
  100. throw t[1];
  101. return t[1];
  102. },
  103. trys: [],
  104. ops: []
  105. }, f, y, t, g;
  106. return g = {
  107. next: verb(0),
  108. 'throw': verb(1),
  109. 'return': verb(2)
  110. }, typeof Symbol === 'function' && (g[Symbol.iterator] = function () {
  111. return this;
  112. }), g;
  113. function verb(n) {
  114. return function (v) {
  115. return step([
  116. n,
  117. v
  118. ]);
  119. };
  120. }
  121. function step(op) {
  122. if (f)
  123. throw new TypeError('Generator is already executing.');
  124. while (_)
  125. try {
  126. if (f = 1, y && (t = op[0] & 2 ? y['return'] : op[0] ? y['throw'] || ((t = y['return']) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
  127. return t;
  128. if (y = 0, t)
  129. op = [
  130. op[0] & 2,
  131. t.value
  132. ];
  133. switch (op[0]) {
  134. case 0:
  135. case 1:
  136. t = op;
  137. break;
  138. case 4:
  139. _.label++;
  140. return {
  141. value: op[1],
  142. done: false
  143. };
  144. case 5:
  145. _.label++;
  146. y = op[1];
  147. op = [0];
  148. continue;
  149. case 7:
  150. op = _.ops.pop();
  151. _.trys.pop();
  152. continue;
  153. default:
  154. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
  155. _ = 0;
  156. continue;
  157. }
  158. if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
  159. _.label = op[1];
  160. break;
  161. }
  162. if (op[0] === 6 && _.label < t[1]) {
  163. _.label = t[1];
  164. t = op;
  165. break;
  166. }
  167. if (t && _.label < t[2]) {
  168. _.label = t[2];
  169. _.ops.push(op);
  170. break;
  171. }
  172. if (t[2])
  173. _.ops.pop();
  174. _.trys.pop();
  175. continue;
  176. }
  177. op = body.call(thisArg, _);
  178. } catch (e) {
  179. op = [
  180. 6,
  181. e
  182. ];
  183. y = 0;
  184. } finally {
  185. f = t = 0;
  186. }
  187. if (op[0] & 5)
  188. throw op[1];
  189. return {
  190. value: op[0] ? op[1] : void 0,
  191. done: true
  192. };
  193. }
  194. }
  195. function __exportStar(m, exports) {
  196. for (var p in m)
  197. if (!exports.hasOwnProperty(p))
  198. exports[p] = m[p];
  199. }
  200. function __values(o) {
  201. var m = typeof Symbol === 'function' && o[Symbol.iterator], i = 0;
  202. if (m)
  203. return m.call(o);
  204. return {
  205. next: function () {
  206. if (o && i >= o.length)
  207. o = void 0;
  208. return {
  209. value: o && o[i++],
  210. done: !o
  211. };
  212. }
  213. };
  214. }
  215. function __read(o, n) {
  216. var m = typeof Symbol === 'function' && o[Symbol.iterator];
  217. if (!m)
  218. return o;
  219. var i = m.call(o), r, ar = [], e;
  220. try {
  221. while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
  222. ar.push(r.value);
  223. } catch (error) {
  224. e = { error: error };
  225. } finally {
  226. try {
  227. if (r && !r.done && (m = i['return']))
  228. m.call(i);
  229. } finally {
  230. if (e)
  231. throw e.error;
  232. }
  233. }
  234. return ar;
  235. }
  236. function __spread() {
  237. for (var ar = [], i = 0; i < arguments.length; i++)
  238. ar = ar.concat(__read(arguments[i]));
  239. return ar;
  240. }
  241. function __await(v) {
  242. return this instanceof __await ? (this.v = v, this) : new __await(v);
  243. }
  244. function __asyncGenerator(thisArg, _arguments, generator) {
  245. if (!Symbol.asyncIterator)
  246. throw new TypeError('Symbol.asyncIterator is not defined.');
  247. var g = generator.apply(thisArg, _arguments || []), i, q = [];
  248. return i = {}, verb('next'), verb('throw'), verb('return'), i[Symbol.asyncIterator] = function () {
  249. return this;
  250. }, i;
  251. function verb(n) {
  252. if (g[n])
  253. i[n] = function (v) {
  254. return new Promise(function (a, b) {
  255. q.push([
  256. n,
  257. v,
  258. a,
  259. b
  260. ]) > 1 || resume(n, v);
  261. });
  262. };
  263. }
  264. function resume(n, v) {
  265. try {
  266. step(g[n](v));
  267. } catch (e) {
  268. settle(q[0][3], e);
  269. }
  270. }
  271. function step(r) {
  272. r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  273. }
  274. function fulfill(value) {
  275. resume('next', value);
  276. }
  277. function reject(value) {
  278. resume('throw', value);
  279. }
  280. function settle(f, v) {
  281. if (f(v), q.shift(), q.length)
  282. resume(q[0][0], q[0][1]);
  283. }
  284. }
  285. function __asyncDelegator(o) {
  286. var i, p;
  287. return i = {}, verb('next'), verb('throw', function (e) {
  288. throw e;
  289. }), verb('return'), i[Symbol.iterator] = function () {
  290. return this;
  291. }, i;
  292. function verb(n, f) {
  293. i[n] = o[n] ? function (v) {
  294. return (p = !p) ? {
  295. value: __await(o[n](v)),
  296. done: n === 'return'
  297. } : f ? f(v) : v;
  298. } : f;
  299. }
  300. }
  301. function __asyncValues(o) {
  302. if (!Symbol.asyncIterator)
  303. throw new TypeError('Symbol.asyncIterator is not defined.');
  304. var m = o[Symbol.asyncIterator], i;
  305. return m ? m.call(o) : (o = typeof __values === 'function' ? __values(o) : o[Symbol.iterator](), i = {}, verb('next'), verb('throw'), verb('return'), i[Symbol.asyncIterator] = function () {
  306. return this;
  307. }, i);
  308. function verb(n) {
  309. i[n] = o[n] && function (v) {
  310. return new Promise(function (resolve, reject) {
  311. v = o[n](v), settle(resolve, reject, v.done, v.value);
  312. });
  313. };
  314. }
  315. function settle(resolve, reject, d, v) {
  316. Promise.resolve(v).then(function (v) {
  317. resolve({
  318. value: v,
  319. done: d
  320. });
  321. }, reject);
  322. }
  323. }
  324. function __makeTemplateObject(cooked, raw) {
  325. if (Object.defineProperty) {
  326. Object.defineProperty(cooked, 'raw', { value: raw });
  327. } else {
  328. cooked.raw = raw;
  329. }
  330. return cooked;
  331. }
  332. function __importStar(mod) {
  333. if (mod && mod.__esModule)
  334. return mod;
  335. var result = {};
  336. if (mod != null)
  337. for (var k in mod)
  338. if (Object.hasOwnProperty.call(mod, k))
  339. result[k] = mod[k];
  340. result.default = mod;
  341. return result;
  342. }
  343. function __importDefault(mod) {
  344. return mod && mod.__esModule ? mod : { default: mod };
  345. }
  346. var tslib_1 = /*#__PURE__*/Object.freeze({
  347. __extends: __extends,
  348. get __assign () { return __assign; },
  349. __rest: __rest,
  350. __decorate: __decorate,
  351. __param: __param,
  352. __metadata: __metadata,
  353. __awaiter: __awaiter,
  354. __generator: __generator,
  355. __exportStar: __exportStar,
  356. __values: __values,
  357. __read: __read,
  358. __spread: __spread,
  359. __await: __await,
  360. __asyncGenerator: __asyncGenerator,
  361. __asyncDelegator: __asyncDelegator,
  362. __asyncValues: __asyncValues,
  363. __makeTemplateObject: __makeTemplateObject,
  364. __importStar: __importStar,
  365. __importDefault: __importDefault
  366. });
  367. var noop = function () {
  368. };
  369. var noarg = function (f) {
  370. return function () {
  371. return f();
  372. };
  373. };
  374. var compose = function (fa, fb) {
  375. return function () {
  376. var args = [];
  377. for (var _i = 0; _i < arguments.length; _i++) {
  378. args[_i] = arguments[_i];
  379. }
  380. return fa(fb.apply(null, args));
  381. };
  382. };
  383. var constant = function (value) {
  384. return function () {
  385. return value;
  386. };
  387. };
  388. var identity = function (x) {
  389. return x;
  390. };
  391. var tripleEquals = function (a, b) {
  392. return a === b;
  393. };
  394. function curry(fn) {
  395. var initialArgs = [];
  396. for (var _i = 1; _i < arguments.length; _i++) {
  397. initialArgs[_i - 1] = arguments[_i];
  398. }
  399. return function () {
  400. var restArgs = [];
  401. for (var _i = 0; _i < arguments.length; _i++) {
  402. restArgs[_i] = arguments[_i];
  403. }
  404. var all = initialArgs.concat(restArgs);
  405. return fn.apply(null, all);
  406. };
  407. }
  408. var not = function (f) {
  409. return function () {
  410. var args = [];
  411. for (var _i = 0; _i < arguments.length; _i++) {
  412. args[_i] = arguments[_i];
  413. }
  414. return !f.apply(null, args);
  415. };
  416. };
  417. var die = function (msg) {
  418. return function () {
  419. throw new Error(msg);
  420. };
  421. };
  422. var apply = function (f) {
  423. return f();
  424. };
  425. var call = function (f) {
  426. f();
  427. };
  428. var never = constant(false);
  429. var always = constant(true);
  430. var Fun = /*#__PURE__*/Object.freeze({
  431. noop: noop,
  432. noarg: noarg,
  433. compose: compose,
  434. constant: constant,
  435. identity: identity,
  436. tripleEquals: tripleEquals,
  437. curry: curry,
  438. not: not,
  439. die: die,
  440. apply: apply,
  441. call: call,
  442. never: never,
  443. always: always
  444. });
  445. var never$1 = never;
  446. var always$1 = always;
  447. var none = function () {
  448. return NONE;
  449. };
  450. var NONE = function () {
  451. var eq = function (o) {
  452. return o.isNone();
  453. };
  454. var call = function (thunk) {
  455. return thunk();
  456. };
  457. var id = function (n) {
  458. return n;
  459. };
  460. var noop = function () {
  461. };
  462. var nul = function () {
  463. return null;
  464. };
  465. var undef = function () {
  466. return undefined;
  467. };
  468. var me = {
  469. fold: function (n, s) {
  470. return n();
  471. },
  472. is: never$1,
  473. isSome: never$1,
  474. isNone: always$1,
  475. getOr: id,
  476. getOrThunk: call,
  477. getOrDie: function (msg) {
  478. throw new Error(msg || 'error: getOrDie called on none.');
  479. },
  480. getOrNull: nul,
  481. getOrUndefined: undef,
  482. or: id,
  483. orThunk: call,
  484. map: none,
  485. ap: none,
  486. each: noop,
  487. bind: none,
  488. flatten: none,
  489. exists: never$1,
  490. forall: always$1,
  491. filter: none,
  492. equals: eq,
  493. equals_: eq,
  494. toArray: function () {
  495. return [];
  496. },
  497. toString: constant('none()')
  498. };
  499. if (Object.freeze)
  500. Object.freeze(me);
  501. return me;
  502. }();
  503. var some = function (a) {
  504. var constant_a = function () {
  505. return a;
  506. };
  507. var self = function () {
  508. return me;
  509. };
  510. var map = function (f) {
  511. return some(f(a));
  512. };
  513. var bind = function (f) {
  514. return f(a);
  515. };
  516. var me = {
  517. fold: function (n, s) {
  518. return s(a);
  519. },
  520. is: function (v) {
  521. return a === v;
  522. },
  523. isSome: always$1,
  524. isNone: never$1,
  525. getOr: constant_a,
  526. getOrThunk: constant_a,
  527. getOrDie: constant_a,
  528. getOrNull: constant_a,
  529. getOrUndefined: constant_a,
  530. or: self,
  531. orThunk: self,
  532. map: map,
  533. ap: function (optfab) {
  534. return optfab.fold(none, function (fab) {
  535. return some(fab(a));
  536. });
  537. },
  538. each: function (f) {
  539. f(a);
  540. },
  541. bind: bind,
  542. flatten: constant_a,
  543. exists: bind,
  544. forall: bind,
  545. filter: function (f) {
  546. return f(a) ? me : NONE;
  547. },
  548. equals: function (o) {
  549. return o.is(a);
  550. },
  551. equals_: function (o, elementEq) {
  552. return o.fold(never$1, function (b) {
  553. return elementEq(a, b);
  554. });
  555. },
  556. toArray: function () {
  557. return [a];
  558. },
  559. toString: function () {
  560. return 'some(' + a + ')';
  561. }
  562. };
  563. return me;
  564. };
  565. var from = function (value) {
  566. return value === null || value === undefined ? NONE : some(value);
  567. };
  568. var Option = {
  569. some: some,
  570. none: none,
  571. from: from
  572. };
  573. var keys = Object.keys;
  574. var hasOwnProperty = Object.hasOwnProperty;
  575. var each = function (obj, f) {
  576. var props = keys(obj);
  577. for (var k = 0, len = props.length; k < len; k++) {
  578. var i = props[k];
  579. var x = obj[i];
  580. f(x, i, obj);
  581. }
  582. };
  583. var map = function (obj, f) {
  584. return tupleMap(obj, function (x, i, obj) {
  585. return {
  586. k: i,
  587. v: f(x, i, obj)
  588. };
  589. });
  590. };
  591. var tupleMap = function (obj, f) {
  592. var r = {};
  593. each(obj, function (x, i) {
  594. var tuple = f(x, i, obj);
  595. r[tuple.k] = tuple.v;
  596. });
  597. return r;
  598. };
  599. var bifilter = function (obj, pred) {
  600. var t = {};
  601. var f = {};
  602. each(obj, function (x, i) {
  603. var branch = pred(x, i) ? t : f;
  604. branch[i] = x;
  605. });
  606. return {
  607. t: t,
  608. f: f
  609. };
  610. };
  611. var mapToArray = function (obj, f) {
  612. var r = [];
  613. each(obj, function (value, name) {
  614. r.push(f(value, name));
  615. });
  616. return r;
  617. };
  618. var find = function (obj, pred) {
  619. var props = keys(obj);
  620. for (var k = 0, len = props.length; k < len; k++) {
  621. var i = props[k];
  622. var x = obj[i];
  623. if (pred(x, i, obj)) {
  624. return Option.some(x);
  625. }
  626. }
  627. return Option.none();
  628. };
  629. var values = function (obj) {
  630. return mapToArray(obj, function (v) {
  631. return v;
  632. });
  633. };
  634. var size = function (obj) {
  635. return keys(obj).length;
  636. };
  637. var get = function (obj, key) {
  638. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  639. };
  640. var has = function (obj, key) {
  641. return hasOwnProperty.call(obj, key);
  642. };
  643. var Obj = /*#__PURE__*/Object.freeze({
  644. keys: keys,
  645. hasOwnProperty: hasOwnProperty,
  646. each: each,
  647. map: map,
  648. tupleMap: tupleMap,
  649. bifilter: bifilter,
  650. mapToArray: mapToArray,
  651. find: find,
  652. values: values,
  653. size: size,
  654. get: get,
  655. has: has
  656. });
  657. var touchstart = constant('touchstart');
  658. var touchmove = constant('touchmove');
  659. var touchend = constant('touchend');
  660. var mousedown = constant('mousedown');
  661. var mousemove = constant('mousemove');
  662. var mouseup = constant('mouseup');
  663. var mouseover = constant('mouseover');
  664. var keydown = constant('keydown');
  665. var keyup = constant('keyup');
  666. var input = constant('input');
  667. var change = constant('change');
  668. var click = constant('click');
  669. var transitionend = constant('transitionend');
  670. var selectstart = constant('selectstart');
  671. var cached = function (f) {
  672. var called = false;
  673. var r;
  674. return function () {
  675. var args = [];
  676. for (var _i = 0; _i < arguments.length; _i++) {
  677. args[_i] = arguments[_i];
  678. }
  679. if (!called) {
  680. called = true;
  681. r = f.apply(null, args);
  682. }
  683. return r;
  684. };
  685. };
  686. var firstMatch = function (regexes, s) {
  687. for (var i = 0; i < regexes.length; i++) {
  688. var x = regexes[i];
  689. if (x.test(s))
  690. return x;
  691. }
  692. return undefined;
  693. };
  694. var find$1 = function (regexes, agent) {
  695. var r = firstMatch(regexes, agent);
  696. if (!r)
  697. return {
  698. major: 0,
  699. minor: 0
  700. };
  701. var group = function (i) {
  702. return Number(agent.replace(r, '$' + i));
  703. };
  704. return nu(group(1), group(2));
  705. };
  706. var detect = function (versionRegexes, agent) {
  707. var cleanedAgent = String(agent).toLowerCase();
  708. if (versionRegexes.length === 0)
  709. return unknown();
  710. return find$1(versionRegexes, cleanedAgent);
  711. };
  712. var unknown = function () {
  713. return nu(0, 0);
  714. };
  715. var nu = function (major, minor) {
  716. return {
  717. major: major,
  718. minor: minor
  719. };
  720. };
  721. var Version = {
  722. nu: nu,
  723. detect: detect,
  724. unknown: unknown
  725. };
  726. var edge = 'Edge';
  727. var chrome = 'Chrome';
  728. var ie = 'IE';
  729. var opera = 'Opera';
  730. var firefox = 'Firefox';
  731. var safari = 'Safari';
  732. var isBrowser = function (name, current) {
  733. return function () {
  734. return current === name;
  735. };
  736. };
  737. var unknown$1 = function () {
  738. return nu$1({
  739. current: undefined,
  740. version: Version.unknown()
  741. });
  742. };
  743. var nu$1 = function (info) {
  744. var current = info.current;
  745. var version = info.version;
  746. return {
  747. current: current,
  748. version: version,
  749. isEdge: isBrowser(edge, current),
  750. isChrome: isBrowser(chrome, current),
  751. isIE: isBrowser(ie, current),
  752. isOpera: isBrowser(opera, current),
  753. isFirefox: isBrowser(firefox, current),
  754. isSafari: isBrowser(safari, current)
  755. };
  756. };
  757. var Browser = {
  758. unknown: unknown$1,
  759. nu: nu$1,
  760. edge: constant(edge),
  761. chrome: constant(chrome),
  762. ie: constant(ie),
  763. opera: constant(opera),
  764. firefox: constant(firefox),
  765. safari: constant(safari)
  766. };
  767. var windows = 'Windows';
  768. var ios = 'iOS';
  769. var android = 'Android';
  770. var linux = 'Linux';
  771. var osx = 'OSX';
  772. var solaris = 'Solaris';
  773. var freebsd = 'FreeBSD';
  774. var isOS = function (name, current) {
  775. return function () {
  776. return current === name;
  777. };
  778. };
  779. var unknown$2 = function () {
  780. return nu$2({
  781. current: undefined,
  782. version: Version.unknown()
  783. });
  784. };
  785. var nu$2 = function (info) {
  786. var current = info.current;
  787. var version = info.version;
  788. return {
  789. current: current,
  790. version: version,
  791. isWindows: isOS(windows, current),
  792. isiOS: isOS(ios, current),
  793. isAndroid: isOS(android, current),
  794. isOSX: isOS(osx, current),
  795. isLinux: isOS(linux, current),
  796. isSolaris: isOS(solaris, current),
  797. isFreeBSD: isOS(freebsd, current)
  798. };
  799. };
  800. var OperatingSystem = {
  801. unknown: unknown$2,
  802. nu: nu$2,
  803. windows: constant(windows),
  804. ios: constant(ios),
  805. android: constant(android),
  806. linux: constant(linux),
  807. osx: constant(osx),
  808. solaris: constant(solaris),
  809. freebsd: constant(freebsd)
  810. };
  811. var DeviceType = function (os, browser, userAgent) {
  812. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  813. var isiPhone = os.isiOS() && !isiPad;
  814. var isAndroid3 = os.isAndroid() && os.version.major === 3;
  815. var isAndroid4 = os.isAndroid() && os.version.major === 4;
  816. var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true;
  817. var isTouch = os.isiOS() || os.isAndroid();
  818. var isPhone = isTouch && !isTablet;
  819. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  820. return {
  821. isiPad: constant(isiPad),
  822. isiPhone: constant(isiPhone),
  823. isTablet: constant(isTablet),
  824. isPhone: constant(isPhone),
  825. isTouch: constant(isTouch),
  826. isAndroid: os.isAndroid,
  827. isiOS: os.isiOS,
  828. isWebView: constant(iOSwebview)
  829. };
  830. };
  831. var typeOf = function (x) {
  832. if (x === null)
  833. return 'null';
  834. var t = typeof x;
  835. if (t === 'object' && Array.prototype.isPrototypeOf(x))
  836. return 'array';
  837. if (t === 'object' && String.prototype.isPrototypeOf(x))
  838. return 'string';
  839. return t;
  840. };
  841. var isType = function (type) {
  842. return function (value) {
  843. return typeOf(value) === type;
  844. };
  845. };
  846. var isString = isType('string');
  847. var isObject = isType('object');
  848. var isArray = isType('array');
  849. var isNull = isType('null');
  850. var isBoolean = isType('boolean');
  851. var isUndefined = isType('undefined');
  852. var isFunction = isType('function');
  853. var isNumber = isType('number');
  854. var Type = /*#__PURE__*/Object.freeze({
  855. isString: isString,
  856. isObject: isObject,
  857. isArray: isArray,
  858. isNull: isNull,
  859. isBoolean: isBoolean,
  860. isUndefined: isUndefined,
  861. isFunction: isFunction,
  862. isNumber: isNumber
  863. });
  864. var slice = Array.prototype.slice;
  865. var rawIndexOf = function () {
  866. var pIndexOf = Array.prototype.indexOf;
  867. var fastIndex = function (xs, x) {
  868. return pIndexOf.call(xs, x);
  869. };
  870. var slowIndex = function (xs, x) {
  871. return slowIndexOf(xs, x);
  872. };
  873. return pIndexOf === undefined ? slowIndex : fastIndex;
  874. }();
  875. var indexOf = function (xs, x) {
  876. var r = rawIndexOf(xs, x);
  877. return r === -1 ? Option.none() : Option.some(r);
  878. };
  879. var contains = function (xs, x) {
  880. return rawIndexOf(xs, x) > -1;
  881. };
  882. var exists = function (xs, pred) {
  883. return findIndex(xs, pred).isSome();
  884. };
  885. var range = function (num, f) {
  886. var r = [];
  887. for (var i = 0; i < num; i++) {
  888. r.push(f(i));
  889. }
  890. return r;
  891. };
  892. var chunk = function (array, size) {
  893. var r = [];
  894. for (var i = 0; i < array.length; i += size) {
  895. var s = slice.call(array, i, i + size);
  896. r.push(s);
  897. }
  898. return r;
  899. };
  900. var map$1 = function (xs, f) {
  901. var len = xs.length;
  902. var r = new Array(len);
  903. for (var i = 0; i < len; i++) {
  904. var x = xs[i];
  905. r[i] = f(x, i, xs);
  906. }
  907. return r;
  908. };
  909. var each$1 = function (xs, f) {
  910. for (var i = 0, len = xs.length; i < len; i++) {
  911. var x = xs[i];
  912. f(x, i, xs);
  913. }
  914. };
  915. var eachr = function (xs, f) {
  916. for (var i = xs.length - 1; i >= 0; i--) {
  917. var x = xs[i];
  918. f(x, i, xs);
  919. }
  920. };
  921. var partition = function (xs, pred) {
  922. var pass = [];
  923. var fail = [];
  924. for (var i = 0, len = xs.length; i < len; i++) {
  925. var x = xs[i];
  926. var arr = pred(x, i, xs) ? pass : fail;
  927. arr.push(x);
  928. }
  929. return {
  930. pass: pass,
  931. fail: fail
  932. };
  933. };
  934. var filter = function (xs, pred) {
  935. var r = [];
  936. for (var i = 0, len = xs.length; i < len; i++) {
  937. var x = xs[i];
  938. if (pred(x, i, xs)) {
  939. r.push(x);
  940. }
  941. }
  942. return r;
  943. };
  944. var groupBy = function (xs, f) {
  945. if (xs.length === 0) {
  946. return [];
  947. } else {
  948. var wasType = f(xs[0]);
  949. var r = [];
  950. var group = [];
  951. for (var i = 0, len = xs.length; i < len; i++) {
  952. var x = xs[i];
  953. var type = f(x);
  954. if (type !== wasType) {
  955. r.push(group);
  956. group = [];
  957. }
  958. wasType = type;
  959. group.push(x);
  960. }
  961. if (group.length !== 0) {
  962. r.push(group);
  963. }
  964. return r;
  965. }
  966. };
  967. var foldr = function (xs, f, acc) {
  968. eachr(xs, function (x) {
  969. acc = f(acc, x);
  970. });
  971. return acc;
  972. };
  973. var foldl = function (xs, f, acc) {
  974. each$1(xs, function (x) {
  975. acc = f(acc, x);
  976. });
  977. return acc;
  978. };
  979. var find$2 = function (xs, pred) {
  980. for (var i = 0, len = xs.length; i < len; i++) {
  981. var x = xs[i];
  982. if (pred(x, i, xs)) {
  983. return Option.some(x);
  984. }
  985. }
  986. return Option.none();
  987. };
  988. var findIndex = function (xs, pred) {
  989. for (var i = 0, len = xs.length; i < len; i++) {
  990. var x = xs[i];
  991. if (pred(x, i, xs)) {
  992. return Option.some(i);
  993. }
  994. }
  995. return Option.none();
  996. };
  997. var slowIndexOf = function (xs, x) {
  998. for (var i = 0, len = xs.length; i < len; ++i) {
  999. if (xs[i] === x) {
  1000. return i;
  1001. }
  1002. }
  1003. return -1;
  1004. };
  1005. var push = Array.prototype.push;
  1006. var flatten = function (xs) {
  1007. var r = [];
  1008. for (var i = 0, len = xs.length; i < len; ++i) {
  1009. if (!Array.prototype.isPrototypeOf(xs[i]))
  1010. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  1011. push.apply(r, xs[i]);
  1012. }
  1013. return r;
  1014. };
  1015. var bind = function (xs, f) {
  1016. var output = map$1(xs, f);
  1017. return flatten(output);
  1018. };
  1019. var forall = function (xs, pred) {
  1020. for (var i = 0, len = xs.length; i < len; ++i) {
  1021. var x = xs[i];
  1022. if (pred(x, i, xs) !== true) {
  1023. return false;
  1024. }
  1025. }
  1026. return true;
  1027. };
  1028. var equal = function (a1, a2) {
  1029. return a1.length === a2.length && forall(a1, function (x, i) {
  1030. return x === a2[i];
  1031. });
  1032. };
  1033. var reverse = function (xs) {
  1034. var r = slice.call(xs, 0);
  1035. r.reverse();
  1036. return r;
  1037. };
  1038. var difference = function (a1, a2) {
  1039. return filter(a1, function (x) {
  1040. return !contains(a2, x);
  1041. });
  1042. };
  1043. var mapToObject = function (xs, f) {
  1044. var r = {};
  1045. for (var i = 0, len = xs.length; i < len; i++) {
  1046. var x = xs[i];
  1047. r[String(x)] = f(x, i);
  1048. }
  1049. return r;
  1050. };
  1051. var pure = function (x) {
  1052. return [x];
  1053. };
  1054. var sort = function (xs, comparator) {
  1055. var copy = slice.call(xs, 0);
  1056. copy.sort(comparator);
  1057. return copy;
  1058. };
  1059. var head = function (xs) {
  1060. return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  1061. };
  1062. var last = function (xs) {
  1063. return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  1064. };
  1065. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  1066. return slice.call(x);
  1067. };
  1068. var Arr = /*#__PURE__*/Object.freeze({
  1069. indexOf: indexOf,
  1070. contains: contains,
  1071. exists: exists,
  1072. range: range,
  1073. chunk: chunk,
  1074. map: map$1,
  1075. each: each$1,
  1076. eachr: eachr,
  1077. partition: partition,
  1078. filter: filter,
  1079. groupBy: groupBy,
  1080. foldr: foldr,
  1081. foldl: foldl,
  1082. find: find$2,
  1083. findIndex: findIndex,
  1084. flatten: flatten,
  1085. bind: bind,
  1086. forall: forall,
  1087. equal: equal,
  1088. reverse: reverse,
  1089. difference: difference,
  1090. mapToObject: mapToObject,
  1091. pure: pure,
  1092. sort: sort,
  1093. head: head,
  1094. last: last,
  1095. from: from$1
  1096. });
  1097. var detect$1 = function (candidates, userAgent) {
  1098. var agent = String(userAgent).toLowerCase();
  1099. return find$2(candidates, function (candidate) {
  1100. return candidate.search(agent);
  1101. });
  1102. };
  1103. var detectBrowser = function (browsers, userAgent) {
  1104. return detect$1(browsers, userAgent).map(function (browser) {
  1105. var version = Version.detect(browser.versionRegexes, userAgent);
  1106. return {
  1107. current: browser.name,
  1108. version: version
  1109. };
  1110. });
  1111. };
  1112. var detectOs = function (oses, userAgent) {
  1113. return detect$1(oses, userAgent).map(function (os) {
  1114. var version = Version.detect(os.versionRegexes, userAgent);
  1115. return {
  1116. current: os.name,
  1117. version: version
  1118. };
  1119. });
  1120. };
  1121. var UaString = {
  1122. detectBrowser: detectBrowser,
  1123. detectOs: detectOs
  1124. };
  1125. var checkRange = function (str, substr, start) {
  1126. if (substr === '')
  1127. return true;
  1128. if (str.length < substr.length)
  1129. return false;
  1130. var x = str.substr(start, start + substr.length);
  1131. return x === substr;
  1132. };
  1133. var supplant = function (str, obj) {
  1134. var isStringOrNumber = function (a) {
  1135. var t = typeof a;
  1136. return t === 'string' || t === 'number';
  1137. };
  1138. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  1139. var value = obj[key];
  1140. return isStringOrNumber(value) ? value.toString() : fullMatch;
  1141. });
  1142. };
  1143. var contains$1 = function (str, substr) {
  1144. return str.indexOf(substr) !== -1;
  1145. };
  1146. var endsWith = function (str, suffix) {
  1147. return checkRange(str, suffix, str.length - suffix.length);
  1148. };
  1149. var trim = function (str) {
  1150. return str.replace(/^\s+|\s+$/g, '');
  1151. };
  1152. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  1153. var checkContains = function (target) {
  1154. return function (uastring) {
  1155. return contains$1(uastring, target);
  1156. };
  1157. };
  1158. var browsers = [
  1159. {
  1160. name: 'Edge',
  1161. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  1162. search: function (uastring) {
  1163. var monstrosity = contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  1164. return monstrosity;
  1165. }
  1166. },
  1167. {
  1168. name: 'Chrome',
  1169. versionRegexes: [
  1170. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  1171. normalVersionRegex
  1172. ],
  1173. search: function (uastring) {
  1174. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  1175. }
  1176. },
  1177. {
  1178. name: 'IE',
  1179. versionRegexes: [
  1180. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  1181. /.*?rv:([0-9]+)\.([0-9]+).*/
  1182. ],
  1183. search: function (uastring) {
  1184. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  1185. }
  1186. },
  1187. {
  1188. name: 'Opera',
  1189. versionRegexes: [
  1190. normalVersionRegex,
  1191. /.*?opera\/([0-9]+)\.([0-9]+).*/
  1192. ],
  1193. search: checkContains('opera')
  1194. },
  1195. {
  1196. name: 'Firefox',
  1197. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1198. search: checkContains('firefox')
  1199. },
  1200. {
  1201. name: 'Safari',
  1202. versionRegexes: [
  1203. normalVersionRegex,
  1204. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1205. ],
  1206. search: function (uastring) {
  1207. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1208. }
  1209. }
  1210. ];
  1211. var oses = [
  1212. {
  1213. name: 'Windows',
  1214. search: checkContains('win'),
  1215. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1216. },
  1217. {
  1218. name: 'iOS',
  1219. search: function (uastring) {
  1220. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1221. },
  1222. versionRegexes: [
  1223. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1224. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1225. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1226. ]
  1227. },
  1228. {
  1229. name: 'Android',
  1230. search: checkContains('android'),
  1231. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1232. },
  1233. {
  1234. name: 'OSX',
  1235. search: checkContains('os x'),
  1236. versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
  1237. },
  1238. {
  1239. name: 'Linux',
  1240. search: checkContains('linux'),
  1241. versionRegexes: []
  1242. },
  1243. {
  1244. name: 'Solaris',
  1245. search: checkContains('sunos'),
  1246. versionRegexes: []
  1247. },
  1248. {
  1249. name: 'FreeBSD',
  1250. search: checkContains('freebsd'),
  1251. versionRegexes: []
  1252. }
  1253. ];
  1254. var PlatformInfo = {
  1255. browsers: constant(browsers),
  1256. oses: constant(oses)
  1257. };
  1258. var detect$2 = function (userAgent) {
  1259. var browsers = PlatformInfo.browsers();
  1260. var oses = PlatformInfo.oses();
  1261. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  1262. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1263. var deviceType = DeviceType(os, browser, userAgent);
  1264. return {
  1265. browser: browser,
  1266. os: os,
  1267. deviceType: deviceType
  1268. };
  1269. };
  1270. var PlatformDetection = { detect: detect$2 };
  1271. var detect$3 = cached(function () {
  1272. var userAgent = domGlobals.navigator.userAgent;
  1273. return PlatformDetection.detect(userAgent);
  1274. });
  1275. var PlatformDetection$1 = { detect: detect$3 };
  1276. var alloy = { tap: constant('alloy.tap') };
  1277. var focus = constant('alloy.focus');
  1278. var postBlur = constant('alloy.blur.post');
  1279. var postPaste = constant('alloy.paste.post');
  1280. var receive = constant('alloy.receive');
  1281. var execute = constant('alloy.execute');
  1282. var focusItem = constant('alloy.focus.item');
  1283. var tap = alloy.tap;
  1284. var tapOrClick = PlatformDetection$1.detect().deviceType.isTouch() ? alloy.tap : click;
  1285. var longpress = constant('alloy.longpress');
  1286. var systemInit = constant('alloy.system.init');
  1287. var attachedToDom = constant('alloy.system.attached');
  1288. var detachedFromDom = constant('alloy.system.detached');
  1289. var focusShifted = constant('alloy.focusmanager.shifted');
  1290. var highlight = constant('alloy.highlight');
  1291. var dehighlight = constant('alloy.dehighlight');
  1292. var emit = function (component, event) {
  1293. dispatchWith(component, component.element(), event, {});
  1294. };
  1295. var emitWith = function (component, event, properties) {
  1296. dispatchWith(component, component.element(), event, properties);
  1297. };
  1298. var emitExecute = function (component) {
  1299. emit(component, execute());
  1300. };
  1301. var dispatch = function (component, target, event) {
  1302. dispatchWith(component, target, event, {});
  1303. };
  1304. var dispatchWith = function (component, target, event, properties) {
  1305. var data = __assign({ target: target }, properties);
  1306. component.getSystem().triggerEvent(event, target, map(data, constant));
  1307. };
  1308. var dispatchEvent = function (component, target, event, simulatedEvent) {
  1309. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  1310. };
  1311. var dispatchFocus = function (component, target) {
  1312. component.getSystem().triggerFocus(target, component.element());
  1313. };
  1314. var fromHtml = function (html, scope) {
  1315. var doc = scope || domGlobals.document;
  1316. var div = doc.createElement('div');
  1317. div.innerHTML = html;
  1318. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1319. domGlobals.console.error('HTML does not have a single root node', html);
  1320. throw new Error('HTML must have a single root node');
  1321. }
  1322. return fromDom(div.childNodes[0]);
  1323. };
  1324. var fromTag = function (tag, scope) {
  1325. var doc = scope || domGlobals.document;
  1326. var node = doc.createElement(tag);
  1327. return fromDom(node);
  1328. };
  1329. var fromText = function (text, scope) {
  1330. var doc = scope || domGlobals.document;
  1331. var node = doc.createTextNode(text);
  1332. return fromDom(node);
  1333. };
  1334. var fromDom = function (node) {
  1335. if (node === null || node === undefined) {
  1336. throw new Error('Node cannot be null or undefined');
  1337. }
  1338. return { dom: constant(node) };
  1339. };
  1340. var fromPoint = function (docElm, x, y) {
  1341. var doc = docElm.dom();
  1342. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  1343. };
  1344. var Element = {
  1345. fromHtml: fromHtml,
  1346. fromTag: fromTag,
  1347. fromText: fromText,
  1348. fromDom: fromDom,
  1349. fromPoint: fromPoint
  1350. };
  1351. var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE;
  1352. var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE;
  1353. var COMMENT = domGlobals.Node.COMMENT_NODE;
  1354. var DOCUMENT = domGlobals.Node.DOCUMENT_NODE;
  1355. var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE;
  1356. var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE;
  1357. var ELEMENT = domGlobals.Node.ELEMENT_NODE;
  1358. var TEXT = domGlobals.Node.TEXT_NODE;
  1359. var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE;
  1360. var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE;
  1361. var ENTITY = domGlobals.Node.ENTITY_NODE;
  1362. var NOTATION = domGlobals.Node.NOTATION_NODE;
  1363. var name = function (element) {
  1364. var r = element.dom().nodeName;
  1365. return r.toLowerCase();
  1366. };
  1367. var type = function (element) {
  1368. return element.dom().nodeType;
  1369. };
  1370. var value = function (element) {
  1371. return element.dom().nodeValue;
  1372. };
  1373. var isType$1 = function (t) {
  1374. return function (element) {
  1375. return type(element) === t;
  1376. };
  1377. };
  1378. var isComment = function (element) {
  1379. return type(element) === COMMENT || name(element) === '#comment';
  1380. };
  1381. var isElement = isType$1(ELEMENT);
  1382. var isText = isType$1(TEXT);
  1383. var isDocument = isType$1(DOCUMENT);
  1384. var Node = /*#__PURE__*/Object.freeze({
  1385. name: name,
  1386. type: type,
  1387. value: value,
  1388. isElement: isElement,
  1389. isText: isText,
  1390. isDocument: isDocument,
  1391. isComment: isComment
  1392. });
  1393. var inBody = function (element) {
  1394. var dom = isText(element) ? element.dom().parentNode : element.dom();
  1395. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  1396. };
  1397. var body = cached(function () {
  1398. return getBody(Element.fromDom(domGlobals.document));
  1399. });
  1400. var getBody = function (doc) {
  1401. var b = doc.dom().body;
  1402. if (b === null || b === undefined) {
  1403. throw new Error('Body is not available yet');
  1404. }
  1405. return Element.fromDom(b);
  1406. };
  1407. var Immutable = function () {
  1408. var fields = [];
  1409. for (var _i = 0; _i < arguments.length; _i++) {
  1410. fields[_i] = arguments[_i];
  1411. }
  1412. return function () {
  1413. var values = [];
  1414. for (var _i = 0; _i < arguments.length; _i++) {
  1415. values[_i] = arguments[_i];
  1416. }
  1417. if (fields.length !== values.length) {
  1418. throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
  1419. }
  1420. var struct = {};
  1421. each$1(fields, function (name, i) {
  1422. struct[name] = constant(values[i]);
  1423. });
  1424. return struct;
  1425. };
  1426. };
  1427. var sort$1 = function (arr) {
  1428. return arr.slice(0).sort();
  1429. };
  1430. var reqMessage = function (required, keys) {
  1431. throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
  1432. };
  1433. var unsuppMessage = function (unsupported) {
  1434. throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
  1435. };
  1436. var validateStrArr = function (label, array) {
  1437. if (!isArray(array))
  1438. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  1439. each$1(array, function (a) {
  1440. if (!isString(a))
  1441. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  1442. });
  1443. };
  1444. var checkDupes = function (everything) {
  1445. var sorted = sort$1(everything);
  1446. var dupe = find$2(sorted, function (s, i) {
  1447. return i < sorted.length - 1 && s === sorted[i + 1];
  1448. });
  1449. dupe.each(function (d) {
  1450. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  1451. });
  1452. };
  1453. var MixedBag = function (required, optional) {
  1454. var everything = required.concat(optional);
  1455. if (everything.length === 0)
  1456. throw new Error('You must specify at least one required or optional field.');
  1457. validateStrArr('required', required);
  1458. validateStrArr('optional', optional);
  1459. checkDupes(everything);
  1460. return function (obj) {
  1461. var keys$1 = keys(obj);
  1462. var allReqd = forall(required, function (req) {
  1463. return contains(keys$1, req);
  1464. });
  1465. if (!allReqd)
  1466. reqMessage(required, keys$1);
  1467. var unsupported = filter(keys$1, function (key) {
  1468. return !contains(everything, key);
  1469. });
  1470. if (unsupported.length > 0)
  1471. unsuppMessage(unsupported);
  1472. var r = {};
  1473. each$1(required, function (req) {
  1474. r[req] = constant(obj[req]);
  1475. });
  1476. each$1(optional, function (opt) {
  1477. r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
  1478. });
  1479. return r;
  1480. };
  1481. };
  1482. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  1483. var path = function (parts, scope) {
  1484. var o = scope !== undefined && scope !== null ? scope : Global;
  1485. for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i)
  1486. o = o[parts[i]];
  1487. return o;
  1488. };
  1489. var resolve = function (p, scope) {
  1490. var parts = p.split('.');
  1491. return path(parts, scope);
  1492. };
  1493. var unsafe = function (name, scope) {
  1494. return resolve(name, scope);
  1495. };
  1496. var getOrDie = function (name, scope) {
  1497. var actual = unsafe(name, scope);
  1498. if (actual === undefined || actual === null)
  1499. throw name + ' not available on this browser';
  1500. return actual;
  1501. };
  1502. var Global$1 = { getOrDie: getOrDie };
  1503. var node = function () {
  1504. var f = Global$1.getOrDie('Node');
  1505. return f;
  1506. };
  1507. var compareDocumentPosition = function (a, b, match) {
  1508. return (a.compareDocumentPosition(b) & match) !== 0;
  1509. };
  1510. var documentPositionPreceding = function (a, b) {
  1511. return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING);
  1512. };
  1513. var documentPositionContainedBy = function (a, b) {
  1514. return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY);
  1515. };
  1516. var Node$1 = {
  1517. documentPositionPreceding: documentPositionPreceding,
  1518. documentPositionContainedBy: documentPositionContainedBy
  1519. };
  1520. var ELEMENT$1 = ELEMENT;
  1521. var DOCUMENT$1 = DOCUMENT;
  1522. var is = function (element, selector) {
  1523. var elem = element.dom();
  1524. if (elem.nodeType !== ELEMENT$1) {
  1525. return false;
  1526. } else if (elem.matches !== undefined) {
  1527. return elem.matches(selector);
  1528. } else if (elem.msMatchesSelector !== undefined) {
  1529. return elem.msMatchesSelector(selector);
  1530. } else if (elem.webkitMatchesSelector !== undefined) {
  1531. return elem.webkitMatchesSelector(selector);
  1532. } else if (elem.mozMatchesSelector !== undefined) {
  1533. return elem.mozMatchesSelector(selector);
  1534. } else {
  1535. throw new Error('Browser lacks native selectors');
  1536. }
  1537. };
  1538. var bypassSelector = function (dom) {
  1539. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  1540. };
  1541. var all = function (selector, scope) {
  1542. var base = scope === undefined ? domGlobals.document : scope.dom();
  1543. return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), Element.fromDom);
  1544. };
  1545. var one = function (selector, scope) {
  1546. var base = scope === undefined ? domGlobals.document : scope.dom();
  1547. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1548. };
  1549. var eq = function (e1, e2) {
  1550. return e1.dom() === e2.dom();
  1551. };
  1552. var regularContains = function (e1, e2) {
  1553. var d1 = e1.dom();
  1554. var d2 = e2.dom();
  1555. return d1 === d2 ? false : d1.contains(d2);
  1556. };
  1557. var ieContains = function (e1, e2) {
  1558. return Node$1.documentPositionContainedBy(e1.dom(), e2.dom());
  1559. };
  1560. var browser = PlatformDetection$1.detect().browser;
  1561. var contains$2 = browser.isIE() ? ieContains : regularContains;
  1562. var owner = function (element) {
  1563. return Element.fromDom(element.dom().ownerDocument);
  1564. };
  1565. var parent = function (element) {
  1566. var dom = element.dom();
  1567. return Option.from(dom.parentNode).map(Element.fromDom);
  1568. };
  1569. var parents = function (element, isRoot) {
  1570. var stop = isFunction(isRoot) ? isRoot : constant(false);
  1571. var dom = element.dom();
  1572. var ret = [];
  1573. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1574. var rawParent = dom.parentNode;
  1575. var p = Element.fromDom(rawParent);
  1576. ret.push(p);
  1577. if (stop(p) === true) {
  1578. break;
  1579. } else {
  1580. dom = rawParent;
  1581. }
  1582. }
  1583. return ret;
  1584. };
  1585. var siblings = function (element) {
  1586. var filterSelf = function (elements) {
  1587. return filter(elements, function (x) {
  1588. return !eq(element, x);
  1589. });
  1590. };
  1591. return parent(element).map(children).map(filterSelf).getOr([]);
  1592. };
  1593. var nextSibling = function (element) {
  1594. var dom = element.dom();
  1595. return Option.from(dom.nextSibling).map(Element.fromDom);
  1596. };
  1597. var children = function (element) {
  1598. var dom = element.dom();
  1599. return map$1(dom.childNodes, Element.fromDom);
  1600. };
  1601. var child = function (element, index) {
  1602. var cs = element.dom().childNodes;
  1603. return Option.from(cs[index]).map(Element.fromDom);
  1604. };
  1605. var firstChild = function (element) {
  1606. return child(element, 0);
  1607. };
  1608. var spot = Immutable('element', 'offset');
  1609. var before = function (marker, element) {
  1610. var parent$1 = parent(marker);
  1611. parent$1.each(function (v) {
  1612. v.dom().insertBefore(element.dom(), marker.dom());
  1613. });
  1614. };
  1615. var after = function (marker, element) {
  1616. var sibling = nextSibling(marker);
  1617. sibling.fold(function () {
  1618. var parent$1 = parent(marker);
  1619. parent$1.each(function (v) {
  1620. append(v, element);
  1621. });
  1622. }, function (v) {
  1623. before(v, element);
  1624. });
  1625. };
  1626. var prepend = function (parent, element) {
  1627. var firstChild$1 = firstChild(parent);
  1628. firstChild$1.fold(function () {
  1629. append(parent, element);
  1630. }, function (v) {
  1631. parent.dom().insertBefore(element.dom(), v.dom());
  1632. });
  1633. };
  1634. var append = function (parent, element) {
  1635. parent.dom().appendChild(element.dom());
  1636. };
  1637. var appendAt = function (parent, element, index) {
  1638. child(parent, index).fold(function () {
  1639. append(parent, element);
  1640. }, function (v) {
  1641. before(v, element);
  1642. });
  1643. };
  1644. var append$1 = function (parent, elements) {
  1645. each$1(elements, function (x) {
  1646. append(parent, x);
  1647. });
  1648. };
  1649. var empty = function (element) {
  1650. element.dom().textContent = '';
  1651. each$1(children(element), function (rogue) {
  1652. remove(rogue);
  1653. });
  1654. };
  1655. var remove = function (element) {
  1656. var dom = element.dom();
  1657. if (dom.parentNode !== null) {
  1658. dom.parentNode.removeChild(dom);
  1659. }
  1660. };
  1661. var fireDetaching = function (component) {
  1662. emit(component, detachedFromDom());
  1663. var children = component.components();
  1664. each$1(children, fireDetaching);
  1665. };
  1666. var fireAttaching = function (component) {
  1667. var children = component.components();
  1668. each$1(children, fireAttaching);
  1669. emit(component, attachedToDom());
  1670. };
  1671. var attach = function (parent, child) {
  1672. attachWith(parent, child, append);
  1673. };
  1674. var attachWith = function (parent, child, insertion) {
  1675. parent.getSystem().addToWorld(child);
  1676. insertion(parent.element(), child.element());
  1677. if (inBody(parent.element())) {
  1678. fireAttaching(child);
  1679. }
  1680. parent.syncComponents();
  1681. };
  1682. var doDetach = function (component) {
  1683. fireDetaching(component);
  1684. remove(component.element());
  1685. component.getSystem().removeFromWorld(component);
  1686. };
  1687. var detach = function (component) {
  1688. var parent$1 = parent(component.element()).bind(function (p) {
  1689. return component.getSystem().getByDom(p).fold(Option.none, Option.some);
  1690. });
  1691. doDetach(component);
  1692. parent$1.each(function (p) {
  1693. p.syncComponents();
  1694. });
  1695. };
  1696. var detachChildren = function (component) {
  1697. var subs = component.components();
  1698. each$1(subs, doDetach);
  1699. empty(component.element());
  1700. component.syncComponents();
  1701. };
  1702. var attachSystemAfter = function (element, guiSystem) {
  1703. attachSystemInternal(element, guiSystem, after);
  1704. };
  1705. var attachSystemInternal = function (element, guiSystem, inserter) {
  1706. inserter(element, guiSystem.element());
  1707. var children$1 = children(guiSystem.element());
  1708. each$1(children$1, function (child) {
  1709. guiSystem.getByDom(child).each(fireAttaching);
  1710. });
  1711. };
  1712. var detachSystem = function (guiSystem) {
  1713. var children$1 = children(guiSystem.element());
  1714. each$1(children$1, function (child) {
  1715. guiSystem.getByDom(child).each(fireDetaching);
  1716. });
  1717. remove(guiSystem.element());
  1718. };
  1719. var value$1 = function (o) {
  1720. var is = function (v) {
  1721. return o === v;
  1722. };
  1723. var or = function (opt) {
  1724. return value$1(o);
  1725. };
  1726. var orThunk = function (f) {
  1727. return value$1(o);
  1728. };
  1729. var map = function (f) {
  1730. return value$1(f(o));
  1731. };
  1732. var mapError = function (f) {
  1733. return value$1(o);
  1734. };
  1735. var each = function (f) {
  1736. f(o);
  1737. };
  1738. var bind = function (f) {
  1739. return f(o);
  1740. };
  1741. var fold = function (_, onValue) {
  1742. return onValue(o);
  1743. };
  1744. var exists = function (f) {
  1745. return f(o);
  1746. };
  1747. var forall = function (f) {
  1748. return f(o);
  1749. };
  1750. var toOption = function () {
  1751. return Option.some(o);
  1752. };
  1753. return {
  1754. is: is,
  1755. isValue: always,
  1756. isError: never,
  1757. getOr: constant(o),
  1758. getOrThunk: constant(o),
  1759. getOrDie: constant(o),
  1760. or: or,
  1761. orThunk: orThunk,
  1762. fold: fold,
  1763. map: map,
  1764. mapError: mapError,
  1765. each: each,
  1766. bind: bind,
  1767. exists: exists,
  1768. forall: forall,
  1769. toOption: toOption
  1770. };
  1771. };
  1772. var error = function (message) {
  1773. var getOrThunk = function (f) {
  1774. return f();
  1775. };
  1776. var getOrDie = function () {
  1777. return die(String(message))();
  1778. };
  1779. var or = function (opt) {
  1780. return opt;
  1781. };
  1782. var orThunk = function (f) {
  1783. return f();
  1784. };
  1785. var map = function (f) {
  1786. return error(message);
  1787. };
  1788. var mapError = function (f) {
  1789. return error(f(message));
  1790. };
  1791. var bind = function (f) {
  1792. return error(message);
  1793. };
  1794. var fold = function (onError, _) {
  1795. return onError(message);
  1796. };
  1797. return {
  1798. is: never,
  1799. isValue: never,
  1800. isError: always,
  1801. getOr: identity,
  1802. getOrThunk: getOrThunk,
  1803. getOrDie: getOrDie,
  1804. or: or,
  1805. orThunk: orThunk,
  1806. fold: fold,
  1807. map: map,
  1808. mapError: mapError,
  1809. each: noop,
  1810. bind: bind,
  1811. exists: never,
  1812. forall: always,
  1813. toOption: Option.none
  1814. };
  1815. };
  1816. var fromOption = function (opt, err) {
  1817. return opt.fold(function () {
  1818. return error(err);
  1819. }, value$1);
  1820. };
  1821. var Result = {
  1822. value: value$1,
  1823. error: error,
  1824. fromOption: fromOption
  1825. };
  1826. var generate = function (cases) {
  1827. if (!isArray(cases)) {
  1828. throw new Error('cases must be an array');
  1829. }
  1830. if (cases.length === 0) {
  1831. throw new Error('there must be at least one case');
  1832. }
  1833. var constructors = [];
  1834. var adt = {};
  1835. each$1(cases, function (acase, count) {
  1836. var keys$1 = keys(acase);
  1837. if (keys$1.length !== 1) {
  1838. throw new Error('one and only one name per case');
  1839. }
  1840. var key = keys$1[0];
  1841. var value = acase[key];
  1842. if (adt[key] !== undefined) {
  1843. throw new Error('duplicate key detected:' + key);
  1844. } else if (key === 'cata') {
  1845. throw new Error('cannot have a case named cata (sorry)');
  1846. } else if (!isArray(value)) {
  1847. throw new Error('case arguments must be an array');
  1848. }
  1849. constructors.push(key);
  1850. adt[key] = function () {
  1851. var argLength = arguments.length;
  1852. if (argLength !== value.length) {
  1853. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1854. }
  1855. var args = new Array(argLength);
  1856. for (var i = 0; i < args.length; i++)
  1857. args[i] = arguments[i];
  1858. var match = function (branches) {
  1859. var branchKeys = keys(branches);
  1860. if (constructors.length !== branchKeys.length) {
  1861. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1862. }
  1863. var allReqd = forall(constructors, function (reqKey) {
  1864. return contains(branchKeys, reqKey);
  1865. });
  1866. if (!allReqd)
  1867. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1868. return branches[key].apply(null, args);
  1869. };
  1870. return {
  1871. fold: function () {
  1872. if (arguments.length !== cases.length) {
  1873. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  1874. }
  1875. var target = arguments[count];
  1876. return target.apply(null, args);
  1877. },
  1878. match: match,
  1879. log: function (label) {
  1880. domGlobals.console.log(label, {
  1881. constructors: constructors,
  1882. constructor: key,
  1883. params: args
  1884. });
  1885. }
  1886. };
  1887. };
  1888. });
  1889. return adt;
  1890. };
  1891. var Adt = { generate: generate };
  1892. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  1893. var shallow = function (old, nu) {
  1894. return nu;
  1895. };
  1896. var deep = function (old, nu) {
  1897. var bothObjects = isObject(old) && isObject(nu);
  1898. return bothObjects ? deepMerge(old, nu) : nu;
  1899. };
  1900. var baseMerge = function (merger) {
  1901. return function () {
  1902. var objects = new Array(arguments.length);
  1903. for (var i = 0; i < objects.length; i++)
  1904. objects[i] = arguments[i];
  1905. if (objects.length === 0)
  1906. throw new Error('Can\'t merge zero objects');
  1907. var ret = {};
  1908. for (var j = 0; j < objects.length; j++) {
  1909. var curObject = objects[j];
  1910. for (var key in curObject)
  1911. if (hasOwnProperty$1.call(curObject, key)) {
  1912. ret[key] = merger(ret[key], curObject[key]);
  1913. }
  1914. }
  1915. return ret;
  1916. };
  1917. };
  1918. var deepMerge = baseMerge(deep);
  1919. var merge = baseMerge(shallow);
  1920. var adt = Adt.generate([
  1921. { strict: [] },
  1922. { defaultedThunk: ['fallbackThunk'] },
  1923. { asOption: [] },
  1924. { asDefaultedOptionThunk: ['fallbackThunk'] },
  1925. { mergeWithThunk: ['baseThunk'] }
  1926. ]);
  1927. var defaulted = function (fallback) {
  1928. return adt.defaultedThunk(constant(fallback));
  1929. };
  1930. var mergeWith = function (base) {
  1931. return adt.mergeWithThunk(constant(base));
  1932. };
  1933. var strict = adt.strict;
  1934. var asOption = adt.asOption;
  1935. var defaultedThunk = adt.defaultedThunk;
  1936. var mergeWithThunk = adt.mergeWithThunk;
  1937. var exclude = function (obj, fields) {
  1938. var r = {};
  1939. each(obj, function (v, k) {
  1940. if (!contains(fields, k)) {
  1941. r[k] = v;
  1942. }
  1943. });
  1944. return r;
  1945. };
  1946. var readOpt = function (key) {
  1947. return function (obj) {
  1948. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  1949. };
  1950. };
  1951. var readOr = function (key, fallback) {
  1952. return function (obj) {
  1953. return has(obj, key) ? obj[key] : fallback;
  1954. };
  1955. };
  1956. var readOptFrom = function (obj, key) {
  1957. return readOpt(key)(obj);
  1958. };
  1959. var hasKey = function (obj, key) {
  1960. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  1961. };
  1962. var wrap = function (key, value) {
  1963. var r = {};
  1964. r[key] = value;
  1965. return r;
  1966. };
  1967. var wrapAll = function (keyvalues) {
  1968. var r = {};
  1969. each$1(keyvalues, function (kv) {
  1970. r[kv.key] = kv.value;
  1971. });
  1972. return r;
  1973. };
  1974. var comparison = Adt.generate([
  1975. {
  1976. bothErrors: [
  1977. 'error1',
  1978. 'error2'
  1979. ]
  1980. },
  1981. {
  1982. firstError: [
  1983. 'error1',
  1984. 'value2'
  1985. ]
  1986. },
  1987. {
  1988. secondError: [
  1989. 'value1',
  1990. 'error2'
  1991. ]
  1992. },
  1993. {
  1994. bothValues: [
  1995. 'value1',
  1996. 'value2'
  1997. ]
  1998. }
  1999. ]);
  2000. var partition$1 = function (results) {
  2001. var errors = [];
  2002. var values = [];
  2003. each$1(results, function (result) {
  2004. result.fold(function (err) {
  2005. errors.push(err);
  2006. }, function (value) {
  2007. values.push(value);
  2008. });
  2009. });
  2010. return {
  2011. errors: errors,
  2012. values: values
  2013. };
  2014. };
  2015. var exclude$1 = function (obj, fields) {
  2016. return exclude(obj, fields);
  2017. };
  2018. var readOpt$1 = function (key) {
  2019. return readOpt(key);
  2020. };
  2021. var readOr$1 = function (key, fallback) {
  2022. return readOr(key, fallback);
  2023. };
  2024. var readOptFrom$1 = function (obj, key) {
  2025. return readOptFrom(obj, key);
  2026. };
  2027. var wrap$1 = function (key, value) {
  2028. return wrap(key, value);
  2029. };
  2030. var wrapAll$1 = function (keyvalues) {
  2031. return wrapAll(keyvalues);
  2032. };
  2033. var mergeValues = function (values, base) {
  2034. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  2035. };
  2036. var mergeErrors = function (errors) {
  2037. return compose(Result.error, flatten)(errors);
  2038. };
  2039. var consolidate = function (objs, base) {
  2040. var partitions = partition$1(objs);
  2041. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2042. };
  2043. var hasKey$1 = function (obj, key) {
  2044. return hasKey(obj, key);
  2045. };
  2046. var SimpleResultType;
  2047. (function (SimpleResultType) {
  2048. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  2049. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  2050. }(SimpleResultType || (SimpleResultType = {})));
  2051. var fold = function (res, onError, onValue) {
  2052. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  2053. };
  2054. var partition$2 = function (results) {
  2055. var values = [];
  2056. var errors = [];
  2057. each$1(results, function (obj) {
  2058. fold(obj, function (err) {
  2059. return errors.push(err);
  2060. }, function (val) {
  2061. return values.push(val);
  2062. });
  2063. });
  2064. return {
  2065. values: values,
  2066. errors: errors
  2067. };
  2068. };
  2069. var mapError = function (res, f) {
  2070. if (res.stype === SimpleResultType.Error) {
  2071. return {
  2072. stype: SimpleResultType.Error,
  2073. serror: f(res.serror)
  2074. };
  2075. } else {
  2076. return res;
  2077. }
  2078. };
  2079. var map$2 = function (res, f) {
  2080. if (res.stype === SimpleResultType.Value) {
  2081. return {
  2082. stype: SimpleResultType.Value,
  2083. svalue: f(res.svalue)
  2084. };
  2085. } else {
  2086. return res;
  2087. }
  2088. };
  2089. var bind$1 = function (res, f) {
  2090. if (res.stype === SimpleResultType.Value) {
  2091. return f(res.svalue);
  2092. } else {
  2093. return res;
  2094. }
  2095. };
  2096. var bindError = function (res, f) {
  2097. if (res.stype === SimpleResultType.Error) {
  2098. return f(res.serror);
  2099. } else {
  2100. return res;
  2101. }
  2102. };
  2103. var svalue = function (v) {
  2104. return {
  2105. stype: SimpleResultType.Value,
  2106. svalue: v
  2107. };
  2108. };
  2109. var serror = function (e) {
  2110. return {
  2111. stype: SimpleResultType.Error,
  2112. serror: e
  2113. };
  2114. };
  2115. var toResult = function (res) {
  2116. return fold(res, Result.error, Result.value);
  2117. };
  2118. var fromResult = function (res) {
  2119. return res.fold(serror, svalue);
  2120. };
  2121. var SimpleResult = {
  2122. fromResult: fromResult,
  2123. toResult: toResult,
  2124. svalue: svalue,
  2125. partition: partition$2,
  2126. serror: serror,
  2127. bind: bind$1,
  2128. bindError: bindError,
  2129. map: map$2,
  2130. mapError: mapError,
  2131. fold: fold
  2132. };
  2133. var mergeValues$1 = function (values, base) {
  2134. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  2135. };
  2136. var mergeErrors$1 = function (errors) {
  2137. return compose(SimpleResult.serror, flatten)(errors);
  2138. };
  2139. var consolidateObj = function (objects, base) {
  2140. var partition = SimpleResult.partition(objects);
  2141. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  2142. };
  2143. var consolidateArr = function (objects) {
  2144. var partitions = SimpleResult.partition(objects);
  2145. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  2146. };
  2147. var ResultCombine = {
  2148. consolidateObj: consolidateObj,
  2149. consolidateArr: consolidateArr
  2150. };
  2151. var typeAdt = Adt.generate([
  2152. {
  2153. setOf: [
  2154. 'validator',
  2155. 'valueType'
  2156. ]
  2157. },
  2158. { arrOf: ['valueType'] },
  2159. { objOf: ['fields'] },
  2160. { itemOf: ['validator'] },
  2161. {
  2162. choiceOf: [
  2163. 'key',
  2164. 'branches'
  2165. ]
  2166. },
  2167. { thunk: ['description'] },
  2168. {
  2169. func: [
  2170. 'args',
  2171. 'outputSchema'
  2172. ]
  2173. }
  2174. ]);
  2175. var fieldAdt = Adt.generate([
  2176. {
  2177. field: [
  2178. 'name',
  2179. 'presence',
  2180. 'type'
  2181. ]
  2182. },
  2183. { state: ['name'] }
  2184. ]);
  2185. var json = function () {
  2186. return Global$1.getOrDie('JSON');
  2187. };
  2188. var parse = function (text) {
  2189. return json().parse(text);
  2190. };
  2191. var stringify = function (obj, replacer, space) {
  2192. return json().stringify(obj, replacer, space);
  2193. };
  2194. var Json = {
  2195. parse: parse,
  2196. stringify: stringify
  2197. };
  2198. var formatObj = function (input) {
  2199. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : Json.stringify(input, null, 2);
  2200. };
  2201. var formatErrors = function (errors) {
  2202. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  2203. path: [],
  2204. getErrorInfo: function () {
  2205. return '... (only showing first ten failures)';
  2206. }
  2207. }]) : errors;
  2208. return map$1(es, function (e) {
  2209. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  2210. });
  2211. };
  2212. var nu$3 = function (path, getErrorInfo) {
  2213. return SimpleResult.serror([{
  2214. path: path,
  2215. getErrorInfo: getErrorInfo
  2216. }]);
  2217. };
  2218. var missingStrict = function (path, key, obj) {
  2219. return nu$3(path, function () {
  2220. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  2221. });
  2222. };
  2223. var missingKey = function (path, key) {
  2224. return nu$3(path, function () {
  2225. return 'Choice schema did not contain choice key: "' + key + '"';
  2226. });
  2227. };
  2228. var missingBranch = function (path, branches, branch) {
  2229. return nu$3(path, function () {
  2230. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  2231. });
  2232. };
  2233. var unsupportedFields = function (path, unsupported) {
  2234. return nu$3(path, function () {
  2235. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  2236. });
  2237. };
  2238. var custom = function (path, err) {
  2239. return nu$3(path, function () {
  2240. return err;
  2241. });
  2242. };
  2243. var adt$1 = Adt.generate([
  2244. {
  2245. field: [
  2246. 'key',
  2247. 'okey',
  2248. 'presence',
  2249. 'prop'
  2250. ]
  2251. },
  2252. {
  2253. state: [
  2254. 'okey',
  2255. 'instantiator'
  2256. ]
  2257. }
  2258. ]);
  2259. var strictAccess = function (path, obj, key) {
  2260. return readOptFrom(obj, key).fold(function () {
  2261. return missingStrict(path, key, obj);
  2262. }, SimpleResult.svalue);
  2263. };
  2264. var fallbackAccess = function (obj, key, fallbackThunk) {
  2265. var v = readOptFrom(obj, key).fold(function () {
  2266. return fallbackThunk(obj);
  2267. }, identity);
  2268. return SimpleResult.svalue(v);
  2269. };
  2270. var optionAccess = function (obj, key) {
  2271. return SimpleResult.svalue(readOptFrom(obj, key));
  2272. };
  2273. var optionDefaultedAccess = function (obj, key, fallback) {
  2274. var opt = readOptFrom(obj, key).map(function (val) {
  2275. return val === true ? fallback(obj) : val;
  2276. });
  2277. return SimpleResult.svalue(opt);
  2278. };
  2279. var cExtractOne = function (path, obj, field, strength) {
  2280. return field.fold(function (key, okey, presence, prop) {
  2281. var bundle = function (av) {
  2282. var result = prop.extract(path.concat([key]), strength, av);
  2283. return SimpleResult.map(result, function (res) {
  2284. return wrap(okey, strength(res));
  2285. });
  2286. };
  2287. var bundleAsOption = function (optValue) {
  2288. return optValue.fold(function () {
  2289. var outcome = wrap(okey, strength(Option.none()));
  2290. return SimpleResult.svalue(outcome);
  2291. }, function (ov) {
  2292. var result = prop.extract(path.concat([key]), strength, ov);
  2293. return SimpleResult.map(result, function (res) {
  2294. return wrap(okey, strength(Option.some(res)));
  2295. });
  2296. });
  2297. };
  2298. return function () {
  2299. return presence.fold(function () {
  2300. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  2301. }, function (fallbackThunk) {
  2302. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  2303. }, function () {
  2304. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  2305. }, function (fallbackThunk) {
  2306. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  2307. }, function (baseThunk) {
  2308. var base = baseThunk(obj);
  2309. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  2310. return deepMerge(base, v);
  2311. });
  2312. return SimpleResult.bind(result, bundle);
  2313. });
  2314. }();
  2315. }, function (okey, instantiator) {
  2316. var state = instantiator(obj);
  2317. return SimpleResult.svalue(wrap(okey, strength(state)));
  2318. });
  2319. };
  2320. var cExtract = function (path, obj, fields, strength) {
  2321. var results = map$1(fields, function (field) {
  2322. return cExtractOne(path, obj, field, strength);
  2323. });
  2324. return ResultCombine.consolidateObj(results, {});
  2325. };
  2326. var value$2 = function (validator) {
  2327. var extract = function (path, strength, val) {
  2328. return SimpleResult.bindError(validator(val, strength), function (err) {
  2329. return custom(path, err);
  2330. });
  2331. };
  2332. var toString = function () {
  2333. return 'val';
  2334. };
  2335. var toDsl = function () {
  2336. return typeAdt.itemOf(validator);
  2337. };
  2338. return {
  2339. extract: extract,
  2340. toString: toString,
  2341. toDsl: toDsl
  2342. };
  2343. };
  2344. var getSetKeys = function (obj) {
  2345. var keys$1 = keys(obj);
  2346. return filter(keys$1, function (k) {
  2347. return hasKey$1(obj, k);
  2348. });
  2349. };
  2350. var objOfOnly = function (fields) {
  2351. var delegate = objOf(fields);
  2352. var fieldNames = foldr(fields, function (acc, f) {
  2353. return f.fold(function (key) {
  2354. return deepMerge(acc, wrap$1(key, true));
  2355. }, constant(acc));
  2356. }, {});
  2357. var extract = function (path, strength, o) {
  2358. var keys = isBoolean(o) ? [] : getSetKeys(o);
  2359. var extra = filter(keys, function (k) {
  2360. return !hasKey$1(fieldNames, k);
  2361. });
  2362. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  2363. };
  2364. return {
  2365. extract: extract,
  2366. toString: delegate.toString,
  2367. toDsl: delegate.toDsl
  2368. };
  2369. };
  2370. var objOf = function (fields) {
  2371. var extract = function (path, strength, o) {
  2372. return cExtract(path, o, fields, strength);
  2373. };
  2374. var toString = function () {
  2375. var fieldStrings = map$1(fields, function (field) {
  2376. return field.fold(function (key, okey, presence, prop) {
  2377. return key + ' -> ' + prop.toString();
  2378. }, function (okey, instantiator) {
  2379. return 'state(' + okey + ')';
  2380. });
  2381. });
  2382. return 'obj{\n' + fieldStrings.join('\n') + '}';
  2383. };
  2384. var toDsl = function () {
  2385. return typeAdt.objOf(map$1(fields, function (f) {
  2386. return f.fold(function (key, okey, presence, prop) {
  2387. return fieldAdt.field(key, presence, prop);
  2388. }, function (okey, instantiator) {
  2389. return fieldAdt.state(okey);
  2390. });
  2391. }));
  2392. };
  2393. return {
  2394. extract: extract,
  2395. toString: toString,
  2396. toDsl: toDsl
  2397. };
  2398. };
  2399. var arrOf = function (prop) {
  2400. var extract = function (path, strength, array) {
  2401. var results = map$1(array, function (a, i) {
  2402. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  2403. });
  2404. return ResultCombine.consolidateArr(results);
  2405. };
  2406. var toString = function () {
  2407. return 'array(' + prop.toString() + ')';
  2408. };
  2409. var toDsl = function () {
  2410. return typeAdt.arrOf(prop);
  2411. };
  2412. return {
  2413. extract: extract,
  2414. toString: toString,
  2415. toDsl: toDsl
  2416. };
  2417. };
  2418. var setOf = function (validator, prop) {
  2419. var validateKeys = function (path, keys) {
  2420. return arrOf(value$2(validator)).extract(path, identity, keys);
  2421. };
  2422. var extract = function (path, strength, o) {
  2423. var keys$1 = keys(o);
  2424. var validatedKeys = validateKeys(path, keys$1);
  2425. return SimpleResult.bind(validatedKeys, function (validKeys) {
  2426. var schema = map$1(validKeys, function (vk) {
  2427. return adt$1.field(vk, vk, strict(), prop);
  2428. });
  2429. return objOf(schema).extract(path, strength, o);
  2430. });
  2431. };
  2432. var toString = function () {
  2433. return 'setOf(' + prop.toString() + ')';
  2434. };
  2435. var toDsl = function () {
  2436. return typeAdt.setOf(validator, prop);
  2437. };
  2438. return {
  2439. extract: extract,
  2440. toString: toString,
  2441. toDsl: toDsl
  2442. };
  2443. };
  2444. var anyValue = constant(value$2(SimpleResult.svalue));
  2445. var state = adt$1.state;
  2446. var field = adt$1.field;
  2447. var chooseFrom = function (path, strength, input, branches, ch) {
  2448. var fields = readOptFrom$1(branches, ch);
  2449. return fields.fold(function () {
  2450. return missingBranch(path, branches, ch);
  2451. }, function (fs) {
  2452. return objOf(fs).extract(path.concat(['branch: ' + ch]), strength, input);
  2453. });
  2454. };
  2455. var choose = function (key, branches) {
  2456. var extract = function (path, strength, input) {
  2457. var choice = readOptFrom$1(input, key);
  2458. return choice.fold(function () {
  2459. return missingKey(path, key);
  2460. }, function (chosen) {
  2461. return chooseFrom(path, strength, input, branches, chosen);
  2462. });
  2463. };
  2464. var toString = function () {
  2465. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  2466. };
  2467. var toDsl = function () {
  2468. return typeAdt.choiceOf(key, branches);
  2469. };
  2470. return {
  2471. extract: extract,
  2472. toString: toString,
  2473. toDsl: toDsl
  2474. };
  2475. };
  2476. var _anyValue = value$2(SimpleResult.svalue);
  2477. var valueOf = function (validator) {
  2478. return value$2(function (v) {
  2479. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  2480. });
  2481. };
  2482. var setOf$1 = function (validator, prop) {
  2483. return setOf(function (v) {
  2484. return SimpleResult.fromResult(validator(v));
  2485. }, prop);
  2486. };
  2487. var extract = function (label, prop, strength, obj) {
  2488. var res = prop.extract([label], strength, obj);
  2489. return SimpleResult.mapError(res, function (errs) {
  2490. return {
  2491. input: obj,
  2492. errors: errs
  2493. };
  2494. });
  2495. };
  2496. var asRaw = function (label, prop, obj) {
  2497. return SimpleResult.toResult(extract(label, prop, identity, obj));
  2498. };
  2499. var getOrDie$1 = function (extraction) {
  2500. return extraction.fold(function (errInfo) {
  2501. throw new Error(formatError(errInfo));
  2502. }, identity);
  2503. };
  2504. var asRawOrDie = function (label, prop, obj) {
  2505. return getOrDie$1(asRaw(label, prop, obj));
  2506. };
  2507. var formatError = function (errInfo) {
  2508. return 'Errors: \n' + formatErrors(errInfo.errors) + '\n\nInput object: ' + formatObj(errInfo.input);
  2509. };
  2510. var choose$1 = function (key, branches) {
  2511. return choose(key, branches);
  2512. };
  2513. var anyValue$1 = constant(_anyValue);
  2514. var typedValue = function (validator, expectedType) {
  2515. return value$2(function (a) {
  2516. var actualType = typeof a;
  2517. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  2518. });
  2519. };
  2520. var functionProcessor = typedValue(isFunction, 'function');
  2521. var strict$1 = function (key) {
  2522. return field(key, key, strict(), anyValue());
  2523. };
  2524. var strictOf = function (key, schema) {
  2525. return field(key, key, strict(), schema);
  2526. };
  2527. var strictFunction = function (key) {
  2528. return strictOf(key, functionProcessor);
  2529. };
  2530. var forbid = function (key, message) {
  2531. return field(key, key, asOption(), value$2(function (v) {
  2532. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  2533. }));
  2534. };
  2535. var strictObjOf = function (key, objSchema) {
  2536. return field(key, key, strict(), objOf(objSchema));
  2537. };
  2538. var option = function (key) {
  2539. return field(key, key, asOption(), anyValue());
  2540. };
  2541. var optionOf = function (key, schema) {
  2542. return field(key, key, asOption(), schema);
  2543. };
  2544. var optionObjOf = function (key, objSchema) {
  2545. return optionOf(key, objOf(objSchema));
  2546. };
  2547. var optionObjOfOnly = function (key, objSchema) {
  2548. return optionOf(key, objOfOnly(objSchema));
  2549. };
  2550. var defaulted$1 = function (key, fallback) {
  2551. return field(key, key, defaulted(fallback), anyValue());
  2552. };
  2553. var defaultedOf = function (key, fallback, schema) {
  2554. return field(key, key, defaulted(fallback), schema);
  2555. };
  2556. var defaultedObjOf = function (key, fallback, objSchema) {
  2557. return defaultedOf(key, fallback, objOf(objSchema));
  2558. };
  2559. var state$1 = function (okey, instantiator) {
  2560. return state(okey, instantiator);
  2561. };
  2562. var isSource = function (component, simulatedEvent) {
  2563. return eq(component.element(), simulatedEvent.event().target());
  2564. };
  2565. var nu$4 = function (parts) {
  2566. if (!hasKey$1(parts, 'can') && !hasKey$1(parts, 'abort') && !hasKey$1(parts, 'run')) {
  2567. throw new Error('EventHandler defined by: ' + Json.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2568. }
  2569. return asRawOrDie('Extracting event.handler', objOfOnly([
  2570. defaulted$1('can', constant(true)),
  2571. defaulted$1('abort', constant(false)),
  2572. defaulted$1('run', noop)
  2573. ]), parts);
  2574. };
  2575. var all$1 = function (handlers, f) {
  2576. return function () {
  2577. var args = [];
  2578. for (var _i = 0; _i < arguments.length; _i++) {
  2579. args[_i] = arguments[_i];
  2580. }
  2581. return foldl(handlers, function (acc, handler) {
  2582. return acc && f(handler).apply(undefined, args);
  2583. }, true);
  2584. };
  2585. };
  2586. var any = function (handlers, f) {
  2587. return function () {
  2588. var args = [];
  2589. for (var _i = 0; _i < arguments.length; _i++) {
  2590. args[_i] = arguments[_i];
  2591. }
  2592. return foldl(handlers, function (acc, handler) {
  2593. return acc || f(handler).apply(undefined, args);
  2594. }, false);
  2595. };
  2596. };
  2597. var read = function (handler) {
  2598. return isFunction(handler) ? {
  2599. can: constant(true),
  2600. abort: constant(false),
  2601. run: handler
  2602. } : handler;
  2603. };
  2604. var fuse = function (handlers) {
  2605. var can = all$1(handlers, function (handler) {
  2606. return handler.can;
  2607. });
  2608. var abort = any(handlers, function (handler) {
  2609. return handler.abort;
  2610. });
  2611. var run = function () {
  2612. var args = [];
  2613. for (var _i = 0; _i < arguments.length; _i++) {
  2614. args[_i] = arguments[_i];
  2615. }
  2616. each$1(handlers, function (handler) {
  2617. handler.run.apply(undefined, args);
  2618. });
  2619. };
  2620. return nu$4({
  2621. can: can,
  2622. abort: abort,
  2623. run: run
  2624. });
  2625. };
  2626. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2627. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  2628. }
  2629. var ancestor = function (scope, predicate, isRoot) {
  2630. var element = scope.dom();
  2631. var stop = isFunction(isRoot) ? isRoot : constant(false);
  2632. while (element.parentNode) {
  2633. element = element.parentNode;
  2634. var el = Element.fromDom(element);
  2635. if (predicate(el)) {
  2636. return Option.some(el);
  2637. } else if (stop(el)) {
  2638. break;
  2639. }
  2640. }
  2641. return Option.none();
  2642. };
  2643. var closest = function (scope, predicate, isRoot) {
  2644. var is = function (s) {
  2645. return predicate(s);
  2646. };
  2647. return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  2648. };
  2649. var sibling = function (scope, predicate) {
  2650. var element = scope.dom();
  2651. if (!element.parentNode) {
  2652. return Option.none();
  2653. }
  2654. return child$1(Element.fromDom(element.parentNode), function (x) {
  2655. return !eq(scope, x) && predicate(x);
  2656. });
  2657. };
  2658. var child$1 = function (scope, predicate) {
  2659. var result = find$2(scope.dom().childNodes, compose(predicate, Element.fromDom));
  2660. return result.map(Element.fromDom);
  2661. };
  2662. var descendant = function (scope, predicate) {
  2663. var descend = function (node) {
  2664. for (var i = 0; i < node.childNodes.length; i++) {
  2665. if (predicate(Element.fromDom(node.childNodes[i]))) {
  2666. return Option.some(Element.fromDom(node.childNodes[i]));
  2667. }
  2668. var res = descend(node.childNodes[i]);
  2669. if (res.isSome()) {
  2670. return res;
  2671. }
  2672. }
  2673. return Option.none();
  2674. };
  2675. return descend(scope.dom());
  2676. };
  2677. var closest$1 = function (target, transform, isRoot) {
  2678. var delegate = closest(target, function (elem) {
  2679. return transform(elem).isSome();
  2680. }, isRoot);
  2681. return delegate.bind(transform);
  2682. };
  2683. var derive = function (configs) {
  2684. return wrapAll$1(configs);
  2685. };
  2686. var abort = function (name, predicate) {
  2687. return {
  2688. key: name,
  2689. value: nu$4({ abort: predicate })
  2690. };
  2691. };
  2692. var can = function (name, predicate) {
  2693. return {
  2694. key: name,
  2695. value: nu$4({ can: predicate })
  2696. };
  2697. };
  2698. var preventDefault = function (name) {
  2699. return {
  2700. key: name,
  2701. value: nu$4({
  2702. run: function (component, simulatedEvent) {
  2703. simulatedEvent.event().prevent();
  2704. }
  2705. })
  2706. };
  2707. };
  2708. var run = function (name, handler) {
  2709. return {
  2710. key: name,
  2711. value: nu$4({ run: handler })
  2712. };
  2713. };
  2714. var runActionExtra = function (name, action, extra) {
  2715. return {
  2716. key: name,
  2717. value: nu$4({
  2718. run: function (component) {
  2719. action.apply(undefined, [component].concat(extra));
  2720. }
  2721. })
  2722. };
  2723. };
  2724. var runOnName = function (name) {
  2725. return function (handler) {
  2726. return run(name, handler);
  2727. };
  2728. };
  2729. var runOnSourceName = function (name) {
  2730. return function (handler) {
  2731. return {
  2732. key: name,
  2733. value: nu$4({
  2734. run: function (component, simulatedEvent) {
  2735. if (isSource(component, simulatedEvent)) {
  2736. handler(component, simulatedEvent);
  2737. }
  2738. }
  2739. })
  2740. };
  2741. };
  2742. };
  2743. var redirectToUid = function (name, uid) {
  2744. return run(name, function (component, simulatedEvent) {
  2745. component.getSystem().getByUid(uid).each(function (redirectee) {
  2746. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2747. });
  2748. });
  2749. };
  2750. var redirectToPart = function (name, detail, partName) {
  2751. var uid = detail.partUids[partName];
  2752. return redirectToUid(name, uid);
  2753. };
  2754. var runWithTarget = function (name, f) {
  2755. return run(name, function (component, simulatedEvent) {
  2756. var ev = simulatedEvent.event();
  2757. var target = component.getSystem().getByDom(ev.target()).fold(function () {
  2758. var closest = closest$1(ev.target(), function (el) {
  2759. return component.getSystem().getByDom(el).toOption();
  2760. }, constant(false));
  2761. return closest.getOr(component);
  2762. }, function (c) {
  2763. return c;
  2764. });
  2765. f(component, target, simulatedEvent);
  2766. });
  2767. };
  2768. var cutter = function (name) {
  2769. return run(name, function (component, simulatedEvent) {
  2770. simulatedEvent.cut();
  2771. });
  2772. };
  2773. var stopper = function (name) {
  2774. return run(name, function (component, simulatedEvent) {
  2775. simulatedEvent.stop();
  2776. });
  2777. };
  2778. var runOnSource = function (name, f) {
  2779. return runOnSourceName(name)(f);
  2780. };
  2781. var runOnAttached = runOnSourceName(attachedToDom());
  2782. var runOnDetached = runOnSourceName(detachedFromDom());
  2783. var runOnInit = runOnSourceName(systemInit());
  2784. var runOnExecute = runOnName(execute());
  2785. var AlloyEvents = /*#__PURE__*/Object.freeze({
  2786. derive: derive,
  2787. run: run,
  2788. preventDefault: preventDefault,
  2789. runActionExtra: runActionExtra,
  2790. runOnAttached: runOnAttached,
  2791. runOnDetached: runOnDetached,
  2792. runOnSource: runOnSource,
  2793. runOnInit: runOnInit,
  2794. runOnExecute: runOnExecute,
  2795. redirectToUid: redirectToUid,
  2796. redirectToPart: redirectToPart,
  2797. runWithTarget: runWithTarget,
  2798. abort: abort,
  2799. can: can,
  2800. cutter: cutter,
  2801. stopper: stopper
  2802. });
  2803. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2804. var delegate = apiFunction.toString();
  2805. var endIndex = delegate.indexOf(')') + 1;
  2806. var openBracketIndex = delegate.indexOf('(');
  2807. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2808. f.toFunctionAnnotation = function () {
  2809. return {
  2810. name: apiName,
  2811. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2812. };
  2813. };
  2814. return f;
  2815. };
  2816. var cleanParameters = function (parameters) {
  2817. return map$1(parameters, function (p) {
  2818. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2819. });
  2820. };
  2821. var markAsExtraApi = function (f, extraName) {
  2822. var delegate = f.toString();
  2823. var endIndex = delegate.indexOf(')') + 1;
  2824. var openBracketIndex = delegate.indexOf('(');
  2825. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2826. f.toFunctionAnnotation = function () {
  2827. return {
  2828. name: extraName,
  2829. parameters: cleanParameters(parameters)
  2830. };
  2831. };
  2832. return f;
  2833. };
  2834. var markAsSketchApi = function (f, apiFunction) {
  2835. var delegate = apiFunction.toString();
  2836. var endIndex = delegate.indexOf(')') + 1;
  2837. var openBracketIndex = delegate.indexOf('(');
  2838. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2839. f.toFunctionAnnotation = function () {
  2840. return {
  2841. name: 'OVERRIDE',
  2842. parameters: cleanParameters(parameters.slice(1))
  2843. };
  2844. };
  2845. return f;
  2846. };
  2847. var nu$5 = function (s) {
  2848. return {
  2849. classes: s.classes !== undefined ? s.classes : [],
  2850. attributes: s.attributes !== undefined ? s.attributes : {},
  2851. styles: s.styles !== undefined ? s.styles : {}
  2852. };
  2853. };
  2854. var merge$1 = function (defnA, mod) {
  2855. return __assign({}, defnA, {
  2856. attributes: __assign({}, defnA.attributes, mod.attributes),
  2857. styles: __assign({}, defnA.styles, mod.styles),
  2858. classes: defnA.classes.concat(mod.classes)
  2859. });
  2860. };
  2861. var executeEvent = function (bConfig, bState, executor) {
  2862. return runOnExecute(function (component) {
  2863. executor(component, bConfig, bState);
  2864. });
  2865. };
  2866. var loadEvent = function (bConfig, bState, f) {
  2867. return runOnInit(function (component, simulatedEvent) {
  2868. f(component, bConfig, bState);
  2869. });
  2870. };
  2871. var create = function (schema, name, active, apis, extra, state) {
  2872. var configSchema = objOfOnly(schema);
  2873. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2874. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2875. };
  2876. var createModes = function (modes, name, active, apis, extra, state) {
  2877. var configSchema = modes;
  2878. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2879. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2880. };
  2881. var wrapApi = function (bName, apiFunction, apiName) {
  2882. var f = function (component) {
  2883. var rest = [];
  2884. for (var _i = 1; _i < arguments.length; _i++) {
  2885. rest[_i - 1] = arguments[_i];
  2886. }
  2887. var args = [component].concat(rest);
  2888. return component.config({ name: constant(bName) }).fold(function () {
  2889. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2890. }, function (info) {
  2891. var rest = Array.prototype.slice.call(args, 1);
  2892. return apiFunction.apply(undefined, [
  2893. component,
  2894. info.config,
  2895. info.state
  2896. ].concat(rest));
  2897. });
  2898. };
  2899. return markAsBehaviourApi(f, apiName, apiFunction);
  2900. };
  2901. var revokeBehaviour = function (name) {
  2902. return {
  2903. key: name,
  2904. value: undefined
  2905. };
  2906. };
  2907. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2908. var getConfig = function (info) {
  2909. return hasKey$1(info, name) ? info[name]() : Option.none();
  2910. };
  2911. var wrappedApis = map(apis, function (apiF, apiName) {
  2912. return wrapApi(name, apiF, apiName);
  2913. });
  2914. var wrappedExtra = map(extra, function (extraF, extraName) {
  2915. return markAsExtraApi(extraF, extraName);
  2916. });
  2917. var me = __assign({}, wrappedExtra, wrappedApis, {
  2918. revoke: curry(revokeBehaviour, name),
  2919. config: function (spec) {
  2920. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  2921. return {
  2922. key: name,
  2923. value: {
  2924. config: prepared,
  2925. me: me,
  2926. configAsRaw: cached(function () {
  2927. return asRawOrDie(name + '-config', configSchema, spec);
  2928. }),
  2929. initialConfig: spec,
  2930. state: state
  2931. }
  2932. };
  2933. },
  2934. schema: function () {
  2935. return schemaSchema;
  2936. },
  2937. exhibit: function (info, base) {
  2938. return getConfig(info).bind(function (behaviourInfo) {
  2939. return readOptFrom$1(active, 'exhibit').map(function (exhibitor) {
  2940. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2941. });
  2942. }).getOr(nu$5({}));
  2943. },
  2944. name: function () {
  2945. return name;
  2946. },
  2947. handlers: function (info) {
  2948. return getConfig(info).map(function (behaviourInfo) {
  2949. var getEvents = readOr$1('events', function (a, b) {
  2950. return {};
  2951. })(active);
  2952. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2953. }).getOr({});
  2954. }
  2955. });
  2956. return me;
  2957. };
  2958. var NoState = {
  2959. init: function () {
  2960. return nu$6({
  2961. readState: function () {
  2962. return 'No State required';
  2963. }
  2964. });
  2965. }
  2966. };
  2967. var nu$6 = function (spec) {
  2968. return spec;
  2969. };
  2970. var derive$1 = function (capabilities) {
  2971. return wrapAll$1(capabilities);
  2972. };
  2973. var simpleSchema = objOfOnly([
  2974. strict$1('fields'),
  2975. strict$1('name'),
  2976. defaulted$1('active', {}),
  2977. defaulted$1('apis', {}),
  2978. defaulted$1('state', NoState),
  2979. defaulted$1('extra', {})
  2980. ]);
  2981. var create$1 = function (data) {
  2982. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  2983. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2984. };
  2985. var modeSchema = objOfOnly([
  2986. strict$1('branchKey'),
  2987. strict$1('branches'),
  2988. strict$1('name'),
  2989. defaulted$1('active', {}),
  2990. defaulted$1('apis', {}),
  2991. defaulted$1('state', NoState),
  2992. defaulted$1('extra', {})
  2993. ]);
  2994. var createModes$1 = function (data) {
  2995. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  2996. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2997. };
  2998. var revoke = constant(undefined);
  2999. var noActive = constant({});
  3000. var noApis = constant({});
  3001. var noExtra = constant({});
  3002. var Behaviour = /*#__PURE__*/Object.freeze({
  3003. derive: derive$1,
  3004. revoke: revoke,
  3005. noActive: noActive,
  3006. noApis: noApis,
  3007. noExtra: noExtra,
  3008. create: create$1,
  3009. createModes: createModes$1
  3010. });
  3011. function Toggler (turnOff, turnOn, initial) {
  3012. var active = initial || false;
  3013. var on = function () {
  3014. turnOn();
  3015. active = true;
  3016. };
  3017. var off = function () {
  3018. turnOff();
  3019. active = false;
  3020. };
  3021. var toggle = function () {
  3022. var f = active ? off : on;
  3023. f();
  3024. };
  3025. var isOn = function () {
  3026. return active;
  3027. };
  3028. return {
  3029. on: on,
  3030. off: off,
  3031. toggle: toggle,
  3032. isOn: isOn
  3033. };
  3034. }
  3035. var rawSet = function (dom, key, value) {
  3036. if (isString(value) || isBoolean(value) || isNumber(value)) {
  3037. dom.setAttribute(key, value + '');
  3038. } else {
  3039. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  3040. throw new Error('Attribute value was not simple');
  3041. }
  3042. };
  3043. var set = function (element, key, value) {
  3044. rawSet(element.dom(), key, value);
  3045. };
  3046. var setAll = function (element, attrs) {
  3047. var dom = element.dom();
  3048. each(attrs, function (v, k) {
  3049. rawSet(dom, k, v);
  3050. });
  3051. };
  3052. var get$1 = function (element, key) {
  3053. var v = element.dom().getAttribute(key);
  3054. return v === null ? undefined : v;
  3055. };
  3056. var getOpt = function (element, key) {
  3057. return Option.from(get$1(element, key));
  3058. };
  3059. var has$1 = function (element, key) {
  3060. var dom = element.dom();
  3061. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  3062. };
  3063. var remove$1 = function (element, key) {
  3064. element.dom().removeAttribute(key);
  3065. };
  3066. var hasNone = function (element) {
  3067. var attrs = element.dom().attributes;
  3068. return attrs === undefined || attrs === null || attrs.length === 0;
  3069. };
  3070. var clone = function (element) {
  3071. return foldl(element.dom().attributes, function (acc, attr) {
  3072. acc[attr.name] = attr.value;
  3073. return acc;
  3074. }, {});
  3075. };
  3076. var transferOne = function (source, destination, attr) {
  3077. if (has$1(source, attr) && !has$1(destination, attr)) {
  3078. set(destination, attr, get$1(source, attr));
  3079. }
  3080. };
  3081. var transfer = function (source, destination, attrs) {
  3082. if (!isElement(source) || !isElement(destination)) {
  3083. return;
  3084. }
  3085. each$1(attrs, function (attr) {
  3086. transferOne(source, destination, attr);
  3087. });
  3088. };
  3089. var Attr = /*#__PURE__*/Object.freeze({
  3090. clone: clone,
  3091. set: set,
  3092. setAll: setAll,
  3093. get: get$1,
  3094. getOpt: getOpt,
  3095. has: has$1,
  3096. remove: remove$1,
  3097. hasNone: hasNone,
  3098. transfer: transfer
  3099. });
  3100. var read$1 = function (element, attr) {
  3101. var value = get$1(element, attr);
  3102. return value === undefined || value === '' ? [] : value.split(' ');
  3103. };
  3104. var add = function (element, attr, id) {
  3105. var old = read$1(element, attr);
  3106. var nu = old.concat([id]);
  3107. set(element, attr, nu.join(' '));
  3108. return true;
  3109. };
  3110. var remove$2 = function (element, attr, id) {
  3111. var nu = filter(read$1(element, attr), function (v) {
  3112. return v !== id;
  3113. });
  3114. if (nu.length > 0) {
  3115. set(element, attr, nu.join(' '));
  3116. } else {
  3117. remove$1(element, attr);
  3118. }
  3119. return false;
  3120. };
  3121. var supports = function (element) {
  3122. return element.dom().classList !== undefined;
  3123. };
  3124. var get$2 = function (element) {
  3125. return read$1(element, 'class');
  3126. };
  3127. var add$1 = function (element, clazz) {
  3128. return add(element, 'class', clazz);
  3129. };
  3130. var remove$3 = function (element, clazz) {
  3131. return remove$2(element, 'class', clazz);
  3132. };
  3133. var toggle = function (element, clazz) {
  3134. if (contains(get$2(element), clazz)) {
  3135. return remove$3(element, clazz);
  3136. } else {
  3137. return add$1(element, clazz);
  3138. }
  3139. };
  3140. var ClassList = /*#__PURE__*/Object.freeze({
  3141. get: get$2,
  3142. add: add$1,
  3143. remove: remove$3,
  3144. toggle: toggle,
  3145. supports: supports
  3146. });
  3147. var add$2 = function (element, clazz) {
  3148. if (supports(element)) {
  3149. element.dom().classList.add(clazz);
  3150. } else {
  3151. add$1(element, clazz);
  3152. }
  3153. };
  3154. var cleanClass = function (element) {
  3155. var classList = supports(element) ? element.dom().classList : get$2(element);
  3156. if (classList.length === 0) {
  3157. remove$1(element, 'class');
  3158. }
  3159. };
  3160. var remove$4 = function (element, clazz) {
  3161. if (supports(element)) {
  3162. var classList = element.dom().classList;
  3163. classList.remove(clazz);
  3164. } else {
  3165. remove$3(element, clazz);
  3166. }
  3167. cleanClass(element);
  3168. };
  3169. var toggle$1 = function (element, clazz) {
  3170. return supports(element) ? element.dom().classList.toggle(clazz) : toggle(element, clazz);
  3171. };
  3172. var toggler = function (element, clazz) {
  3173. var hasClasslist = supports(element);
  3174. var classList = element.dom().classList;
  3175. var off = function () {
  3176. if (hasClasslist) {
  3177. classList.remove(clazz);
  3178. } else {
  3179. remove$3(element, clazz);
  3180. }
  3181. };
  3182. var on = function () {
  3183. if (hasClasslist) {
  3184. classList.add(clazz);
  3185. } else {
  3186. add$1(element, clazz);
  3187. }
  3188. };
  3189. return Toggler(off, on, has$2(element, clazz));
  3190. };
  3191. var has$2 = function (element, clazz) {
  3192. return supports(element) && element.dom().classList.contains(clazz);
  3193. };
  3194. var Class = /*#__PURE__*/Object.freeze({
  3195. add: add$2,
  3196. remove: remove$4,
  3197. toggle: toggle$1,
  3198. toggler: toggler,
  3199. has: has$2
  3200. });
  3201. var swap = function (element, addCls, removeCls) {
  3202. remove$4(element, removeCls);
  3203. add$2(element, addCls);
  3204. };
  3205. var toAlpha = function (component, swapConfig, swapState) {
  3206. swap(component.element(), swapConfig.alpha, swapConfig.omega);
  3207. };
  3208. var toOmega = function (component, swapConfig, swapState) {
  3209. swap(component.element(), swapConfig.omega, swapConfig.alpha);
  3210. };
  3211. var clear = function (component, swapConfig, swapState) {
  3212. remove$4(component.element(), swapConfig.alpha);
  3213. remove$4(component.element(), swapConfig.omega);
  3214. };
  3215. var isAlpha = function (component, swapConfig, swapState) {
  3216. return has$2(component.element(), swapConfig.alpha);
  3217. };
  3218. var isOmega = function (component, swapConfig, swapState) {
  3219. return has$2(component.element(), swapConfig.omega);
  3220. };
  3221. var SwapApis = /*#__PURE__*/Object.freeze({
  3222. toAlpha: toAlpha,
  3223. toOmega: toOmega,
  3224. isAlpha: isAlpha,
  3225. isOmega: isOmega,
  3226. clear: clear
  3227. });
  3228. var SwapSchema = [
  3229. strict$1('alpha'),
  3230. strict$1('omega')
  3231. ];
  3232. var Swapping = create$1({
  3233. fields: SwapSchema,
  3234. name: 'swapping',
  3235. apis: SwapApis
  3236. });
  3237. var Cell = function (initial) {
  3238. var value = initial;
  3239. var get = function () {
  3240. return value;
  3241. };
  3242. var set = function (v) {
  3243. value = v;
  3244. };
  3245. var clone = function () {
  3246. return Cell(get());
  3247. };
  3248. return {
  3249. get: get,
  3250. set: set,
  3251. clone: clone
  3252. };
  3253. };
  3254. var focus$1 = function (element) {
  3255. element.dom().focus();
  3256. };
  3257. var blur = function (element) {
  3258. element.dom().blur();
  3259. };
  3260. var hasFocus = function (element) {
  3261. var doc = owner(element).dom();
  3262. return element.dom() === doc.activeElement;
  3263. };
  3264. var active = function (_DOC) {
  3265. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  3266. return Option.from(doc.activeElement).map(Element.fromDom);
  3267. };
  3268. var search = function (element) {
  3269. return active(owner(element)).filter(function (e) {
  3270. return element.dom().contains(e.dom());
  3271. });
  3272. };
  3273. var global = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  3274. var global$1 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  3275. var openLink = function (target) {
  3276. var link = domGlobals.document.createElement('a');
  3277. link.target = '_blank';
  3278. link.href = target.href;
  3279. link.rel = 'noreferrer noopener';
  3280. var nuEvt = domGlobals.document.createEvent('MouseEvents');
  3281. nuEvt.initMouseEvent('click', true, true, domGlobals.window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  3282. domGlobals.document.body.appendChild(link);
  3283. link.dispatchEvent(nuEvt);
  3284. domGlobals.document.body.removeChild(link);
  3285. };
  3286. var TinyCodeDupe = { openLink: openLink };
  3287. var isSkinDisabled = function (editor) {
  3288. return editor.settings.skin === false;
  3289. };
  3290. var readOnlyOnInit = function (editor) {
  3291. return false;
  3292. };
  3293. var formatChanged = 'formatChanged';
  3294. var orientationChanged = 'orientationChanged';
  3295. var dropupDismissed = 'dropupDismissed';
  3296. var TinyChannels = {
  3297. formatChanged: constant(formatChanged),
  3298. orientationChanged: constant(orientationChanged),
  3299. dropupDismissed: constant(dropupDismissed)
  3300. };
  3301. var fromHtml$1 = function (html, scope) {
  3302. var doc = scope || domGlobals.document;
  3303. var div = doc.createElement('div');
  3304. div.innerHTML = html;
  3305. return children(Element.fromDom(div));
  3306. };
  3307. var get$3 = function (element) {
  3308. return element.dom().innerHTML;
  3309. };
  3310. var set$1 = function (element, content) {
  3311. var owner$1 = owner(element);
  3312. var docDom = owner$1.dom();
  3313. var fragment = Element.fromDom(docDom.createDocumentFragment());
  3314. var contentElements = fromHtml$1(content, docDom);
  3315. append$1(fragment, contentElements);
  3316. empty(element);
  3317. append(element, fragment);
  3318. };
  3319. var getOuter = function (element) {
  3320. var container = Element.fromTag('div');
  3321. var clone = Element.fromDom(element.dom().cloneNode(true));
  3322. append(container, clone);
  3323. return get$3(container);
  3324. };
  3325. var clone$1 = function (original, isDeep) {
  3326. return Element.fromDom(original.dom().cloneNode(isDeep));
  3327. };
  3328. var shallow$1 = function (original) {
  3329. return clone$1(original, false);
  3330. };
  3331. var getHtml = function (element) {
  3332. var clone = shallow$1(element);
  3333. return getOuter(clone);
  3334. };
  3335. var element = function (elem) {
  3336. return getHtml(elem);
  3337. };
  3338. var chooseChannels = function (channels, message) {
  3339. return message.universal() ? channels : filter(channels, function (ch) {
  3340. return contains(message.channels(), ch);
  3341. });
  3342. };
  3343. var events = function (receiveConfig) {
  3344. return derive([run(receive(), function (component, message) {
  3345. var channelMap = receiveConfig.channels;
  3346. var channels = keys(channelMap);
  3347. var targetChannels = chooseChannels(channels, message);
  3348. each$1(targetChannels, function (ch) {
  3349. var channelInfo = channelMap[ch];
  3350. var channelSchema = channelInfo.schema;
  3351. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, message.data());
  3352. channelInfo.onReceive(component, data);
  3353. });
  3354. })]);
  3355. };
  3356. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  3357. events: events
  3358. });
  3359. var cat = function (arr) {
  3360. var r = [];
  3361. var push = function (x) {
  3362. r.push(x);
  3363. };
  3364. for (var i = 0; i < arr.length; i++) {
  3365. arr[i].each(push);
  3366. }
  3367. return r;
  3368. };
  3369. var findMap = function (arr, f) {
  3370. for (var i = 0; i < arr.length; i++) {
  3371. var r = f(arr[i], i);
  3372. if (r.isSome()) {
  3373. return r;
  3374. }
  3375. }
  3376. return Option.none();
  3377. };
  3378. var liftN = function (arr, f) {
  3379. var r = [];
  3380. for (var i = 0; i < arr.length; i++) {
  3381. var x = arr[i];
  3382. if (x.isSome()) {
  3383. r.push(x.getOrDie());
  3384. } else {
  3385. return Option.none();
  3386. }
  3387. }
  3388. return Option.some(f.apply(null, r));
  3389. };
  3390. function lift() {
  3391. var args = [];
  3392. for (var _i = 0; _i < arguments.length; _i++) {
  3393. args[_i] = arguments[_i];
  3394. }
  3395. var f = args.pop();
  3396. return liftN(args, f);
  3397. }
  3398. var Options = /*#__PURE__*/Object.freeze({
  3399. cat: cat,
  3400. findMap: findMap,
  3401. liftN: liftN,
  3402. lift: lift
  3403. });
  3404. var unknown$3 = 'unknown';
  3405. var EventConfiguration;
  3406. (function (EventConfiguration) {
  3407. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3408. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3409. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3410. }(EventConfiguration || (EventConfiguration = {})));
  3411. var eventConfig = Cell({});
  3412. var makeEventLogger = function (eventName, initialTarget) {
  3413. var sequence = [];
  3414. var startTime = new Date().getTime();
  3415. return {
  3416. logEventCut: function (name, target, purpose) {
  3417. sequence.push({
  3418. outcome: 'cut',
  3419. target: target,
  3420. purpose: purpose
  3421. });
  3422. },
  3423. logEventStopped: function (name, target, purpose) {
  3424. sequence.push({
  3425. outcome: 'stopped',
  3426. target: target,
  3427. purpose: purpose
  3428. });
  3429. },
  3430. logNoParent: function (name, target, purpose) {
  3431. sequence.push({
  3432. outcome: 'no-parent',
  3433. target: target,
  3434. purpose: purpose
  3435. });
  3436. },
  3437. logEventNoHandlers: function (name, target) {
  3438. sequence.push({
  3439. outcome: 'no-handlers-left',
  3440. target: target
  3441. });
  3442. },
  3443. logEventResponse: function (name, target, purpose) {
  3444. sequence.push({
  3445. outcome: 'response',
  3446. purpose: purpose,
  3447. target: target
  3448. });
  3449. },
  3450. write: function () {
  3451. var finishTime = new Date().getTime();
  3452. if (contains([
  3453. 'mousemove',
  3454. 'mouseover',
  3455. 'mouseout',
  3456. systemInit()
  3457. ], eventName)) {
  3458. return;
  3459. }
  3460. domGlobals.console.log(eventName, {
  3461. event: eventName,
  3462. time: finishTime - startTime,
  3463. target: initialTarget.dom(),
  3464. sequence: map$1(sequence, function (s) {
  3465. if (!contains([
  3466. 'cut',
  3467. 'stopped',
  3468. 'response'
  3469. ], s.outcome)) {
  3470. return s.outcome;
  3471. } else {
  3472. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3473. }
  3474. })
  3475. });
  3476. }
  3477. };
  3478. };
  3479. var processEvent = function (eventName, initialTarget, f) {
  3480. var status = readOptFrom$1(eventConfig.get(), eventName).orThunk(function () {
  3481. var patterns = keys(eventConfig.get());
  3482. return findMap(patterns, function (p) {
  3483. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  3484. });
  3485. }).getOr(EventConfiguration.NORMAL);
  3486. switch (status) {
  3487. case EventConfiguration.NORMAL:
  3488. return f(noLogger());
  3489. case EventConfiguration.LOGGING: {
  3490. var logger = makeEventLogger(eventName, initialTarget);
  3491. var output = f(logger);
  3492. logger.write();
  3493. return output;
  3494. }
  3495. case EventConfiguration.STOP:
  3496. return true;
  3497. }
  3498. };
  3499. var path$1 = [
  3500. 'alloy/data/Fields',
  3501. 'alloy/debugging/Debugging'
  3502. ];
  3503. var getTrace = function () {
  3504. var err = new Error();
  3505. if (err.stack !== undefined) {
  3506. var lines = err.stack.split('\n');
  3507. return find$2(lines, function (line) {
  3508. return line.indexOf('alloy') > 0 && !exists(path$1, function (p) {
  3509. return line.indexOf(p) > -1;
  3510. });
  3511. }).getOr(unknown$3);
  3512. } else {
  3513. return unknown$3;
  3514. }
  3515. };
  3516. var ignoreEvent = {
  3517. logEventCut: noop,
  3518. logEventStopped: noop,
  3519. logNoParent: noop,
  3520. logEventNoHandlers: noop,
  3521. logEventResponse: noop,
  3522. write: noop
  3523. };
  3524. var monitorEvent = function (eventName, initialTarget, f) {
  3525. return processEvent(eventName, initialTarget, f);
  3526. };
  3527. var noLogger = constant(ignoreEvent);
  3528. var menuFields = constant([
  3529. strict$1('menu'),
  3530. strict$1('selectedMenu')
  3531. ]);
  3532. var itemFields = constant([
  3533. strict$1('item'),
  3534. strict$1('selectedItem')
  3535. ]);
  3536. var schema = constant(objOf(itemFields().concat(menuFields())));
  3537. var itemSchema = constant(objOf(itemFields()));
  3538. var _initSize = strictObjOf('initSize', [
  3539. strict$1('numColumns'),
  3540. strict$1('numRows')
  3541. ]);
  3542. var itemMarkers = function () {
  3543. return strictOf('markers', itemSchema());
  3544. };
  3545. var tieredMenuMarkers = function () {
  3546. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3547. };
  3548. var markers = function (required) {
  3549. return strictObjOf('markers', map$1(required, strict$1));
  3550. };
  3551. var onPresenceHandler = function (label, fieldName, presence) {
  3552. var trace = getTrace();
  3553. return field(fieldName, fieldName, presence, valueOf(function (f) {
  3554. return Result.value(function () {
  3555. var args = [];
  3556. for (var _i = 0; _i < arguments.length; _i++) {
  3557. args[_i] = arguments[_i];
  3558. }
  3559. return f.apply(undefined, args);
  3560. });
  3561. }));
  3562. };
  3563. var onHandler = function (fieldName) {
  3564. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  3565. };
  3566. var onKeyboardHandler = function (fieldName) {
  3567. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  3568. };
  3569. var onStrictHandler = function (fieldName) {
  3570. return onPresenceHandler('onHandler', fieldName, strict());
  3571. };
  3572. var onStrictKeyboardHandler = function (fieldName) {
  3573. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  3574. };
  3575. var output = function (name, value) {
  3576. return state$1(name, constant(value));
  3577. };
  3578. var snapshot = function (name) {
  3579. return state$1(name, identity);
  3580. };
  3581. var initSize = constant(_initSize);
  3582. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  3583. onStrictHandler('onReceive'),
  3584. defaulted$1('schema', anyValue$1())
  3585. ])))];
  3586. var Receiving = create$1({
  3587. fields: ReceivingSchema,
  3588. name: 'receiving',
  3589. active: ActiveReceiving
  3590. });
  3591. var updateAriaState = function (component, toggleConfig, toggleState) {
  3592. var ariaInfo = toggleConfig.aria;
  3593. ariaInfo.update(component, ariaInfo, toggleState.get());
  3594. };
  3595. var updateClass = function (component, toggleConfig, toggleState) {
  3596. toggleConfig.toggleClass.each(function (toggleClass) {
  3597. if (toggleState.get()) {
  3598. add$2(component.element(), toggleClass);
  3599. } else {
  3600. remove$4(component.element(), toggleClass);
  3601. }
  3602. });
  3603. };
  3604. var toggle$2 = function (component, toggleConfig, toggleState) {
  3605. set$2(component, toggleConfig, toggleState, !toggleState.get());
  3606. };
  3607. var on = function (component, toggleConfig, toggleState) {
  3608. toggleState.set(true);
  3609. updateClass(component, toggleConfig, toggleState);
  3610. updateAriaState(component, toggleConfig, toggleState);
  3611. };
  3612. var off = function (component, toggleConfig, toggleState) {
  3613. toggleState.set(false);
  3614. updateClass(component, toggleConfig, toggleState);
  3615. updateAriaState(component, toggleConfig, toggleState);
  3616. };
  3617. var set$2 = function (component, toggleConfig, toggleState, state) {
  3618. var action = state ? on : off;
  3619. action(component, toggleConfig, toggleState);
  3620. };
  3621. var isOn = function (component, toggleConfig, toggleState) {
  3622. return toggleState.get();
  3623. };
  3624. var onLoad = function (component, toggleConfig, toggleState) {
  3625. set$2(component, toggleConfig, toggleState, toggleConfig.selected);
  3626. };
  3627. var ToggleApis = /*#__PURE__*/Object.freeze({
  3628. onLoad: onLoad,
  3629. toggle: toggle$2,
  3630. isOn: isOn,
  3631. on: on,
  3632. off: off,
  3633. set: set$2
  3634. });
  3635. var exhibit = function (base, toggleConfig, toggleState) {
  3636. return nu$5({});
  3637. };
  3638. var events$1 = function (toggleConfig, toggleState) {
  3639. var execute = executeEvent(toggleConfig, toggleState, toggle$2);
  3640. var load = loadEvent(toggleConfig, toggleState, onLoad);
  3641. return derive(flatten([
  3642. toggleConfig.toggleOnExecute ? [execute] : [],
  3643. [load]
  3644. ]));
  3645. };
  3646. var ActiveToggle = /*#__PURE__*/Object.freeze({
  3647. exhibit: exhibit,
  3648. events: events$1
  3649. });
  3650. var SetupBehaviourCellState = function (initialState) {
  3651. var init = function () {
  3652. var cell = Cell(initialState);
  3653. var get = function () {
  3654. return cell.get();
  3655. };
  3656. var set = function (newState) {
  3657. return cell.set(newState);
  3658. };
  3659. var clear = function () {
  3660. return cell.set(initialState);
  3661. };
  3662. var readState = function () {
  3663. return cell.get();
  3664. };
  3665. return {
  3666. get: get,
  3667. set: set,
  3668. clear: clear,
  3669. readState: readState
  3670. };
  3671. };
  3672. return { init: init };
  3673. };
  3674. var updatePressed = function (component, ariaInfo, status) {
  3675. set(component.element(), 'aria-pressed', status);
  3676. if (ariaInfo.syncWithExpanded) {
  3677. updateExpanded(component, ariaInfo, status);
  3678. }
  3679. };
  3680. var updateSelected = function (component, ariaInfo, status) {
  3681. set(component.element(), 'aria-selected', status);
  3682. };
  3683. var updateChecked = function (component, ariaInfo, status) {
  3684. set(component.element(), 'aria-checked', status);
  3685. };
  3686. var updateExpanded = function (component, ariaInfo, status) {
  3687. set(component.element(), 'aria-expanded', status);
  3688. };
  3689. var ToggleSchema = [
  3690. defaulted$1('selected', false),
  3691. option('toggleClass'),
  3692. defaulted$1('toggleOnExecute', true),
  3693. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  3694. pressed: [
  3695. defaulted$1('syncWithExpanded', false),
  3696. output('update', updatePressed)
  3697. ],
  3698. checked: [output('update', updateChecked)],
  3699. expanded: [output('update', updateExpanded)],
  3700. selected: [output('update', updateSelected)],
  3701. none: [output('update', noop)]
  3702. }))
  3703. ];
  3704. var Toggling = create$1({
  3705. fields: ToggleSchema,
  3706. name: 'toggling',
  3707. active: ActiveToggle,
  3708. apis: ToggleApis,
  3709. state: SetupBehaviourCellState(false)
  3710. });
  3711. var format = function (command, update) {
  3712. return Receiving.config({
  3713. channels: wrap$1(TinyChannels.formatChanged(), {
  3714. onReceive: function (button, data) {
  3715. if (data.command === command) {
  3716. update(button, data.state);
  3717. }
  3718. }
  3719. })
  3720. });
  3721. };
  3722. var orientation = function (onReceive) {
  3723. return Receiving.config({ channels: wrap$1(TinyChannels.orientationChanged(), { onReceive: onReceive }) });
  3724. };
  3725. var receive$1 = function (channel, onReceive) {
  3726. return {
  3727. key: channel,
  3728. value: { onReceive: onReceive }
  3729. };
  3730. };
  3731. var Receivers = {
  3732. format: format,
  3733. orientation: orientation,
  3734. receive: receive$1
  3735. };
  3736. var prefix = 'tinymce-mobile';
  3737. var resolve$1 = function (p) {
  3738. return prefix + '-' + p;
  3739. };
  3740. var Styles = {
  3741. resolve: resolve$1,
  3742. prefix: constant(prefix)
  3743. };
  3744. var events$2 = function (optAction) {
  3745. var executeHandler = function (action) {
  3746. return run(execute(), function (component, simulatedEvent) {
  3747. action(component);
  3748. simulatedEvent.stop();
  3749. });
  3750. };
  3751. var onClick = function (component, simulatedEvent) {
  3752. simulatedEvent.stop();
  3753. emitExecute(component);
  3754. };
  3755. var onMousedown = function (component, simulatedEvent) {
  3756. simulatedEvent.cut();
  3757. };
  3758. var pointerEvents = PlatformDetection$1.detect().deviceType.isTouch() ? [run(tap(), onClick)] : [
  3759. run(click(), onClick),
  3760. run(mousedown(), onMousedown)
  3761. ];
  3762. return derive(flatten([
  3763. optAction.map(executeHandler).toArray(),
  3764. pointerEvents
  3765. ]));
  3766. };
  3767. var focus$2 = function (component, focusConfig) {
  3768. if (!focusConfig.ignore) {
  3769. focus$1(component.element());
  3770. focusConfig.onFocus(component);
  3771. }
  3772. };
  3773. var blur$1 = function (component, focusConfig) {
  3774. if (!focusConfig.ignore) {
  3775. blur(component.element());
  3776. }
  3777. };
  3778. var isFocused = function (component) {
  3779. return hasFocus(component.element());
  3780. };
  3781. var FocusApis = /*#__PURE__*/Object.freeze({
  3782. focus: focus$2,
  3783. blur: blur$1,
  3784. isFocused: isFocused
  3785. });
  3786. var exhibit$1 = function (base, focusConfig) {
  3787. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3788. return nu$5(mod);
  3789. };
  3790. var events$3 = function (focusConfig) {
  3791. return derive([run(focus(), function (component, simulatedEvent) {
  3792. focus$2(component, focusConfig);
  3793. simulatedEvent.stop();
  3794. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3795. simulatedEvent.event().prevent();
  3796. })] : []));
  3797. };
  3798. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3799. exhibit: exhibit$1,
  3800. events: events$3
  3801. });
  3802. var FocusSchema = [
  3803. onHandler('onFocus'),
  3804. defaulted$1('stopMousedown', false),
  3805. defaulted$1('ignore', false)
  3806. ];
  3807. var Focusing = create$1({
  3808. fields: FocusSchema,
  3809. name: 'focusing',
  3810. active: ActiveFocus,
  3811. apis: FocusApis
  3812. });
  3813. var isSupported = function (dom) {
  3814. return dom.style !== undefined;
  3815. };
  3816. var internalSet = function (dom, property, value) {
  3817. if (!isString(value)) {
  3818. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3819. throw new Error('CSS value must be a string: ' + value);
  3820. }
  3821. if (isSupported(dom)) {
  3822. dom.style.setProperty(property, value);
  3823. }
  3824. };
  3825. var internalRemove = function (dom, property) {
  3826. if (isSupported(dom)) {
  3827. dom.style.removeProperty(property);
  3828. }
  3829. };
  3830. var set$3 = function (element, property, value) {
  3831. var dom = element.dom();
  3832. internalSet(dom, property, value);
  3833. };
  3834. var setAll$1 = function (element, css) {
  3835. var dom = element.dom();
  3836. each(css, function (v, k) {
  3837. internalSet(dom, k, v);
  3838. });
  3839. };
  3840. var setOptions = function (element, css) {
  3841. var dom = element.dom();
  3842. each(css, function (v, k) {
  3843. v.fold(function () {
  3844. internalRemove(dom, k);
  3845. }, function (value) {
  3846. internalSet(dom, k, value);
  3847. });
  3848. });
  3849. };
  3850. var get$4 = function (element, property) {
  3851. var dom = element.dom();
  3852. var styles = domGlobals.window.getComputedStyle(dom);
  3853. var r = styles.getPropertyValue(property);
  3854. var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3855. return v === null ? undefined : v;
  3856. };
  3857. var getUnsafeProperty = function (dom, property) {
  3858. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  3859. };
  3860. var getRaw = function (element, property) {
  3861. var dom = element.dom();
  3862. var raw = getUnsafeProperty(dom, property);
  3863. return Option.from(raw).filter(function (r) {
  3864. return r.length > 0;
  3865. });
  3866. };
  3867. var getAllRaw = function (element) {
  3868. var css = {};
  3869. var dom = element.dom();
  3870. if (isSupported(dom)) {
  3871. for (var i = 0; i < dom.style.length; i++) {
  3872. var ruleName = dom.style.item(i);
  3873. css[ruleName] = dom.style[ruleName];
  3874. }
  3875. }
  3876. return css;
  3877. };
  3878. var isValidValue = function (tag, property, value) {
  3879. var element = Element.fromTag(tag);
  3880. set$3(element, property, value);
  3881. var style = getRaw(element, property);
  3882. return style.isSome();
  3883. };
  3884. var remove$5 = function (element, property) {
  3885. var dom = element.dom();
  3886. internalRemove(dom, property);
  3887. if (has$1(element, 'style') && trim(get$1(element, 'style')) === '') {
  3888. remove$1(element, 'style');
  3889. }
  3890. };
  3891. var preserve = function (element, f) {
  3892. var oldStyles = get$1(element, 'style');
  3893. var result = f(element);
  3894. var restore = oldStyles === undefined ? remove$1 : set;
  3895. restore(element, 'style', oldStyles);
  3896. return result;
  3897. };
  3898. var copy = function (source, target) {
  3899. var sourceDom = source.dom();
  3900. var targetDom = target.dom();
  3901. if (isSupported(sourceDom) && isSupported(targetDom)) {
  3902. targetDom.style.cssText = sourceDom.style.cssText;
  3903. }
  3904. };
  3905. var reflow = function (e) {
  3906. return e.dom().offsetWidth;
  3907. };
  3908. var transferOne$1 = function (source, destination, style) {
  3909. getRaw(source, style).each(function (value) {
  3910. if (getRaw(destination, style).isNone()) {
  3911. set$3(destination, style, value);
  3912. }
  3913. });
  3914. };
  3915. var transfer$1 = function (source, destination, styles) {
  3916. if (!isElement(source) || !isElement(destination)) {
  3917. return;
  3918. }
  3919. each$1(styles, function (style) {
  3920. transferOne$1(source, destination, style);
  3921. });
  3922. };
  3923. var Css = /*#__PURE__*/Object.freeze({
  3924. copy: copy,
  3925. set: set$3,
  3926. preserve: preserve,
  3927. setAll: setAll$1,
  3928. setOptions: setOptions,
  3929. remove: remove$5,
  3930. get: get$4,
  3931. getRaw: getRaw,
  3932. getAllRaw: getAllRaw,
  3933. isValidValue: isValidValue,
  3934. reflow: reflow,
  3935. transfer: transfer$1
  3936. });
  3937. function Dimension (name, getOffset) {
  3938. var set = function (element, h) {
  3939. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3940. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3941. }
  3942. var dom = element.dom();
  3943. if (isSupported(dom)) {
  3944. dom.style[name] = h + 'px';
  3945. }
  3946. };
  3947. var get = function (element) {
  3948. var r = getOffset(element);
  3949. if (r <= 0 || r === null) {
  3950. var css = get$4(element, name);
  3951. return parseFloat(css) || 0;
  3952. }
  3953. return r;
  3954. };
  3955. var getOuter = get;
  3956. var aggregate = function (element, properties) {
  3957. return foldl(properties, function (acc, property) {
  3958. var val = get$4(element, property);
  3959. var value = val === undefined ? 0 : parseInt(val, 10);
  3960. return isNaN(value) ? acc : acc + value;
  3961. }, 0);
  3962. };
  3963. var max = function (element, value, properties) {
  3964. var cumulativeInclusions = aggregate(element, properties);
  3965. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3966. return absoluteMax;
  3967. };
  3968. return {
  3969. set: set,
  3970. get: get,
  3971. getOuter: getOuter,
  3972. aggregate: aggregate,
  3973. max: max
  3974. };
  3975. }
  3976. var api = Dimension('height', function (element) {
  3977. var dom = element.dom();
  3978. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3979. });
  3980. var get$5 = function (element) {
  3981. return api.get(element);
  3982. };
  3983. var ancestors = function (scope, predicate, isRoot) {
  3984. return filter(parents(scope, isRoot), predicate);
  3985. };
  3986. var siblings$1 = function (scope, predicate) {
  3987. return filter(siblings(scope), predicate);
  3988. };
  3989. var children$1 = function (scope, predicate) {
  3990. return filter(children(scope), predicate);
  3991. };
  3992. var all$2 = function (selector) {
  3993. return all(selector);
  3994. };
  3995. var ancestors$1 = function (scope, selector, isRoot) {
  3996. return ancestors(scope, function (e) {
  3997. return is(e, selector);
  3998. }, isRoot);
  3999. };
  4000. var siblings$2 = function (scope, selector) {
  4001. return siblings$1(scope, function (e) {
  4002. return is(e, selector);
  4003. });
  4004. };
  4005. var children$2 = function (scope, selector) {
  4006. return children$1(scope, function (e) {
  4007. return is(e, selector);
  4008. });
  4009. };
  4010. var descendants = function (scope, selector) {
  4011. return all(selector, scope);
  4012. };
  4013. var SelectorFilter = /*#__PURE__*/Object.freeze({
  4014. all: all$2,
  4015. ancestors: ancestors$1,
  4016. siblings: siblings$2,
  4017. children: children$2,
  4018. descendants: descendants
  4019. });
  4020. var first = function (selector) {
  4021. return one(selector);
  4022. };
  4023. var ancestor$1 = function (scope, selector, isRoot) {
  4024. return ancestor(scope, function (e) {
  4025. return is(e, selector);
  4026. }, isRoot);
  4027. };
  4028. var sibling$1 = function (scope, selector) {
  4029. return sibling(scope, function (e) {
  4030. return is(e, selector);
  4031. });
  4032. };
  4033. var child$2 = function (scope, selector) {
  4034. return child$1(scope, function (e) {
  4035. return is(e, selector);
  4036. });
  4037. };
  4038. var descendant$1 = function (scope, selector) {
  4039. return one(selector, scope);
  4040. };
  4041. var closest$2 = function (scope, selector, isRoot) {
  4042. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  4043. };
  4044. var SelectorFind = /*#__PURE__*/Object.freeze({
  4045. first: first,
  4046. ancestor: ancestor$1,
  4047. sibling: sibling$1,
  4048. child: child$2,
  4049. descendant: descendant$1,
  4050. closest: closest$2
  4051. });
  4052. var BACKSPACE = function () {
  4053. return [8];
  4054. };
  4055. var TAB = function () {
  4056. return [9];
  4057. };
  4058. var ENTER = function () {
  4059. return [13];
  4060. };
  4061. var ESCAPE = function () {
  4062. return [27];
  4063. };
  4064. var SPACE = function () {
  4065. return [32];
  4066. };
  4067. var LEFT = function () {
  4068. return [37];
  4069. };
  4070. var UP = function () {
  4071. return [38];
  4072. };
  4073. var RIGHT = function () {
  4074. return [39];
  4075. };
  4076. var DOWN = function () {
  4077. return [40];
  4078. };
  4079. var cyclePrev = function (values, index, predicate) {
  4080. var before = reverse(values.slice(0, index));
  4081. var after = reverse(values.slice(index + 1));
  4082. return find$2(before.concat(after), predicate);
  4083. };
  4084. var tryPrev = function (values, index, predicate) {
  4085. var before = reverse(values.slice(0, index));
  4086. return find$2(before, predicate);
  4087. };
  4088. var cycleNext = function (values, index, predicate) {
  4089. var before = values.slice(0, index);
  4090. var after = values.slice(index + 1);
  4091. return find$2(after.concat(before), predicate);
  4092. };
  4093. var tryNext = function (values, index, predicate) {
  4094. var after = values.slice(index + 1);
  4095. return find$2(after, predicate);
  4096. };
  4097. var inSet = function (keys) {
  4098. return function (event) {
  4099. var raw = event.raw();
  4100. return contains(keys, raw.which);
  4101. };
  4102. };
  4103. var and = function (preds) {
  4104. return function (event) {
  4105. return forall(preds, function (pred) {
  4106. return pred(event);
  4107. });
  4108. };
  4109. };
  4110. var is$1 = function (key) {
  4111. return function (event) {
  4112. var raw = event.raw();
  4113. return raw.which === key;
  4114. };
  4115. };
  4116. var isShift = function (event) {
  4117. var raw = event.raw();
  4118. return raw.shiftKey === true;
  4119. };
  4120. var isControl = function (event) {
  4121. var raw = event.raw();
  4122. return raw.ctrlKey === true;
  4123. };
  4124. var isNotShift = not(isShift);
  4125. var basic = function (key, action) {
  4126. return {
  4127. matches: is$1(key),
  4128. classification: action
  4129. };
  4130. };
  4131. var rule = function (matches, action) {
  4132. return {
  4133. matches: matches,
  4134. classification: action
  4135. };
  4136. };
  4137. var choose$2 = function (transitions, event) {
  4138. var transition = find$2(transitions, function (t) {
  4139. return t.matches(event);
  4140. });
  4141. return transition.map(function (t) {
  4142. return t.classification;
  4143. });
  4144. };
  4145. var KeyRules = /*#__PURE__*/Object.freeze({
  4146. basic: basic,
  4147. rule: rule,
  4148. choose: choose$2
  4149. });
  4150. var cycleBy = function (value, delta, min, max) {
  4151. var r = value + delta;
  4152. if (r > max) {
  4153. return min;
  4154. } else {
  4155. return r < min ? max : r;
  4156. }
  4157. };
  4158. var cap = function (value, min, max) {
  4159. if (value <= min) {
  4160. return min;
  4161. } else {
  4162. return value >= max ? max : value;
  4163. }
  4164. };
  4165. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  4166. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  4167. each$1(highlighted, function (h) {
  4168. if (!exists(skip, function (skipComp) {
  4169. return skipComp.element() === h;
  4170. })) {
  4171. remove$4(h, hConfig.highlightClass);
  4172. component.getSystem().getByDom(h).each(function (target) {
  4173. hConfig.onDehighlight(component, target);
  4174. emit(target, dehighlight());
  4175. });
  4176. }
  4177. });
  4178. };
  4179. var dehighlightAll = function (component, hConfig, hState) {
  4180. return dehighlightAllExcept(component, hConfig, hState, []);
  4181. };
  4182. var dehighlight$1 = function (component, hConfig, hState, target) {
  4183. if (isHighlighted(component, hConfig, hState, target)) {
  4184. remove$4(target.element(), hConfig.highlightClass);
  4185. hConfig.onDehighlight(component, target);
  4186. emit(target, dehighlight());
  4187. }
  4188. };
  4189. var highlight$1 = function (component, hConfig, hState, target) {
  4190. dehighlightAllExcept(component, hConfig, hState, [target]);
  4191. if (!isHighlighted(component, hConfig, hState, target)) {
  4192. add$2(target.element(), hConfig.highlightClass);
  4193. hConfig.onHighlight(component, target);
  4194. emit(target, highlight());
  4195. }
  4196. };
  4197. var highlightFirst = function (component, hConfig, hState) {
  4198. getFirst(component, hConfig, hState).each(function (firstComp) {
  4199. highlight$1(component, hConfig, hState, firstComp);
  4200. });
  4201. };
  4202. var highlightLast = function (component, hConfig, hState) {
  4203. getLast(component, hConfig, hState).each(function (lastComp) {
  4204. highlight$1(component, hConfig, hState, lastComp);
  4205. });
  4206. };
  4207. var highlightAt = function (component, hConfig, hState, index) {
  4208. getByIndex(component, hConfig, hState, index).fold(function (err) {
  4209. throw new Error(err);
  4210. }, function (firstComp) {
  4211. highlight$1(component, hConfig, hState, firstComp);
  4212. });
  4213. };
  4214. var highlightBy = function (component, hConfig, hState, predicate) {
  4215. var candidates = getCandidates(component, hConfig, hState);
  4216. var targetComp = find$2(candidates, predicate);
  4217. targetComp.each(function (c) {
  4218. highlight$1(component, hConfig, hState, c);
  4219. });
  4220. };
  4221. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  4222. return has$2(queryTarget.element(), hConfig.highlightClass);
  4223. };
  4224. var getHighlighted = function (component, hConfig, hState) {
  4225. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  4226. return component.getSystem().getByDom(e).toOption();
  4227. });
  4228. };
  4229. var getByIndex = function (component, hConfig, hState, index) {
  4230. var items = descendants(component.element(), '.' + hConfig.itemClass);
  4231. return Option.from(items[index]).fold(function () {
  4232. return Result.error('No element found with index ' + index);
  4233. }, component.getSystem().getByDom);
  4234. };
  4235. var getFirst = function (component, hConfig, hState) {
  4236. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  4237. return component.getSystem().getByDom(e).toOption();
  4238. });
  4239. };
  4240. var getLast = function (component, hConfig, hState) {
  4241. var items = descendants(component.element(), '.' + hConfig.itemClass);
  4242. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  4243. return last.bind(function (c) {
  4244. return component.getSystem().getByDom(c).toOption();
  4245. });
  4246. };
  4247. var getDelta = function (component, hConfig, hState, delta) {
  4248. var items = descendants(component.element(), '.' + hConfig.itemClass);
  4249. var current = findIndex(items, function (item) {
  4250. return has$2(item, hConfig.highlightClass);
  4251. });
  4252. return current.bind(function (selected) {
  4253. var dest = cycleBy(selected, delta, 0, items.length - 1);
  4254. return component.getSystem().getByDom(items[dest]).toOption();
  4255. });
  4256. };
  4257. var getPrevious = function (component, hConfig, hState) {
  4258. return getDelta(component, hConfig, hState, -1);
  4259. };
  4260. var getNext = function (component, hConfig, hState) {
  4261. return getDelta(component, hConfig, hState, +1);
  4262. };
  4263. var getCandidates = function (component, hConfig, hState) {
  4264. var items = descendants(component.element(), '.' + hConfig.itemClass);
  4265. return cat(map$1(items, function (i) {
  4266. return component.getSystem().getByDom(i).toOption();
  4267. }));
  4268. };
  4269. var HighlightApis = /*#__PURE__*/Object.freeze({
  4270. dehighlightAll: dehighlightAll,
  4271. dehighlight: dehighlight$1,
  4272. highlight: highlight$1,
  4273. highlightFirst: highlightFirst,
  4274. highlightLast: highlightLast,
  4275. highlightAt: highlightAt,
  4276. highlightBy: highlightBy,
  4277. isHighlighted: isHighlighted,
  4278. getHighlighted: getHighlighted,
  4279. getFirst: getFirst,
  4280. getLast: getLast,
  4281. getPrevious: getPrevious,
  4282. getNext: getNext,
  4283. getCandidates: getCandidates
  4284. });
  4285. var HighlightSchema = [
  4286. strict$1('highlightClass'),
  4287. strict$1('itemClass'),
  4288. onHandler('onHighlight'),
  4289. onHandler('onDehighlight')
  4290. ];
  4291. var Highlighting = create$1({
  4292. fields: HighlightSchema,
  4293. name: 'highlighting',
  4294. apis: HighlightApis
  4295. });
  4296. var reportFocusShifting = function (component, prevFocus, newFocus) {
  4297. var noChange = prevFocus.exists(function (p) {
  4298. return newFocus.exists(function (n) {
  4299. return eq(n, p);
  4300. });
  4301. });
  4302. if (!noChange) {
  4303. emitWith(component, focusShifted(), {
  4304. prevFocus: prevFocus,
  4305. newFocus: newFocus
  4306. });
  4307. }
  4308. };
  4309. var dom = function () {
  4310. var get = function (component) {
  4311. return search(component.element());
  4312. };
  4313. var set = function (component, focusee) {
  4314. var prevFocus = get(component);
  4315. component.getSystem().triggerFocus(focusee, component.element());
  4316. var newFocus = get(component);
  4317. reportFocusShifting(component, prevFocus, newFocus);
  4318. };
  4319. return {
  4320. get: get,
  4321. set: set
  4322. };
  4323. };
  4324. var highlights = function () {
  4325. var get = function (component) {
  4326. return Highlighting.getHighlighted(component).map(function (item) {
  4327. return item.element();
  4328. });
  4329. };
  4330. var set = function (component, element) {
  4331. var prevFocus = get(component);
  4332. component.getSystem().getByDom(element).fold(noop, function (item) {
  4333. Highlighting.highlight(component, item);
  4334. });
  4335. var newFocus = get(component);
  4336. reportFocusShifting(component, prevFocus, newFocus);
  4337. };
  4338. return {
  4339. get: get,
  4340. set: set
  4341. };
  4342. };
  4343. var FocusInsideModes;
  4344. (function (FocusInsideModes) {
  4345. FocusInsideModes['OnFocusMode'] = 'onFocus';
  4346. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  4347. FocusInsideModes['OnApiMode'] = 'onApi';
  4348. }(FocusInsideModes || (FocusInsideModes = {})));
  4349. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  4350. var schema = function () {
  4351. return infoSchema.concat([
  4352. defaulted$1('focusManager', dom()),
  4353. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  4354. return contains([
  4355. 'onFocus',
  4356. 'onEnterOrSpace',
  4357. 'onApi'
  4358. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  4359. })),
  4360. output('handler', me),
  4361. output('state', stateInit),
  4362. output('sendFocusIn', optFocusIn)
  4363. ]);
  4364. };
  4365. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  4366. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  4367. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  4368. return rule(component, simulatedEvent, keyingConfig, keyingState);
  4369. });
  4370. };
  4371. var toEvents = function (keyingConfig, keyingState) {
  4372. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  4373. return run(focus(), function (component, simulatedEvent) {
  4374. focusIn(component, keyingConfig, keyingState);
  4375. simulatedEvent.stop();
  4376. });
  4377. });
  4378. var tryGoInsideComponent = function (component, simulatedEvent) {
  4379. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  4380. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  4381. optFocusIn(keyingConfig).each(function (focusIn) {
  4382. focusIn(component, keyingConfig, keyingState);
  4383. simulatedEvent.stop();
  4384. });
  4385. }
  4386. };
  4387. return derive(onFocusHandler.toArray().concat([
  4388. run(keydown(), function (component, simulatedEvent) {
  4389. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  4390. tryGoInsideComponent(component, simulatedEvent);
  4391. }, function (_) {
  4392. simulatedEvent.stop();
  4393. });
  4394. }),
  4395. run(keyup(), function (component, simulatedEvent) {
  4396. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  4397. simulatedEvent.stop();
  4398. });
  4399. })
  4400. ]));
  4401. };
  4402. var me = {
  4403. schema: schema,
  4404. processKey: processKey,
  4405. toEvents: toEvents
  4406. };
  4407. return me;
  4408. };
  4409. var create$2 = function (cyclicField) {
  4410. var schema = [
  4411. option('onEscape'),
  4412. option('onEnter'),
  4413. defaulted$1('selector', '[data-alloy-tabstop="true"]'),
  4414. defaulted$1('firstTabstop', 0),
  4415. defaulted$1('useTabstopAt', constant(true)),
  4416. option('visibilitySelector')
  4417. ].concat([cyclicField]);
  4418. var isVisible = function (tabbingConfig, element) {
  4419. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  4420. return closest$2(element, sel);
  4421. }).getOr(element);
  4422. return get$5(target) > 0;
  4423. };
  4424. var findInitial = function (component, tabbingConfig) {
  4425. var tabstops = descendants(component.element(), tabbingConfig.selector);
  4426. var visibles = filter(tabstops, function (elem) {
  4427. return isVisible(tabbingConfig, elem);
  4428. });
  4429. return Option.from(visibles[tabbingConfig.firstTabstop]);
  4430. };
  4431. var findCurrent = function (component, tabbingConfig) {
  4432. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  4433. return closest$2(elem, tabbingConfig.selector);
  4434. });
  4435. };
  4436. var isTabstop = function (tabbingConfig, element) {
  4437. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  4438. };
  4439. var focusIn = function (component, tabbingConfig) {
  4440. findInitial(component, tabbingConfig).each(function (target) {
  4441. tabbingConfig.focusManager.set(component, target);
  4442. });
  4443. };
  4444. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  4445. return cycle(tabstops, stopIndex, function (elem) {
  4446. return isTabstop(tabbingConfig, elem);
  4447. }).fold(function () {
  4448. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  4449. }, function (target) {
  4450. tabbingConfig.focusManager.set(component, target);
  4451. return Option.some(true);
  4452. });
  4453. };
  4454. var go = function (component, simulatedEvent, tabbingConfig, cycle) {
  4455. var tabstops = descendants(component.element(), tabbingConfig.selector);
  4456. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  4457. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  4458. return optStopIndex.bind(function (stopIndex) {
  4459. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  4460. });
  4461. });
  4462. };
  4463. var goBackwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  4464. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  4465. return go(component, simulatedEvent, tabbingConfig, navigate);
  4466. };
  4467. var goForwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  4468. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  4469. return go(component, simulatedEvent, tabbingConfig, navigate);
  4470. };
  4471. var execute = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  4472. return tabbingConfig.onEnter.bind(function (f) {
  4473. return f(component, simulatedEvent);
  4474. });
  4475. };
  4476. var exit = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  4477. return tabbingConfig.onEscape.bind(function (f) {
  4478. return f(component, simulatedEvent);
  4479. });
  4480. };
  4481. var getKeydownRules = constant([
  4482. rule(and([
  4483. isShift,
  4484. inSet(TAB())
  4485. ]), goBackwards),
  4486. rule(inSet(TAB()), goForwards),
  4487. rule(inSet(ESCAPE()), exit),
  4488. rule(and([
  4489. isNotShift,
  4490. inSet(ENTER())
  4491. ]), execute)
  4492. ]);
  4493. var getKeyupRules = constant([]);
  4494. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  4495. return Option.some(focusIn);
  4496. });
  4497. };
  4498. var AcyclicType = create$2(state$1('cyclic', constant(false)));
  4499. var CyclicType = create$2(state$1('cyclic', constant(true)));
  4500. var inside = function (target) {
  4501. return name(target) === 'input' && get$1(target, 'type') !== 'radio' || name(target) === 'textarea';
  4502. };
  4503. var doDefaultExecute = function (component, simulatedEvent, focused) {
  4504. dispatch(component, focused, execute());
  4505. return Option.some(true);
  4506. };
  4507. var defaultExecute = function (component, simulatedEvent, focused) {
  4508. return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  4509. };
  4510. var stopEventForFirefox = function (component, simulatedEvent) {
  4511. return Option.some(true);
  4512. };
  4513. var schema$1 = [
  4514. defaulted$1('execute', defaultExecute),
  4515. defaulted$1('useSpace', false),
  4516. defaulted$1('useEnter', true),
  4517. defaulted$1('useControlEnter', false),
  4518. defaulted$1('useDown', false)
  4519. ];
  4520. var execute$1 = function (component, simulatedEvent, executeConfig) {
  4521. return executeConfig.execute(component, simulatedEvent, component.element());
  4522. };
  4523. var getKeydownRules = function (component, simulatedEvent, executeConfig, executeState) {
  4524. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  4525. var enterExec = executeConfig.useEnter ? ENTER() : [];
  4526. var downExec = executeConfig.useDown ? DOWN() : [];
  4527. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  4528. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  4529. isControl,
  4530. inSet(ENTER())
  4531. ]), execute$1)] : []);
  4532. };
  4533. var getKeyupRules = function (component, simulatedEvent, executeConfig, executeState) {
  4534. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  4535. };
  4536. var ExecutionType = typical(schema$1, NoState.init, getKeydownRules, getKeyupRules, function () {
  4537. return Option.none();
  4538. });
  4539. var flatgrid = function (spec) {
  4540. var dimensions = Cell(Option.none());
  4541. var setGridSize = function (numRows, numColumns) {
  4542. dimensions.set(Option.some({
  4543. numRows: constant(numRows),
  4544. numColumns: constant(numColumns)
  4545. }));
  4546. };
  4547. var getNumRows = function () {
  4548. return dimensions.get().map(function (d) {
  4549. return d.numRows();
  4550. });
  4551. };
  4552. var getNumColumns = function () {
  4553. return dimensions.get().map(function (d) {
  4554. return d.numColumns();
  4555. });
  4556. };
  4557. return nu$6({
  4558. readState: function () {
  4559. return dimensions.get().map(function (d) {
  4560. return {
  4561. numRows: d.numRows(),
  4562. numColumns: d.numColumns()
  4563. };
  4564. }).getOr({
  4565. numRows: '?',
  4566. numColumns: '?'
  4567. });
  4568. },
  4569. setGridSize: setGridSize,
  4570. getNumRows: getNumRows,
  4571. getNumColumns: getNumColumns
  4572. });
  4573. };
  4574. var init = function (spec) {
  4575. return spec.state(spec);
  4576. };
  4577. var KeyingState = /*#__PURE__*/Object.freeze({
  4578. flatgrid: flatgrid,
  4579. init: init
  4580. });
  4581. var onDirection = function (isLtr, isRtl) {
  4582. return function (element) {
  4583. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4584. };
  4585. };
  4586. var getDirection = function (element) {
  4587. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4588. };
  4589. var useH = function (movement) {
  4590. return function (component, simulatedEvent, config, state) {
  4591. var move = movement(component.element());
  4592. return use(move, component, simulatedEvent, config, state);
  4593. };
  4594. };
  4595. var west = function (moveLeft, moveRight) {
  4596. var movement = onDirection(moveLeft, moveRight);
  4597. return useH(movement);
  4598. };
  4599. var east = function (moveLeft, moveRight) {
  4600. var movement = onDirection(moveRight, moveLeft);
  4601. return useH(movement);
  4602. };
  4603. var useV = function (move) {
  4604. return function (component, simulatedEvent, config, state) {
  4605. return use(move, component, simulatedEvent, config, state);
  4606. };
  4607. };
  4608. var use = function (move, component, simulatedEvent, config, state) {
  4609. var outcome = config.focusManager.get(component).bind(function (focused) {
  4610. return move(component.element(), focused, config, state);
  4611. });
  4612. return outcome.map(function (newFocus) {
  4613. config.focusManager.set(component, newFocus);
  4614. return true;
  4615. });
  4616. };
  4617. var north = useV;
  4618. var south = useV;
  4619. var move = useV;
  4620. var isHidden = function (dom) {
  4621. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  4622. };
  4623. var isVisible = function (element) {
  4624. var dom = element.dom();
  4625. return !isHidden(dom);
  4626. };
  4627. var indexInfo = MixedBag([
  4628. 'index',
  4629. 'candidates'
  4630. ], []);
  4631. var locate = function (candidates, predicate) {
  4632. return findIndex(candidates, predicate).map(function (index) {
  4633. return indexInfo({
  4634. index: index,
  4635. candidates: candidates
  4636. });
  4637. });
  4638. };
  4639. var locateVisible = function (container, current, selector) {
  4640. var filter = isVisible;
  4641. return locateIn(container, current, selector, filter);
  4642. };
  4643. var locateIn = function (container, current, selector, filter$1) {
  4644. var predicate = curry(eq, current);
  4645. var candidates = descendants(container, selector);
  4646. var visible = filter(candidates, isVisible);
  4647. return locate(visible, predicate);
  4648. };
  4649. var findIndex$1 = function (elements, target) {
  4650. return findIndex(elements, function (elem) {
  4651. return eq(target, elem);
  4652. });
  4653. };
  4654. var withGrid = function (values, index, numCols, f) {
  4655. var oldRow = Math.floor(index / numCols);
  4656. var oldColumn = index % numCols;
  4657. return f(oldRow, oldColumn).bind(function (address) {
  4658. var newIndex = address.row() * numCols + address.column();
  4659. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  4660. });
  4661. };
  4662. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  4663. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  4664. var onLastRow = oldRow === numRows - 1;
  4665. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  4666. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  4667. return Option.some({
  4668. row: constant(oldRow),
  4669. column: constant(newColumn)
  4670. });
  4671. });
  4672. };
  4673. var cycleVertical = function (values, index, numRows, numCols, delta) {
  4674. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  4675. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  4676. var onLastRow = newRow === numRows - 1;
  4677. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  4678. var newCol = cap(oldColumn, 0, colsInRow - 1);
  4679. return Option.some({
  4680. row: constant(newRow),
  4681. column: constant(newCol)
  4682. });
  4683. });
  4684. };
  4685. var cycleRight = function (values, index, numRows, numCols) {
  4686. return cycleHorizontal(values, index, numRows, numCols, +1);
  4687. };
  4688. var cycleLeft = function (values, index, numRows, numCols) {
  4689. return cycleHorizontal(values, index, numRows, numCols, -1);
  4690. };
  4691. var cycleUp = function (values, index, numRows, numCols) {
  4692. return cycleVertical(values, index, numRows, numCols, -1);
  4693. };
  4694. var cycleDown = function (values, index, numRows, numCols) {
  4695. return cycleVertical(values, index, numRows, numCols, +1);
  4696. };
  4697. var schema$2 = [
  4698. strict$1('selector'),
  4699. defaulted$1('execute', defaultExecute),
  4700. onKeyboardHandler('onEscape'),
  4701. defaulted$1('captureTab', false),
  4702. initSize()
  4703. ];
  4704. var focusIn = function (component, gridConfig, gridState) {
  4705. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  4706. gridConfig.focusManager.set(component, first);
  4707. });
  4708. };
  4709. var findCurrent = function (component, gridConfig) {
  4710. return gridConfig.focusManager.get(component).bind(function (elem) {
  4711. return closest$2(elem, gridConfig.selector);
  4712. });
  4713. };
  4714. var execute$2 = function (component, simulatedEvent, gridConfig, gridState) {
  4715. return findCurrent(component, gridConfig).bind(function (focused) {
  4716. return gridConfig.execute(component, simulatedEvent, focused);
  4717. });
  4718. };
  4719. var doMove = function (cycle) {
  4720. return function (element, focused, gridConfig, gridState) {
  4721. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  4722. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  4723. });
  4724. };
  4725. };
  4726. var handleTab = function (component, simulatedEvent, gridConfig, gridState) {
  4727. return gridConfig.captureTab ? Option.some(true) : Option.none();
  4728. };
  4729. var doEscape = function (component, simulatedEvent, gridConfig, gridState) {
  4730. return gridConfig.onEscape(component, simulatedEvent);
  4731. };
  4732. var moveLeft = doMove(cycleLeft);
  4733. var moveRight = doMove(cycleRight);
  4734. var moveNorth = doMove(cycleUp);
  4735. var moveSouth = doMove(cycleDown);
  4736. var getKeydownRules$1 = constant([
  4737. rule(inSet(LEFT()), west(moveLeft, moveRight)),
  4738. rule(inSet(RIGHT()), east(moveLeft, moveRight)),
  4739. rule(inSet(UP()), north(moveNorth)),
  4740. rule(inSet(DOWN()), south(moveSouth)),
  4741. rule(and([
  4742. isShift,
  4743. inSet(TAB())
  4744. ]), handleTab),
  4745. rule(and([
  4746. isNotShift,
  4747. inSet(TAB())
  4748. ]), handleTab),
  4749. rule(inSet(ESCAPE()), doEscape),
  4750. rule(inSet(SPACE().concat(ENTER())), execute$2)
  4751. ]);
  4752. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4753. var FlatgridType = typical(schema$2, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  4754. return Option.some(focusIn);
  4755. });
  4756. var horizontal = function (container, selector, current, delta) {
  4757. var isDisabledButton = function (candidate) {
  4758. return name(candidate) === 'button' && get$1(candidate, 'disabled') === 'disabled';
  4759. };
  4760. var tryCycle = function (initial, index, candidates) {
  4761. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  4762. if (newIndex === initial) {
  4763. return Option.none();
  4764. } else {
  4765. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  4766. }
  4767. };
  4768. return locateVisible(container, current, selector).bind(function (identified) {
  4769. var index = identified.index();
  4770. var candidates = identified.candidates();
  4771. return tryCycle(index, index, candidates);
  4772. });
  4773. };
  4774. var schema$3 = [
  4775. strict$1('selector'),
  4776. defaulted$1('getInitial', Option.none),
  4777. defaulted$1('execute', defaultExecute),
  4778. onKeyboardHandler('onEscape'),
  4779. defaulted$1('executeOnMove', false),
  4780. defaulted$1('allowVertical', true)
  4781. ];
  4782. var findCurrent$1 = function (component, flowConfig) {
  4783. return flowConfig.focusManager.get(component).bind(function (elem) {
  4784. return closest$2(elem, flowConfig.selector);
  4785. });
  4786. };
  4787. var execute$3 = function (component, simulatedEvent, flowConfig) {
  4788. return findCurrent$1(component, flowConfig).bind(function (focused) {
  4789. return flowConfig.execute(component, simulatedEvent, focused);
  4790. });
  4791. };
  4792. var focusIn$1 = function (component, flowConfig) {
  4793. flowConfig.getInitial(component).orThunk(function () {
  4794. return descendant$1(component.element(), flowConfig.selector);
  4795. }).each(function (first) {
  4796. flowConfig.focusManager.set(component, first);
  4797. });
  4798. };
  4799. var moveLeft$1 = function (element, focused, info) {
  4800. return horizontal(element, info.selector, focused, -1);
  4801. };
  4802. var moveRight$1 = function (element, focused, info) {
  4803. return horizontal(element, info.selector, focused, +1);
  4804. };
  4805. var doMove$1 = function (movement) {
  4806. return function (component, simulatedEvent, flowConfig) {
  4807. return movement(component, simulatedEvent, flowConfig).bind(function () {
  4808. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  4809. });
  4810. };
  4811. };
  4812. var doEscape$1 = function (component, simulatedEvent, flowConfig, _flowState) {
  4813. return flowConfig.onEscape(component, simulatedEvent);
  4814. };
  4815. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  4816. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  4817. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  4818. return [
  4819. rule(inSet(westMovers), doMove$1(west(moveLeft$1, moveRight$1))),
  4820. rule(inSet(eastMovers), doMove$1(east(moveLeft$1, moveRight$1))),
  4821. rule(inSet(ENTER()), execute$3),
  4822. rule(inSet(SPACE()), execute$3),
  4823. rule(inSet(ESCAPE()), doEscape$1)
  4824. ];
  4825. };
  4826. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4827. var FlowType = typical(schema$3, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  4828. return Option.some(focusIn$1);
  4829. });
  4830. var outcome = MixedBag([
  4831. 'rowIndex',
  4832. 'columnIndex',
  4833. 'cell'
  4834. ], []);
  4835. var toCell = function (matrix, rowIndex, columnIndex) {
  4836. return Option.from(matrix[rowIndex]).bind(function (row) {
  4837. return Option.from(row[columnIndex]).map(function (cell) {
  4838. return outcome({
  4839. rowIndex: rowIndex,
  4840. columnIndex: columnIndex,
  4841. cell: cell
  4842. });
  4843. });
  4844. });
  4845. };
  4846. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  4847. var row = matrix[rowIndex];
  4848. var colsInRow = row.length;
  4849. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  4850. return toCell(matrix, rowIndex, newColIndex);
  4851. };
  4852. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  4853. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  4854. var colsInNextRow = matrix[nextRowIndex].length;
  4855. var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
  4856. return toCell(matrix, nextRowIndex, nextColIndex);
  4857. };
  4858. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4859. var row = matrix[rowIndex];
  4860. var colsInRow = row.length;
  4861. var newColIndex = cap(startCol + deltaCol, 0, colsInRow - 1);
  4862. return toCell(matrix, rowIndex, newColIndex);
  4863. };
  4864. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  4865. var nextRowIndex = cap(startRow + deltaRow, 0, matrix.length - 1);
  4866. var colsInNextRow = matrix[nextRowIndex].length;
  4867. var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
  4868. return toCell(matrix, nextRowIndex, nextColIndex);
  4869. };
  4870. var cycleRight$1 = function (matrix, startRow, startCol) {
  4871. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  4872. };
  4873. var cycleLeft$1 = function (matrix, startRow, startCol) {
  4874. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  4875. };
  4876. var cycleUp$1 = function (matrix, startRow, startCol) {
  4877. return cycleVertical$1(matrix, startCol, startRow, -1);
  4878. };
  4879. var cycleDown$1 = function (matrix, startRow, startCol) {
  4880. return cycleVertical$1(matrix, startCol, startRow, +1);
  4881. };
  4882. var moveLeft$2 = function (matrix, startRow, startCol) {
  4883. return moveHorizontal(matrix, startRow, startCol, -1);
  4884. };
  4885. var moveRight$2 = function (matrix, startRow, startCol) {
  4886. return moveHorizontal(matrix, startRow, startCol, +1);
  4887. };
  4888. var moveUp = function (matrix, startRow, startCol) {
  4889. return moveVertical(matrix, startCol, startRow, -1);
  4890. };
  4891. var moveDown = function (matrix, startRow, startCol) {
  4892. return moveVertical(matrix, startCol, startRow, +1);
  4893. };
  4894. var schema$4 = [
  4895. strictObjOf('selectors', [
  4896. strict$1('row'),
  4897. strict$1('cell')
  4898. ]),
  4899. defaulted$1('cycles', true),
  4900. defaulted$1('previousSelector', Option.none),
  4901. defaulted$1('execute', defaultExecute)
  4902. ];
  4903. var focusIn$2 = function (component, matrixConfig) {
  4904. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4905. var selectors = matrixConfig.selectors;
  4906. return descendant$1(component.element(), selectors.cell);
  4907. });
  4908. focused.each(function (cell) {
  4909. matrixConfig.focusManager.set(component, cell);
  4910. });
  4911. };
  4912. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  4913. return search(component.element()).bind(function (focused) {
  4914. return matrixConfig.execute(component, simulatedEvent, focused);
  4915. });
  4916. };
  4917. var toMatrix = function (rows, matrixConfig) {
  4918. return map$1(rows, function (row) {
  4919. return descendants(row, matrixConfig.selectors.cell);
  4920. });
  4921. };
  4922. var doMove$2 = function (ifCycle, ifMove) {
  4923. return function (element, focused, matrixConfig) {
  4924. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4925. return closest$2(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4926. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4927. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  4928. var allRows = descendants(element, matrixConfig.selectors.row);
  4929. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  4930. var matrix = toMatrix(allRows, matrixConfig);
  4931. return move(matrix, rowIndex, colIndex).map(function (next) {
  4932. return next.cell();
  4933. });
  4934. });
  4935. });
  4936. });
  4937. };
  4938. };
  4939. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  4940. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  4941. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  4942. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  4943. var getKeydownRules$3 = constant([
  4944. rule(inSet(LEFT()), west(moveLeft$3, moveRight$3)),
  4945. rule(inSet(RIGHT()), east(moveLeft$3, moveRight$3)),
  4946. rule(inSet(UP()), north(moveNorth$1)),
  4947. rule(inSet(DOWN()), south(moveSouth$1)),
  4948. rule(inSet(SPACE().concat(ENTER())), execute$4)
  4949. ]);
  4950. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4951. var MatrixType = typical(schema$4, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4952. return Option.some(focusIn$2);
  4953. });
  4954. var schema$5 = [
  4955. strict$1('selector'),
  4956. defaulted$1('execute', defaultExecute),
  4957. defaulted$1('moveOnTab', false)
  4958. ];
  4959. var execute$5 = function (component, simulatedEvent, menuConfig) {
  4960. return menuConfig.focusManager.get(component).bind(function (focused) {
  4961. return menuConfig.execute(component, simulatedEvent, focused);
  4962. });
  4963. };
  4964. var focusIn$3 = function (component, menuConfig) {
  4965. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  4966. menuConfig.focusManager.set(component, first);
  4967. });
  4968. };
  4969. var moveUp$1 = function (element, focused, info) {
  4970. return horizontal(element, info.selector, focused, -1);
  4971. };
  4972. var moveDown$1 = function (element, focused, info) {
  4973. return horizontal(element, info.selector, focused, +1);
  4974. };
  4975. var fireShiftTab = function (component, simulatedEvent, menuConfig) {
  4976. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig) : Option.none();
  4977. };
  4978. var fireTab = function (component, simulatedEvent, menuConfig) {
  4979. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig) : Option.none();
  4980. };
  4981. var getKeydownRules$4 = constant([
  4982. rule(inSet(UP()), move(moveUp$1)),
  4983. rule(inSet(DOWN()), move(moveDown$1)),
  4984. rule(and([
  4985. isShift,
  4986. inSet(TAB())
  4987. ]), fireShiftTab),
  4988. rule(and([
  4989. isNotShift,
  4990. inSet(TAB())
  4991. ]), fireTab),
  4992. rule(inSet(ENTER()), execute$5),
  4993. rule(inSet(SPACE()), execute$5)
  4994. ]);
  4995. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4996. var MenuType = typical(schema$5, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  4997. return Option.some(focusIn$3);
  4998. });
  4999. var schema$6 = [
  5000. onKeyboardHandler('onSpace'),
  5001. onKeyboardHandler('onEnter'),
  5002. onKeyboardHandler('onShiftEnter'),
  5003. onKeyboardHandler('onLeft'),
  5004. onKeyboardHandler('onRight'),
  5005. onKeyboardHandler('onTab'),
  5006. onKeyboardHandler('onShiftTab'),
  5007. onKeyboardHandler('onUp'),
  5008. onKeyboardHandler('onDown'),
  5009. onKeyboardHandler('onEscape'),
  5010. defaulted$1('stopSpaceKeyup', false),
  5011. option('focusIn')
  5012. ];
  5013. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  5014. return [
  5015. rule(inSet(SPACE()), specialInfo.onSpace),
  5016. rule(and([
  5017. isNotShift,
  5018. inSet(ENTER())
  5019. ]), specialInfo.onEnter),
  5020. rule(and([
  5021. isShift,
  5022. inSet(ENTER())
  5023. ]), specialInfo.onShiftEnter),
  5024. rule(and([
  5025. isShift,
  5026. inSet(TAB())
  5027. ]), specialInfo.onShiftTab),
  5028. rule(and([
  5029. isNotShift,
  5030. inSet(TAB())
  5031. ]), specialInfo.onTab),
  5032. rule(inSet(UP()), specialInfo.onUp),
  5033. rule(inSet(DOWN()), specialInfo.onDown),
  5034. rule(inSet(LEFT()), specialInfo.onLeft),
  5035. rule(inSet(RIGHT()), specialInfo.onRight),
  5036. rule(inSet(SPACE()), specialInfo.onSpace),
  5037. rule(inSet(ESCAPE()), specialInfo.onEscape)
  5038. ];
  5039. };
  5040. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  5041. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  5042. };
  5043. var SpecialType = typical(schema$6, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  5044. return specialInfo.focusIn;
  5045. });
  5046. var acyclic = AcyclicType.schema();
  5047. var cyclic = CyclicType.schema();
  5048. var flow = FlowType.schema();
  5049. var flatgrid$1 = FlatgridType.schema();
  5050. var matrix = MatrixType.schema();
  5051. var execution = ExecutionType.schema();
  5052. var menu = MenuType.schema();
  5053. var special = SpecialType.schema();
  5054. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  5055. acyclic: acyclic,
  5056. cyclic: cyclic,
  5057. flow: flow,
  5058. flatgrid: flatgrid$1,
  5059. matrix: matrix,
  5060. execution: execution,
  5061. menu: menu,
  5062. special: special
  5063. });
  5064. var Keying = createModes$1({
  5065. branchKey: 'mode',
  5066. branches: KeyboardBranches,
  5067. name: 'keying',
  5068. active: {
  5069. events: function (keyingConfig, keyingState) {
  5070. var handler = keyingConfig.handler;
  5071. return handler.toEvents(keyingConfig, keyingState);
  5072. }
  5073. },
  5074. apis: {
  5075. focusIn: function (component, keyConfig, keyState) {
  5076. keyConfig.sendFocusIn(keyConfig).fold(function () {
  5077. component.getSystem().triggerFocus(component.element(), component.element());
  5078. }, function (sendFocusIn) {
  5079. sendFocusIn(component, keyConfig, keyState);
  5080. });
  5081. },
  5082. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  5083. if (!hasKey$1(keyState, 'setGridSize')) {
  5084. domGlobals.console.error('Layout does not support setGridSize');
  5085. } else {
  5086. keyState.setGridSize(numRows, numColumns);
  5087. }
  5088. }
  5089. },
  5090. state: KeyingState
  5091. });
  5092. var field$1 = function (name, forbidden) {
  5093. return defaultedObjOf(name, {}, map$1(forbidden, function (f) {
  5094. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  5095. }).concat([state$1('dump', identity)]));
  5096. };
  5097. var get$6 = function (data) {
  5098. return data.dump;
  5099. };
  5100. var augment = function (data, original) {
  5101. return __assign({}, data.dump, derive$1(original));
  5102. };
  5103. var SketchBehaviours = {
  5104. field: field$1,
  5105. augment: augment,
  5106. get: get$6
  5107. };
  5108. var SketchBehaviours$1 = /*#__PURE__*/Object.freeze({
  5109. SketchBehaviours: SketchBehaviours,
  5110. field: field$1,
  5111. get: get$6,
  5112. augment: augment
  5113. });
  5114. var _placeholder = 'placeholder';
  5115. var adt$2 = Adt.generate([
  5116. {
  5117. single: [
  5118. 'required',
  5119. 'valueThunk'
  5120. ]
  5121. },
  5122. {
  5123. multiple: [
  5124. 'required',
  5125. 'valueThunks'
  5126. ]
  5127. }
  5128. ]);
  5129. var isSubstitute = function (uiType) {
  5130. return contains([_placeholder], uiType);
  5131. };
  5132. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  5133. if (owner.exists(function (o) {
  5134. return o !== compSpec.owner;
  5135. })) {
  5136. return adt$2.single(true, constant(compSpec));
  5137. }
  5138. return readOptFrom$1(placeholders, compSpec.name).fold(function () {
  5139. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + Json.stringify(compSpec, null, 2));
  5140. }, function (newSpec) {
  5141. return newSpec.replace();
  5142. });
  5143. };
  5144. var scan = function (owner, detail, compSpec, placeholders) {
  5145. if (compSpec.uiType === _placeholder) {
  5146. return subPlaceholder(owner, detail, compSpec, placeholders);
  5147. } else {
  5148. return adt$2.single(false, constant(compSpec));
  5149. }
  5150. };
  5151. var substitute = function (owner, detail, compSpec, placeholders) {
  5152. var base = scan(owner, detail, compSpec, placeholders);
  5153. return base.fold(function (req, valueThunk) {
  5154. var value = valueThunk(detail, compSpec.config, compSpec.validated);
  5155. var childSpecs = readOptFrom$1(value, 'components').getOr([]);
  5156. var substituted = bind(childSpecs, function (c) {
  5157. return substitute(owner, detail, c, placeholders);
  5158. });
  5159. return [__assign({}, value, { components: substituted })];
  5160. }, function (req, valuesThunk) {
  5161. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  5162. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  5163. return preprocessor(values);
  5164. });
  5165. };
  5166. var substituteAll = function (owner, detail, components, placeholders) {
  5167. return bind(components, function (c) {
  5168. return substitute(owner, detail, c, placeholders);
  5169. });
  5170. };
  5171. var oneReplace = function (label, replacements) {
  5172. var called = false;
  5173. var used = function () {
  5174. return called;
  5175. };
  5176. var replace = function () {
  5177. if (called === true) {
  5178. throw new Error('Trying to use the same placeholder more than once: ' + label);
  5179. }
  5180. called = true;
  5181. return replacements;
  5182. };
  5183. var required = function () {
  5184. return replacements.fold(function (req, _) {
  5185. return req;
  5186. }, function (req, _) {
  5187. return req;
  5188. });
  5189. };
  5190. return {
  5191. name: constant(label),
  5192. required: required,
  5193. used: used,
  5194. replace: replace
  5195. };
  5196. };
  5197. var substitutePlaces = function (owner, detail, components, placeholders) {
  5198. var ps = map(placeholders, function (ph, name) {
  5199. return oneReplace(name, ph);
  5200. });
  5201. var outcome = substituteAll(owner, detail, components, ps);
  5202. each(ps, function (p) {
  5203. if (p.used() === false && p.required()) {
  5204. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + Json.stringify(detail.components, null, 2));
  5205. }
  5206. });
  5207. return outcome;
  5208. };
  5209. var singleReplace = function (detail, p) {
  5210. var replacement = p;
  5211. return replacement.fold(function (req, valueThunk) {
  5212. return [valueThunk(detail)];
  5213. }, function (req, valuesThunk) {
  5214. return valuesThunk(detail);
  5215. });
  5216. };
  5217. var single = adt$2.single;
  5218. var multiple = adt$2.multiple;
  5219. var placeholder = constant(_placeholder);
  5220. var UiSubstitutes = /*#__PURE__*/Object.freeze({
  5221. single: single,
  5222. multiple: multiple,
  5223. isSubstitute: isSubstitute,
  5224. placeholder: placeholder,
  5225. substituteAll: substituteAll,
  5226. substitutePlaces: substitutePlaces,
  5227. singleReplace: singleReplace
  5228. });
  5229. var unique = 0;
  5230. var generate$1 = function (prefix) {
  5231. var date = new Date();
  5232. var time = date.getTime();
  5233. var random = Math.floor(Math.random() * 1000000000);
  5234. unique++;
  5235. return prefix + '_' + random + unique + String(time);
  5236. };
  5237. var adt$3 = Adt.generate([
  5238. { required: ['data'] },
  5239. { external: ['data'] },
  5240. { optional: ['data'] },
  5241. { group: ['data'] }
  5242. ]);
  5243. var fFactory = defaulted$1('factory', { sketch: identity });
  5244. var fSchema = defaulted$1('schema', []);
  5245. var fName = strict$1('name');
  5246. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  5247. return '<alloy.' + generate$1(typeSpec.name) + '>';
  5248. }), anyValue$1());
  5249. var fGroupSchema = state$1('schema', function () {
  5250. return [option('preprocess')];
  5251. });
  5252. var fDefaults = defaulted$1('defaults', constant({}));
  5253. var fOverrides = defaulted$1('overrides', constant({}));
  5254. var requiredSpec = objOf([
  5255. fFactory,
  5256. fSchema,
  5257. fName,
  5258. fPname,
  5259. fDefaults,
  5260. fOverrides
  5261. ]);
  5262. var optionalSpec = objOf([
  5263. fFactory,
  5264. fSchema,
  5265. fName,
  5266. fPname,
  5267. fDefaults,
  5268. fOverrides
  5269. ]);
  5270. var groupSpec = objOf([
  5271. fFactory,
  5272. fGroupSchema,
  5273. fName,
  5274. strict$1('unit'),
  5275. fPname,
  5276. fDefaults,
  5277. fOverrides
  5278. ]);
  5279. var asNamedPart = function (part) {
  5280. return part.fold(Option.some, Option.none, Option.some, Option.some);
  5281. };
  5282. var name$1 = function (part) {
  5283. var get = function (data) {
  5284. return data.name;
  5285. };
  5286. return part.fold(get, get, get, get);
  5287. };
  5288. var convert = function (adtConstructor, partSchema) {
  5289. return function (spec) {
  5290. var data = asRawOrDie('Converting part type', partSchema, spec);
  5291. return adtConstructor(data);
  5292. };
  5293. };
  5294. var required = convert(adt$3.required, requiredSpec);
  5295. var optional = convert(adt$3.optional, optionalSpec);
  5296. var group = convert(adt$3.group, groupSpec);
  5297. var original = constant('entirety');
  5298. var combine = function (detail, data, partSpec, partValidated) {
  5299. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  5300. };
  5301. var subs = function (owner, detail, parts) {
  5302. var internals = {};
  5303. var externals = {};
  5304. each$1(parts, function (part) {
  5305. part.fold(function (data) {
  5306. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  5307. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  5308. });
  5309. }, function (data) {
  5310. var partSpec = detail.parts[data.name];
  5311. externals[data.name] = constant(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  5312. }, function (data) {
  5313. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  5314. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  5315. });
  5316. }, function (data) {
  5317. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  5318. var units = detail[data.name];
  5319. return map$1(units, function (u) {
  5320. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  5321. });
  5322. });
  5323. });
  5324. });
  5325. return {
  5326. internals: constant(internals),
  5327. externals: constant(externals)
  5328. };
  5329. };
  5330. var generate$2 = function (owner, parts) {
  5331. var r = {};
  5332. each$1(parts, function (part) {
  5333. asNamedPart(part).each(function (np) {
  5334. var g = doGenerateOne(owner, np.pname);
  5335. r[np.name] = function (config) {
  5336. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  5337. return __assign({}, g, {
  5338. config: config,
  5339. validated: validated
  5340. });
  5341. };
  5342. });
  5343. });
  5344. return r;
  5345. };
  5346. var doGenerateOne = function (owner, pname) {
  5347. return {
  5348. uiType: placeholder(),
  5349. owner: owner,
  5350. name: pname
  5351. };
  5352. };
  5353. var generateOne = function (owner, pname, config) {
  5354. return {
  5355. uiType: placeholder(),
  5356. owner: owner,
  5357. name: pname,
  5358. config: config,
  5359. validated: {}
  5360. };
  5361. };
  5362. var schemas = function (parts) {
  5363. return bind(parts, function (part) {
  5364. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  5365. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  5366. }).toArray();
  5367. });
  5368. };
  5369. var names = function (parts) {
  5370. return map$1(parts, name$1);
  5371. };
  5372. var substitutes = function (owner, detail, parts) {
  5373. return subs(owner, detail, parts);
  5374. };
  5375. var components = function (owner, detail, internals) {
  5376. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  5377. };
  5378. var getPart = function (component, detail, partKey) {
  5379. var uid = detail.partUids[partKey];
  5380. return component.getSystem().getByUid(uid).toOption();
  5381. };
  5382. var getPartOrDie = function (component, detail, partKey) {
  5383. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  5384. };
  5385. var getParts = function (component, detail, partKeys) {
  5386. var r = {};
  5387. var uids = detail.partUids;
  5388. var system = component.getSystem();
  5389. each$1(partKeys, function (pk) {
  5390. r[pk] = system.getByUid(uids[pk]);
  5391. });
  5392. return map(r, constant);
  5393. };
  5394. var getAllParts = function (component, detail) {
  5395. var system = component.getSystem();
  5396. return map(detail.partUids, function (pUid, k) {
  5397. return constant(system.getByUid(pUid));
  5398. });
  5399. };
  5400. var getAllPartNames = function (detail) {
  5401. return keys(detail.partUids);
  5402. };
  5403. var getPartsOrDie = function (component, detail, partKeys) {
  5404. var r = {};
  5405. var uids = detail.partUids;
  5406. var system = component.getSystem();
  5407. each$1(partKeys, function (pk) {
  5408. r[pk] = system.getByUid(uids[pk]).getOrDie();
  5409. });
  5410. return map(r, constant);
  5411. };
  5412. var defaultUids = function (baseUid, partTypes) {
  5413. var partNames = names(partTypes);
  5414. return wrapAll$1(map$1(partNames, function (pn) {
  5415. return {
  5416. key: pn,
  5417. value: baseUid + '-' + pn
  5418. };
  5419. }));
  5420. };
  5421. var defaultUidsSchema = function (partTypes) {
  5422. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  5423. return defaultUids(spec.uid, partTypes);
  5424. }), anyValue$1());
  5425. };
  5426. var AlloyParts = /*#__PURE__*/Object.freeze({
  5427. generate: generate$2,
  5428. generateOne: generateOne,
  5429. schemas: schemas,
  5430. names: names,
  5431. substitutes: substitutes,
  5432. components: components,
  5433. defaultUids: defaultUids,
  5434. defaultUidsSchema: defaultUidsSchema,
  5435. getAllParts: getAllParts,
  5436. getAllPartNames: getAllPartNames,
  5437. getPart: getPart,
  5438. getPartOrDie: getPartOrDie,
  5439. getParts: getParts,
  5440. getPartsOrDie: getPartsOrDie
  5441. });
  5442. var premadeTag = generate$1('alloy-premade');
  5443. var premade = function (comp) {
  5444. return wrap$1(premadeTag, comp);
  5445. };
  5446. var getPremade = function (spec) {
  5447. return readOptFrom$1(spec, premadeTag);
  5448. };
  5449. var makeApi = function (f) {
  5450. return markAsSketchApi(function (component) {
  5451. var rest = [];
  5452. for (var _i = 1; _i < arguments.length; _i++) {
  5453. rest[_i - 1] = arguments[_i];
  5454. }
  5455. return f.apply(undefined, [component.getApis()].concat([component].concat(rest)));
  5456. }, f);
  5457. };
  5458. var GuiTypes = /*#__PURE__*/Object.freeze({
  5459. makeApi: makeApi,
  5460. premade: premade,
  5461. getPremade: getPremade
  5462. });
  5463. var prefix$1 = constant('alloy-id-');
  5464. var idAttr = constant('data-alloy-id');
  5465. var prefix$2 = prefix$1();
  5466. var idAttr$1 = idAttr();
  5467. var write = function (label, elem) {
  5468. var id = generate$1(prefix$2 + label);
  5469. writeOnly(elem, id);
  5470. return id;
  5471. };
  5472. var writeOnly = function (elem, uid) {
  5473. Object.defineProperty(elem.dom(), idAttr$1, {
  5474. value: uid,
  5475. writable: true
  5476. });
  5477. };
  5478. var read$2 = function (elem) {
  5479. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  5480. return Option.from(id);
  5481. };
  5482. var generate$3 = function (prefix) {
  5483. return generate$1(prefix);
  5484. };
  5485. var base = function (label, partSchemas, partUidsSchemas, spec) {
  5486. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  5487. return ps.concat([
  5488. strict$1('uid'),
  5489. defaulted$1('dom', {}),
  5490. defaulted$1('components', []),
  5491. snapshot('originalSpec'),
  5492. defaulted$1('debug.sketcher', {})
  5493. ]).concat(partUidsSchemas);
  5494. };
  5495. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  5496. var baseS = base(label, partSchemas, partUidsSchemas, spec);
  5497. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  5498. };
  5499. var single$1 = function (owner, schema, factory, spec) {
  5500. var specWithUid = supplyUid(spec);
  5501. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  5502. return factory(detail, specWithUid);
  5503. };
  5504. var composite = function (owner, schema, partTypes, factory, spec) {
  5505. var specWithUid = supplyUid(spec);
  5506. var partSchemas = schemas(partTypes);
  5507. var partUidsSchema = defaultUidsSchema(partTypes);
  5508. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  5509. var subs = substitutes(owner, detail, partTypes);
  5510. var components$1 = components(owner, detail, subs.internals());
  5511. return factory(detail, components$1, specWithUid, subs.externals());
  5512. };
  5513. var supplyUid = function (spec) {
  5514. return spec.hasOwnProperty('uid') ? spec : __assign({}, spec, { uid: generate$3('uid') });
  5515. };
  5516. function isSketchSpec(spec) {
  5517. return spec.uid !== undefined;
  5518. }
  5519. var singleSchema = objOfOnly([
  5520. strict$1('name'),
  5521. strict$1('factory'),
  5522. strict$1('configFields'),
  5523. defaulted$1('apis', {}),
  5524. defaulted$1('extraApis', {})
  5525. ]);
  5526. var compositeSchema = objOfOnly([
  5527. strict$1('name'),
  5528. strict$1('factory'),
  5529. strict$1('configFields'),
  5530. strict$1('partFields'),
  5531. defaulted$1('apis', {}),
  5532. defaulted$1('extraApis', {})
  5533. ]);
  5534. var single$2 = function (rawConfig) {
  5535. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  5536. var sketch = function (spec) {
  5537. return single$1(config.name, config.configFields, config.factory, spec);
  5538. };
  5539. var apis = map(config.apis, makeApi);
  5540. var extraApis = map(config.extraApis, function (f, k) {
  5541. return markAsExtraApi(f, k);
  5542. });
  5543. return __assign({
  5544. name: constant(config.name),
  5545. partFields: constant([]),
  5546. configFields: constant(config.configFields),
  5547. sketch: sketch
  5548. }, apis, extraApis);
  5549. };
  5550. var composite$1 = function (rawConfig) {
  5551. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  5552. var sketch = function (spec) {
  5553. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  5554. };
  5555. var parts = generate$2(config.name, config.partFields);
  5556. var apis = map(config.apis, makeApi);
  5557. var extraApis = map(config.extraApis, function (f, k) {
  5558. return markAsExtraApi(f, k);
  5559. });
  5560. return __assign({
  5561. name: constant(config.name),
  5562. partFields: constant(config.partFields),
  5563. configFields: constant(config.configFields),
  5564. sketch: sketch,
  5565. parts: constant(parts)
  5566. }, apis, extraApis);
  5567. };
  5568. var factory = function (detail) {
  5569. var events = events$2(detail.action);
  5570. var tag = detail.dom.tag;
  5571. var lookupAttr = function (attr) {
  5572. return readOptFrom$1(detail.dom, 'attributes').bind(function (attrs) {
  5573. return readOptFrom$1(attrs, attr);
  5574. });
  5575. };
  5576. var getModAttributes = function () {
  5577. if (tag === 'button') {
  5578. var type = lookupAttr('type').getOr('button');
  5579. var roleAttrs = lookupAttr('role').map(function (role) {
  5580. return { role: role };
  5581. }).getOr({});
  5582. return __assign({ type: type }, roleAttrs);
  5583. } else {
  5584. var role = lookupAttr('role').getOr('button');
  5585. return { role: role };
  5586. }
  5587. };
  5588. return {
  5589. uid: detail.uid,
  5590. dom: detail.dom,
  5591. components: detail.components,
  5592. events: events,
  5593. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  5594. Focusing.config({}),
  5595. Keying.config({
  5596. mode: 'execution',
  5597. useSpace: true,
  5598. useEnter: true
  5599. })
  5600. ]),
  5601. domModification: { attributes: getModAttributes() },
  5602. eventOrder: detail.eventOrder
  5603. };
  5604. };
  5605. var Button = single$2({
  5606. name: 'Button',
  5607. factory: factory,
  5608. configFields: [
  5609. defaulted$1('uid', undefined),
  5610. strict$1('dom'),
  5611. defaulted$1('components', []),
  5612. SketchBehaviours.field('buttonBehaviours', [
  5613. Focusing,
  5614. Keying
  5615. ]),
  5616. option('action'),
  5617. option('role'),
  5618. defaulted$1('eventOrder', {})
  5619. ]
  5620. });
  5621. var exhibit$2 = function (base, unselectConfig) {
  5622. return nu$5({
  5623. styles: {
  5624. '-webkit-user-select': 'none',
  5625. 'user-select': 'none',
  5626. '-ms-user-select': 'none',
  5627. '-moz-user-select': '-moz-none'
  5628. },
  5629. attributes: { unselectable: 'on' }
  5630. });
  5631. };
  5632. var events$4 = function (unselectConfig) {
  5633. return derive([abort(selectstart(), constant(true))]);
  5634. };
  5635. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  5636. events: events$4,
  5637. exhibit: exhibit$2
  5638. });
  5639. var Unselecting = create$1({
  5640. fields: [],
  5641. name: 'unselecting',
  5642. active: ActiveUnselecting
  5643. });
  5644. var getAttrs = function (elem) {
  5645. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  5646. return foldl(attributes, function (b, attr) {
  5647. var _a;
  5648. if (attr.name === 'class') {
  5649. return b;
  5650. } else {
  5651. return __assign({}, b, (_a = {}, _a[attr.name] = attr.value, _a));
  5652. }
  5653. }, {});
  5654. };
  5655. var getClasses = function (elem) {
  5656. return Array.prototype.slice.call(elem.dom().classList, 0);
  5657. };
  5658. var fromHtml$2 = function (html) {
  5659. var elem = Element.fromHtml(html);
  5660. var children$1 = children(elem);
  5661. var attrs = getAttrs(elem);
  5662. var classes = getClasses(elem);
  5663. var contents = children$1.length === 0 ? {} : { innerHtml: get$3(elem) };
  5664. return __assign({
  5665. tag: name(elem),
  5666. classes: classes,
  5667. attributes: attrs
  5668. }, contents);
  5669. };
  5670. var dom$1 = function (rawHtml) {
  5671. var html = supplant(rawHtml, { prefix: Styles.prefix() });
  5672. return fromHtml$2(html);
  5673. };
  5674. var spec = function (rawHtml) {
  5675. var sDom = dom$1(rawHtml);
  5676. return { dom: sDom };
  5677. };
  5678. var forToolbarCommand = function (editor, command) {
  5679. return forToolbar(command, function () {
  5680. editor.execCommand(command);
  5681. }, {}, editor);
  5682. };
  5683. var getToggleBehaviours = function (command) {
  5684. return derive$1([
  5685. Toggling.config({
  5686. toggleClass: Styles.resolve('toolbar-button-selected'),
  5687. toggleOnExecute: false,
  5688. aria: { mode: 'pressed' }
  5689. }),
  5690. Receivers.format(command, function (button, status) {
  5691. var toggle = status ? Toggling.on : Toggling.off;
  5692. toggle(button);
  5693. })
  5694. ]);
  5695. };
  5696. var forToolbarStateCommand = function (editor, command) {
  5697. var extraBehaviours = getToggleBehaviours(command);
  5698. return forToolbar(command, function () {
  5699. editor.execCommand(command);
  5700. }, extraBehaviours, editor);
  5701. };
  5702. var forToolbarStateAction = function (editor, clazz, command, action) {
  5703. var extraBehaviours = getToggleBehaviours(command);
  5704. return forToolbar(clazz, action, extraBehaviours, editor);
  5705. };
  5706. var getToolbarIconButton = function (clazz, editor) {
  5707. var icons = editor.ui.registry.getAll().icons;
  5708. var optOxideIcon = Option.from(icons[clazz]);
  5709. return optOxideIcon.fold(function () {
  5710. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  5711. }, function (icon) {
  5712. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  5713. });
  5714. };
  5715. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  5716. return Button.sketch({
  5717. dom: getToolbarIconButton(clazz, editor),
  5718. action: action,
  5719. buttonBehaviours: deepMerge(derive$1([Unselecting.config({})]), extraBehaviours)
  5720. });
  5721. };
  5722. var Buttons = {
  5723. forToolbar: forToolbar,
  5724. forToolbarCommand: forToolbarCommand,
  5725. forToolbarStateAction: forToolbarStateAction,
  5726. forToolbarStateCommand: forToolbarStateCommand,
  5727. getToolbarIconButton: getToolbarIconButton
  5728. };
  5729. var platform = PlatformDetection$1.detect();
  5730. var isTouch = platform.deviceType.isTouch();
  5731. var labelPart = optional({
  5732. schema: [strict$1('dom')],
  5733. name: 'label'
  5734. });
  5735. var edgePart = function (name) {
  5736. return optional({
  5737. name: '' + name + '-edge',
  5738. overrides: function (detail) {
  5739. var action = detail.model.manager.edgeActions[name];
  5740. return action.fold(function () {
  5741. return {};
  5742. }, function (a) {
  5743. var touchEvents = derive([runActionExtra(touchstart(), a, [detail])]);
  5744. var mouseEvents = derive([
  5745. runActionExtra(mousedown(), a, [detail]),
  5746. runActionExtra(mousemove(), function (l, det) {
  5747. if (det.mouseIsDown.get()) {
  5748. a(l, det);
  5749. }
  5750. }, [detail])
  5751. ]);
  5752. return { events: isTouch ? touchEvents : mouseEvents };
  5753. });
  5754. }
  5755. });
  5756. };
  5757. var tlEdgePart = edgePart('top-left');
  5758. var tedgePart = edgePart('top');
  5759. var trEdgePart = edgePart('top-right');
  5760. var redgePart = edgePart('right');
  5761. var brEdgePart = edgePart('bottom-right');
  5762. var bedgePart = edgePart('bottom');
  5763. var blEdgePart = edgePart('bottom-left');
  5764. var ledgePart = edgePart('left');
  5765. var thumbPart = required({
  5766. name: 'thumb',
  5767. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  5768. overrides: function (detail) {
  5769. return {
  5770. events: derive([
  5771. redirectToPart(touchstart(), detail, 'spectrum'),
  5772. redirectToPart(touchmove(), detail, 'spectrum'),
  5773. redirectToPart(touchend(), detail, 'spectrum'),
  5774. redirectToPart(mousedown(), detail, 'spectrum'),
  5775. redirectToPart(mousemove(), detail, 'spectrum'),
  5776. redirectToPart(mouseup(), detail, 'spectrum')
  5777. ])
  5778. };
  5779. }
  5780. });
  5781. var spectrumPart = required({
  5782. schema: [state$1('mouseIsDown', function () {
  5783. return Cell(false);
  5784. })],
  5785. name: 'spectrum',
  5786. overrides: function (detail) {
  5787. var modelDetail = detail.model;
  5788. var model = modelDetail.manager;
  5789. var setValueFrom = function (component, simulatedEvent) {
  5790. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  5791. return model.setValueFrom(component, detail, value);
  5792. });
  5793. };
  5794. var touchEvents = derive([
  5795. run(touchstart(), setValueFrom),
  5796. run(touchmove(), setValueFrom)
  5797. ]);
  5798. var mouseEvents = derive([
  5799. run(mousedown(), setValueFrom),
  5800. run(mousemove(), function (spectrum, se) {
  5801. if (detail.mouseIsDown.get()) {
  5802. setValueFrom(spectrum, se);
  5803. }
  5804. })
  5805. ]);
  5806. return {
  5807. behaviours: derive$1(isTouch ? [] : [
  5808. Keying.config({
  5809. mode: 'special',
  5810. onLeft: function (spectrum) {
  5811. return model.onLeft(spectrum, detail);
  5812. },
  5813. onRight: function (spectrum) {
  5814. return model.onRight(spectrum, detail);
  5815. },
  5816. onUp: function (spectrum) {
  5817. return model.onUp(spectrum, detail);
  5818. },
  5819. onDown: function (spectrum) {
  5820. return model.onDown(spectrum, detail);
  5821. }
  5822. }),
  5823. Focusing.config({})
  5824. ]),
  5825. events: isTouch ? touchEvents : mouseEvents
  5826. };
  5827. }
  5828. });
  5829. var SliderParts = [
  5830. labelPart,
  5831. ledgePart,
  5832. redgePart,
  5833. tedgePart,
  5834. bedgePart,
  5835. tlEdgePart,
  5836. trEdgePart,
  5837. blEdgePart,
  5838. brEdgePart,
  5839. thumbPart,
  5840. spectrumPart
  5841. ];
  5842. var onLoad$1 = function (component, repConfig, repState) {
  5843. repConfig.store.manager.onLoad(component, repConfig, repState);
  5844. };
  5845. var onUnload = function (component, repConfig, repState) {
  5846. repConfig.store.manager.onUnload(component, repConfig, repState);
  5847. };
  5848. var setValue = function (component, repConfig, repState, data) {
  5849. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5850. };
  5851. var getValue = function (component, repConfig, repState) {
  5852. return repConfig.store.manager.getValue(component, repConfig, repState);
  5853. };
  5854. var getState = function (component, repConfig, repState) {
  5855. return repState;
  5856. };
  5857. var RepresentApis = /*#__PURE__*/Object.freeze({
  5858. onLoad: onLoad$1,
  5859. onUnload: onUnload,
  5860. setValue: setValue,
  5861. getValue: getValue,
  5862. getState: getState
  5863. });
  5864. var events$5 = function (repConfig, repState) {
  5865. var es = repConfig.resetOnDom ? [
  5866. runOnAttached(function (comp, se) {
  5867. onLoad$1(comp, repConfig, repState);
  5868. }),
  5869. runOnDetached(function (comp, se) {
  5870. onUnload(comp, repConfig, repState);
  5871. })
  5872. ] : [loadEvent(repConfig, repState, onLoad$1)];
  5873. return derive(es);
  5874. };
  5875. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5876. events: events$5
  5877. });
  5878. var memory = function () {
  5879. var data = Cell(null);
  5880. var readState = function () {
  5881. return {
  5882. mode: 'memory',
  5883. value: data.get()
  5884. };
  5885. };
  5886. var isNotSet = function () {
  5887. return data.get() === null;
  5888. };
  5889. var clear = function () {
  5890. data.set(null);
  5891. };
  5892. return nu$6({
  5893. set: data.set,
  5894. get: data.get,
  5895. isNotSet: isNotSet,
  5896. clear: clear,
  5897. readState: readState
  5898. });
  5899. };
  5900. var manual = function () {
  5901. var readState = function () {
  5902. };
  5903. return nu$6({ readState: readState });
  5904. };
  5905. var dataset = function () {
  5906. var dataByValue = Cell({});
  5907. var dataByText = Cell({});
  5908. var readState = function () {
  5909. return {
  5910. mode: 'dataset',
  5911. dataByValue: dataByValue.get(),
  5912. dataByText: dataByText.get()
  5913. };
  5914. };
  5915. var clear = function () {
  5916. dataByValue.set({});
  5917. dataByText.set({});
  5918. };
  5919. var lookup = function (itemString) {
  5920. return readOptFrom$1(dataByValue.get(), itemString).orThunk(function () {
  5921. return readOptFrom$1(dataByText.get(), itemString);
  5922. });
  5923. };
  5924. var update = function (items) {
  5925. var currentDataByValue = dataByValue.get();
  5926. var currentDataByText = dataByText.get();
  5927. var newDataByValue = {};
  5928. var newDataByText = {};
  5929. each$1(items, function (item) {
  5930. newDataByValue[item.value] = item;
  5931. readOptFrom$1(item, 'meta').each(function (meta) {
  5932. readOptFrom$1(meta, 'text').each(function (text) {
  5933. newDataByText[text] = item;
  5934. });
  5935. });
  5936. });
  5937. dataByValue.set(__assign({}, currentDataByValue, newDataByValue));
  5938. dataByText.set(__assign({}, currentDataByText, newDataByText));
  5939. };
  5940. return nu$6({
  5941. readState: readState,
  5942. lookup: lookup,
  5943. update: update,
  5944. clear: clear
  5945. });
  5946. };
  5947. var init$1 = function (spec) {
  5948. return spec.store.manager.state(spec);
  5949. };
  5950. var RepresentState = /*#__PURE__*/Object.freeze({
  5951. memory: memory,
  5952. dataset: dataset,
  5953. manual: manual,
  5954. init: init$1
  5955. });
  5956. var setValue$1 = function (component, repConfig, repState, data) {
  5957. var store = repConfig.store;
  5958. repState.update([data]);
  5959. store.setValue(component, data);
  5960. repConfig.onSetValue(component, data);
  5961. };
  5962. var getValue$1 = function (component, repConfig, repState) {
  5963. var store = repConfig.store;
  5964. var key = store.getDataKey(component);
  5965. return repState.lookup(key).fold(function () {
  5966. return store.getFallbackEntry(key);
  5967. }, function (data) {
  5968. return data;
  5969. });
  5970. };
  5971. var onLoad$2 = function (component, repConfig, repState) {
  5972. var store = repConfig.store;
  5973. store.initialValue.each(function (data) {
  5974. setValue$1(component, repConfig, repState, data);
  5975. });
  5976. };
  5977. var onUnload$1 = function (component, repConfig, repState) {
  5978. repState.clear();
  5979. };
  5980. var DatasetStore = [
  5981. option('initialValue'),
  5982. strict$1('getFallbackEntry'),
  5983. strict$1('getDataKey'),
  5984. strict$1('setValue'),
  5985. output('manager', {
  5986. setValue: setValue$1,
  5987. getValue: getValue$1,
  5988. onLoad: onLoad$2,
  5989. onUnload: onUnload$1,
  5990. state: dataset
  5991. })
  5992. ];
  5993. var getValue$2 = function (component, repConfig, repState) {
  5994. return repConfig.store.getValue(component);
  5995. };
  5996. var setValue$2 = function (component, repConfig, repState, data) {
  5997. repConfig.store.setValue(component, data);
  5998. repConfig.onSetValue(component, data);
  5999. };
  6000. var onLoad$3 = function (component, repConfig, repState) {
  6001. repConfig.store.initialValue.each(function (data) {
  6002. repConfig.store.setValue(component, data);
  6003. });
  6004. };
  6005. var ManualStore = [
  6006. strict$1('getValue'),
  6007. defaulted$1('setValue', noop),
  6008. option('initialValue'),
  6009. output('manager', {
  6010. setValue: setValue$2,
  6011. getValue: getValue$2,
  6012. onLoad: onLoad$3,
  6013. onUnload: noop,
  6014. state: NoState.init
  6015. })
  6016. ];
  6017. var setValue$3 = function (component, repConfig, repState, data) {
  6018. repState.set(data);
  6019. repConfig.onSetValue(component, data);
  6020. };
  6021. var getValue$3 = function (component, repConfig, repState) {
  6022. return repState.get();
  6023. };
  6024. var onLoad$4 = function (component, repConfig, repState) {
  6025. repConfig.store.initialValue.each(function (initVal) {
  6026. if (repState.isNotSet()) {
  6027. repState.set(initVal);
  6028. }
  6029. });
  6030. };
  6031. var onUnload$2 = function (component, repConfig, repState) {
  6032. repState.clear();
  6033. };
  6034. var MemoryStore = [
  6035. option('initialValue'),
  6036. output('manager', {
  6037. setValue: setValue$3,
  6038. getValue: getValue$3,
  6039. onLoad: onLoad$4,
  6040. onUnload: onUnload$2,
  6041. state: memory
  6042. })
  6043. ];
  6044. var RepresentSchema = [
  6045. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  6046. memory: MemoryStore,
  6047. manual: ManualStore,
  6048. dataset: DatasetStore
  6049. })),
  6050. onHandler('onSetValue'),
  6051. defaulted$1('resetOnDom', false)
  6052. ];
  6053. var Representing = create$1({
  6054. fields: RepresentSchema,
  6055. name: 'representing',
  6056. active: ActiveRepresenting,
  6057. apis: RepresentApis,
  6058. extra: {
  6059. setValueFrom: function (component, source) {
  6060. var value = Representing.getValue(source);
  6061. Representing.setValue(component, value);
  6062. }
  6063. },
  6064. state: RepresentState
  6065. });
  6066. var r = function (left, top) {
  6067. var translate = function (x, y) {
  6068. return r(left + x, top + y);
  6069. };
  6070. return {
  6071. left: constant(left),
  6072. top: constant(top),
  6073. translate: translate
  6074. };
  6075. };
  6076. var Position = r;
  6077. var isTouch$1 = PlatformDetection$1.detect().deviceType.isTouch();
  6078. var _sliderChangeEvent = 'slider.change.value';
  6079. var sliderChangeEvent = constant(_sliderChangeEvent);
  6080. var getEventSource = function (simulatedEvent) {
  6081. var evt = simulatedEvent.event().raw();
  6082. if (isTouch$1) {
  6083. var touchEvent = evt;
  6084. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  6085. return Position(t.clientX, t.clientY);
  6086. }) : Option.none();
  6087. } else {
  6088. var mouseEvent = evt;
  6089. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  6090. return Position(me.clientX, me.clientY);
  6091. }) : Option.none();
  6092. }
  6093. };
  6094. var reduceBy = function (value, min, max, step) {
  6095. if (value < min) {
  6096. return value;
  6097. } else if (value > max) {
  6098. return max;
  6099. } else if (value === min) {
  6100. return min - 1;
  6101. } else {
  6102. return Math.max(min, value - step);
  6103. }
  6104. };
  6105. var increaseBy = function (value, min, max, step) {
  6106. if (value > max) {
  6107. return value;
  6108. } else if (value < min) {
  6109. return min;
  6110. } else if (value === max) {
  6111. return max + 1;
  6112. } else {
  6113. return Math.min(max, value + step);
  6114. }
  6115. };
  6116. var capValue = function (value, min, max) {
  6117. return Math.max(min, Math.min(max, value));
  6118. };
  6119. var snapValueOf = function (value, min, max, step, snapStart) {
  6120. return snapStart.fold(function () {
  6121. var initValue = value - min;
  6122. var extraValue = Math.round(initValue / step) * step;
  6123. return capValue(min + extraValue, min - 1, max + 1);
  6124. }, function (start) {
  6125. var remainder = (value - start) % step;
  6126. var adjustment = Math.round(remainder / step);
  6127. var rawSteps = Math.floor((value - start) / step);
  6128. var maxSteps = Math.floor((max - start) / step);
  6129. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  6130. var r = start + numSteps * step;
  6131. return Math.max(start, r);
  6132. });
  6133. };
  6134. var findOffsetOf = function (value, min, max) {
  6135. return Math.min(max, Math.max(value, min)) - min;
  6136. };
  6137. var findValueOf = function (args) {
  6138. 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;
  6139. var capMin = hasMinEdge ? min - 1 : min;
  6140. var capMax = hasMaxEdge ? max + 1 : max;
  6141. if (value < minBound) {
  6142. return capMin;
  6143. } else if (value > maxBound) {
  6144. return capMax;
  6145. } else {
  6146. var offset = findOffsetOf(value, minBound, maxBound);
  6147. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  6148. if (snap && newValue >= min && newValue <= max) {
  6149. return snapValueOf(newValue, min, max, step, snapStart);
  6150. } else if (rounded) {
  6151. return Math.round(newValue);
  6152. } else {
  6153. return newValue;
  6154. }
  6155. }
  6156. };
  6157. var findOffsetOfValue = function (args) {
  6158. 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;
  6159. if (value < min) {
  6160. return hasMinEdge ? 0 : centerMinEdge;
  6161. } else if (value > max) {
  6162. return hasMaxEdge ? maxBound : centerMaxEdge;
  6163. } else {
  6164. return (value - min) / range * maxOffset;
  6165. }
  6166. };
  6167. var api$1 = Dimension('width', function (element) {
  6168. return element.dom().offsetWidth;
  6169. });
  6170. var set$4 = function (element, h) {
  6171. api$1.set(element, h);
  6172. };
  6173. var get$7 = function (element) {
  6174. return api$1.get(element);
  6175. };
  6176. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  6177. var minX = function (detail) {
  6178. return detail.model.minX;
  6179. };
  6180. var minY = function (detail) {
  6181. return detail.model.minY;
  6182. };
  6183. var min1X = function (detail) {
  6184. return detail.model.minX - 1;
  6185. };
  6186. var min1Y = function (detail) {
  6187. return detail.model.minY - 1;
  6188. };
  6189. var maxX = function (detail) {
  6190. return detail.model.maxX;
  6191. };
  6192. var maxY = function (detail) {
  6193. return detail.model.maxY;
  6194. };
  6195. var max1X = function (detail) {
  6196. return detail.model.maxX + 1;
  6197. };
  6198. var max1Y = function (detail) {
  6199. return detail.model.maxY + 1;
  6200. };
  6201. var range$1 = function (detail, max, min) {
  6202. return max(detail) - min(detail);
  6203. };
  6204. var xRange = function (detail) {
  6205. return range$1(detail, maxX, minX);
  6206. };
  6207. var yRange = function (detail) {
  6208. return range$1(detail, maxY, minY);
  6209. };
  6210. var halfX = function (detail) {
  6211. return xRange(detail) / 2;
  6212. };
  6213. var halfY = function (detail) {
  6214. return yRange(detail) / 2;
  6215. };
  6216. var step = function (detail) {
  6217. return detail.stepSize;
  6218. };
  6219. var snap = function (detail) {
  6220. return detail.snapToGrid;
  6221. };
  6222. var snapStart = function (detail) {
  6223. return detail.snapStart;
  6224. };
  6225. var rounded = function (detail) {
  6226. return detail.rounded;
  6227. };
  6228. var hasEdge = function (detail, edgeName) {
  6229. return detail[edgeName + '-edge'] !== undefined;
  6230. };
  6231. var hasLEdge = function (detail) {
  6232. return hasEdge(detail, l);
  6233. };
  6234. var hasREdge = function (detail) {
  6235. return hasEdge(detail, r$1);
  6236. };
  6237. var hasTEdge = function (detail) {
  6238. return hasEdge(detail, t);
  6239. };
  6240. var hasBEdge = function (detail) {
  6241. return hasEdge(detail, b);
  6242. };
  6243. var currentValue = function (detail) {
  6244. return detail.model.value.get();
  6245. };
  6246. var xValue = function (x) {
  6247. return { x: constant(x) };
  6248. };
  6249. var yValue = function (y) {
  6250. return { y: constant(y) };
  6251. };
  6252. var xyValue = function (x, y) {
  6253. return {
  6254. x: constant(x),
  6255. y: constant(y)
  6256. };
  6257. };
  6258. var fireSliderChange = function (component, value) {
  6259. emitWith(component, sliderChangeEvent(), { value: value });
  6260. };
  6261. var setToTLEdgeXY = function (edge, detail) {
  6262. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  6263. };
  6264. var setToTEdge = function (edge, detail) {
  6265. fireSliderChange(edge, yValue(min1Y(detail)));
  6266. };
  6267. var setToTEdgeXY = function (edge, detail) {
  6268. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  6269. };
  6270. var setToTREdgeXY = function (edge, detail) {
  6271. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  6272. };
  6273. var setToREdge = function (edge, detail) {
  6274. fireSliderChange(edge, xValue(max1X(detail)));
  6275. };
  6276. var setToREdgeXY = function (edge, detail) {
  6277. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  6278. };
  6279. var setToBREdgeXY = function (edge, detail) {
  6280. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  6281. };
  6282. var setToBEdge = function (edge, detail) {
  6283. fireSliderChange(edge, yValue(max1Y(detail)));
  6284. };
  6285. var setToBEdgeXY = function (edge, detail) {
  6286. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  6287. };
  6288. var setToBLEdgeXY = function (edge, detail) {
  6289. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  6290. };
  6291. var setToLEdge = function (edge, detail) {
  6292. fireSliderChange(edge, xValue(min1X(detail)));
  6293. };
  6294. var setToLEdgeXY = function (edge, detail) {
  6295. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  6296. };
  6297. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  6298. var getBounds = function (component) {
  6299. return component.element().dom().getBoundingClientRect();
  6300. };
  6301. var getBoundsProperty = function (bounds, property) {
  6302. return bounds[property];
  6303. };
  6304. var getMinXBounds = function (component) {
  6305. var bounds = getBounds(component);
  6306. return getBoundsProperty(bounds, left);
  6307. };
  6308. var getMaxXBounds = function (component) {
  6309. var bounds = getBounds(component);
  6310. return getBoundsProperty(bounds, right);
  6311. };
  6312. var getMinYBounds = function (component) {
  6313. var bounds = getBounds(component);
  6314. return getBoundsProperty(bounds, top);
  6315. };
  6316. var getMaxYBounds = function (component) {
  6317. var bounds = getBounds(component);
  6318. return getBoundsProperty(bounds, bottom);
  6319. };
  6320. var getXScreenRange = function (component) {
  6321. var bounds = getBounds(component);
  6322. return getBoundsProperty(bounds, width);
  6323. };
  6324. var getYScreenRange = function (component) {
  6325. var bounds = getBounds(component);
  6326. return getBoundsProperty(bounds, height);
  6327. };
  6328. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  6329. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  6330. };
  6331. var getXCenterOffSetOf = function (component, spectrum) {
  6332. var componentBounds = getBounds(component);
  6333. var spectrumBounds = getBounds(spectrum);
  6334. var componentMinEdge = getBoundsProperty(componentBounds, left);
  6335. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  6336. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  6337. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  6338. };
  6339. var getYCenterOffSetOf = function (component, spectrum) {
  6340. var componentBounds = getBounds(component);
  6341. var spectrumBounds = getBounds(spectrum);
  6342. var componentMinEdge = getBoundsProperty(componentBounds, top);
  6343. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  6344. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  6345. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  6346. };
  6347. var fireSliderChange$1 = function (spectrum, value) {
  6348. emitWith(spectrum, sliderChangeEvent(), { value: value });
  6349. };
  6350. var sliderValue = function (x) {
  6351. return { x: constant(x) };
  6352. };
  6353. var findValueOfOffset = function (spectrum, detail, left) {
  6354. var args = {
  6355. min: minX(detail),
  6356. max: maxX(detail),
  6357. range: xRange(detail),
  6358. value: left,
  6359. step: step(detail),
  6360. snap: snap(detail),
  6361. snapStart: snapStart(detail),
  6362. rounded: rounded(detail),
  6363. hasMinEdge: hasLEdge(detail),
  6364. hasMaxEdge: hasREdge(detail),
  6365. minBound: getMinXBounds(spectrum),
  6366. maxBound: getMaxXBounds(spectrum),
  6367. screenRange: getXScreenRange(spectrum)
  6368. };
  6369. return findValueOf(args);
  6370. };
  6371. var setValueFrom = function (spectrum, detail, value) {
  6372. var xValue = findValueOfOffset(spectrum, detail, value);
  6373. var sliderVal = sliderValue(xValue);
  6374. fireSliderChange$1(spectrum, sliderVal);
  6375. return xValue;
  6376. };
  6377. var setToMin = function (spectrum, detail) {
  6378. var min = minX(detail);
  6379. fireSliderChange$1(spectrum, sliderValue(min));
  6380. };
  6381. var setToMax = function (spectrum, detail) {
  6382. var max = maxX(detail);
  6383. fireSliderChange$1(spectrum, sliderValue(max));
  6384. };
  6385. var moveBy = function (direction, spectrum, detail) {
  6386. var f = direction > 0 ? increaseBy : reduceBy;
  6387. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  6388. fireSliderChange$1(spectrum, sliderValue(xValue));
  6389. return Option.some(xValue);
  6390. };
  6391. var handleMovement = function (direction) {
  6392. return function (spectrum, detail) {
  6393. return moveBy(direction, spectrum, detail).map(function () {
  6394. return true;
  6395. });
  6396. };
  6397. };
  6398. var getValueFromEvent = function (simulatedEvent) {
  6399. var pos = getEventSource(simulatedEvent);
  6400. return pos.map(function (p) {
  6401. return p.left();
  6402. });
  6403. };
  6404. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  6405. var minOffset = 0;
  6406. var maxOffset = getXScreenRange(spectrum);
  6407. var centerMinEdge = minEdge.bind(function (edge) {
  6408. return Option.some(getXCenterOffSetOf(edge, spectrum));
  6409. }).getOr(minOffset);
  6410. var centerMaxEdge = maxEdge.bind(function (edge) {
  6411. return Option.some(getXCenterOffSetOf(edge, spectrum));
  6412. }).getOr(maxOffset);
  6413. var args = {
  6414. min: minX(detail),
  6415. max: maxX(detail),
  6416. range: xRange(detail),
  6417. value: value,
  6418. hasMinEdge: hasLEdge(detail),
  6419. hasMaxEdge: hasREdge(detail),
  6420. minBound: getMinXBounds(spectrum),
  6421. minOffset: minOffset,
  6422. maxBound: getMaxXBounds(spectrum),
  6423. maxOffset: maxOffset,
  6424. centerMinEdge: centerMinEdge,
  6425. centerMaxEdge: centerMaxEdge
  6426. };
  6427. return findOffsetOfValue(args);
  6428. };
  6429. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  6430. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  6431. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  6432. };
  6433. var setPositionFromValue = function (slider, thumb, detail, edges) {
  6434. var value = currentValue(detail);
  6435. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  6436. var thumbRadius = get$7(thumb.element()) / 2;
  6437. set$3(thumb.element(), 'left', pos - thumbRadius + 'px');
  6438. };
  6439. var onLeft = handleMovement(-1);
  6440. var onRight = handleMovement(1);
  6441. var onUp = Option.none;
  6442. var onDown = Option.none;
  6443. var edgeActions = {
  6444. 'top-left': Option.none(),
  6445. 'top': Option.none(),
  6446. 'top-right': Option.none(),
  6447. 'right': Option.some(setToREdge),
  6448. 'bottom-right': Option.none(),
  6449. 'bottom': Option.none(),
  6450. 'bottom-left': Option.none(),
  6451. 'left': Option.some(setToLEdge)
  6452. };
  6453. var HorizontalModel = /*#__PURE__*/Object.freeze({
  6454. setValueFrom: setValueFrom,
  6455. setToMin: setToMin,
  6456. setToMax: setToMax,
  6457. findValueOfOffset: findValueOfOffset,
  6458. getValueFromEvent: getValueFromEvent,
  6459. findPositionOfValue: findPositionOfValue,
  6460. setPositionFromValue: setPositionFromValue,
  6461. onLeft: onLeft,
  6462. onRight: onRight,
  6463. onUp: onUp,
  6464. onDown: onDown,
  6465. edgeActions: edgeActions
  6466. });
  6467. var fireSliderChange$2 = function (spectrum, value) {
  6468. emitWith(spectrum, sliderChangeEvent(), { value: value });
  6469. };
  6470. var sliderValue$1 = function (y) {
  6471. return { y: constant(y) };
  6472. };
  6473. var findValueOfOffset$1 = function (spectrum, detail, top) {
  6474. var args = {
  6475. min: minY(detail),
  6476. max: maxY(detail),
  6477. range: yRange(detail),
  6478. value: top,
  6479. step: step(detail),
  6480. snap: snap(detail),
  6481. snapStart: snapStart(detail),
  6482. rounded: rounded(detail),
  6483. hasMinEdge: hasTEdge(detail),
  6484. hasMaxEdge: hasBEdge(detail),
  6485. minBound: getMinYBounds(spectrum),
  6486. maxBound: getMaxYBounds(spectrum),
  6487. screenRange: getYScreenRange(spectrum)
  6488. };
  6489. return findValueOf(args);
  6490. };
  6491. var setValueFrom$1 = function (spectrum, detail, value) {
  6492. var yValue = findValueOfOffset$1(spectrum, detail, value);
  6493. var sliderVal = sliderValue$1(yValue);
  6494. fireSliderChange$2(spectrum, sliderVal);
  6495. return yValue;
  6496. };
  6497. var setToMin$1 = function (spectrum, detail) {
  6498. var min = minY(detail);
  6499. fireSliderChange$2(spectrum, sliderValue$1(min));
  6500. };
  6501. var setToMax$1 = function (spectrum, detail) {
  6502. var max = maxY(detail);
  6503. fireSliderChange$2(spectrum, sliderValue$1(max));
  6504. };
  6505. var moveBy$1 = function (direction, spectrum, detail) {
  6506. var f = direction > 0 ? increaseBy : reduceBy;
  6507. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  6508. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  6509. return Option.some(yValue);
  6510. };
  6511. var handleMovement$1 = function (direction) {
  6512. return function (spectrum, detail) {
  6513. return moveBy$1(direction, spectrum, detail).map(function () {
  6514. return true;
  6515. });
  6516. };
  6517. };
  6518. var getValueFromEvent$1 = function (simulatedEvent) {
  6519. var pos = getEventSource(simulatedEvent);
  6520. return pos.map(function (p) {
  6521. return p.top();
  6522. });
  6523. };
  6524. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  6525. var minOffset = 0;
  6526. var maxOffset = getYScreenRange(spectrum);
  6527. var centerMinEdge = minEdge.bind(function (edge) {
  6528. return Option.some(getYCenterOffSetOf(edge, spectrum));
  6529. }).getOr(minOffset);
  6530. var centerMaxEdge = maxEdge.bind(function (edge) {
  6531. return Option.some(getYCenterOffSetOf(edge, spectrum));
  6532. }).getOr(maxOffset);
  6533. var args = {
  6534. min: minY(detail),
  6535. max: maxY(detail),
  6536. range: yRange(detail),
  6537. value: value,
  6538. hasMinEdge: hasTEdge(detail),
  6539. hasMaxEdge: hasBEdge(detail),
  6540. minBound: getMinYBounds(spectrum),
  6541. minOffset: minOffset,
  6542. maxBound: getMaxYBounds(spectrum),
  6543. maxOffset: maxOffset,
  6544. centerMinEdge: centerMinEdge,
  6545. centerMaxEdge: centerMaxEdge
  6546. };
  6547. return findOffsetOfValue(args);
  6548. };
  6549. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  6550. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  6551. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  6552. };
  6553. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  6554. var value = currentValue(detail);
  6555. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  6556. var thumbRadius = get$5(thumb.element()) / 2;
  6557. set$3(thumb.element(), 'top', pos - thumbRadius + 'px');
  6558. };
  6559. var onLeft$1 = Option.none;
  6560. var onRight$1 = Option.none;
  6561. var onUp$1 = handleMovement$1(-1);
  6562. var onDown$1 = handleMovement$1(1);
  6563. var edgeActions$1 = {
  6564. 'top-left': Option.none(),
  6565. 'top': Option.some(setToTEdge),
  6566. 'top-right': Option.none(),
  6567. 'right': Option.none(),
  6568. 'bottom-right': Option.none(),
  6569. 'bottom': Option.some(setToBEdge),
  6570. 'bottom-left': Option.none(),
  6571. 'left': Option.none()
  6572. };
  6573. var VerticalModel = /*#__PURE__*/Object.freeze({
  6574. setValueFrom: setValueFrom$1,
  6575. setToMin: setToMin$1,
  6576. setToMax: setToMax$1,
  6577. findValueOfOffset: findValueOfOffset$1,
  6578. getValueFromEvent: getValueFromEvent$1,
  6579. findPositionOfValue: findPositionOfValue$1,
  6580. setPositionFromValue: setPositionFromValue$1,
  6581. onLeft: onLeft$1,
  6582. onRight: onRight$1,
  6583. onUp: onUp$1,
  6584. onDown: onDown$1,
  6585. edgeActions: edgeActions$1
  6586. });
  6587. var fireSliderChange$3 = function (spectrum, value) {
  6588. emitWith(spectrum, sliderChangeEvent(), { value: value });
  6589. };
  6590. var sliderValue$2 = function (x, y) {
  6591. return {
  6592. x: constant(x),
  6593. y: constant(y)
  6594. };
  6595. };
  6596. var setValueFrom$2 = function (spectrum, detail, value) {
  6597. var xValue = findValueOfOffset(spectrum, detail, value.left());
  6598. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  6599. var val = sliderValue$2(xValue, yValue);
  6600. fireSliderChange$3(spectrum, val);
  6601. return val;
  6602. };
  6603. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  6604. var f = direction > 0 ? increaseBy : reduceBy;
  6605. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  6606. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  6607. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  6608. return Option.some(xValue);
  6609. };
  6610. var handleMovement$2 = function (direction, isVerticalMovement) {
  6611. return function (spectrum, detail) {
  6612. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  6613. return true;
  6614. });
  6615. };
  6616. };
  6617. var setToMin$2 = function (spectrum, detail) {
  6618. var mX = minX(detail);
  6619. var mY = minY(detail);
  6620. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  6621. };
  6622. var setToMax$2 = function (spectrum, detail) {
  6623. var mX = maxX(detail);
  6624. var mY = maxY(detail);
  6625. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  6626. };
  6627. var getValueFromEvent$2 = function (simulatedEvent) {
  6628. return getEventSource(simulatedEvent);
  6629. };
  6630. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  6631. var value = currentValue(detail);
  6632. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  6633. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  6634. var thumbXRadius = get$7(thumb.element()) / 2;
  6635. var thumbYRadius = get$5(thumb.element()) / 2;
  6636. set$3(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  6637. set$3(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  6638. };
  6639. var onLeft$2 = handleMovement$2(-1, false);
  6640. var onRight$2 = handleMovement$2(1, false);
  6641. var onUp$2 = handleMovement$2(-1, true);
  6642. var onDown$2 = handleMovement$2(1, true);
  6643. var edgeActions$2 = {
  6644. 'top-left': Option.some(setToTLEdgeXY),
  6645. 'top': Option.some(setToTEdgeXY),
  6646. 'top-right': Option.some(setToTREdgeXY),
  6647. 'right': Option.some(setToREdgeXY),
  6648. 'bottom-right': Option.some(setToBREdgeXY),
  6649. 'bottom': Option.some(setToBEdgeXY),
  6650. 'bottom-left': Option.some(setToBLEdgeXY),
  6651. 'left': Option.some(setToLEdgeXY)
  6652. };
  6653. var TwoDModel = /*#__PURE__*/Object.freeze({
  6654. setValueFrom: setValueFrom$2,
  6655. setToMin: setToMin$2,
  6656. setToMax: setToMax$2,
  6657. getValueFromEvent: getValueFromEvent$2,
  6658. setPositionFromValue: setPositionFromValue$2,
  6659. onLeft: onLeft$2,
  6660. onRight: onRight$2,
  6661. onUp: onUp$2,
  6662. onDown: onDown$2,
  6663. edgeActions: edgeActions$2
  6664. });
  6665. var isTouch$2 = PlatformDetection$1.detect().deviceType.isTouch();
  6666. var SliderSchema = [
  6667. defaulted$1('stepSize', 1),
  6668. defaulted$1('onChange', noop),
  6669. defaulted$1('onChoose', noop),
  6670. defaulted$1('onInit', noop),
  6671. defaulted$1('onDragStart', noop),
  6672. defaulted$1('onDragEnd', noop),
  6673. defaulted$1('snapToGrid', false),
  6674. defaulted$1('rounded', true),
  6675. option('snapStart'),
  6676. strictOf('model', choose$1('mode', {
  6677. x: [
  6678. defaulted$1('minX', 0),
  6679. defaulted$1('maxX', 100),
  6680. state$1('value', function (spec) {
  6681. return Cell(spec.mode.minX);
  6682. }),
  6683. strict$1('getInitialValue'),
  6684. output('manager', HorizontalModel)
  6685. ],
  6686. y: [
  6687. defaulted$1('minY', 0),
  6688. defaulted$1('maxY', 100),
  6689. state$1('value', function (spec) {
  6690. return Cell(spec.mode.minY);
  6691. }),
  6692. strict$1('getInitialValue'),
  6693. output('manager', VerticalModel)
  6694. ],
  6695. xy: [
  6696. defaulted$1('minX', 0),
  6697. defaulted$1('maxX', 100),
  6698. defaulted$1('minY', 0),
  6699. defaulted$1('maxY', 100),
  6700. state$1('value', function (spec) {
  6701. return Cell({
  6702. x: constant(spec.mode.minX),
  6703. y: constant(spec.mode.minY)
  6704. });
  6705. }),
  6706. strict$1('getInitialValue'),
  6707. output('manager', TwoDModel)
  6708. ]
  6709. })),
  6710. field$1('sliderBehaviours', [
  6711. Keying,
  6712. Representing
  6713. ])
  6714. ].concat(!isTouch$2 ? [state$1('mouseIsDown', function () {
  6715. return Cell(false);
  6716. })] : []);
  6717. var isTouch$3 = PlatformDetection$1.detect().deviceType.isTouch();
  6718. var sketch = function (detail, components, _spec, _externals) {
  6719. var getThumb = function (component) {
  6720. return getPartOrDie(component, detail, 'thumb');
  6721. };
  6722. var getSpectrum = function (component) {
  6723. return getPartOrDie(component, detail, 'spectrum');
  6724. };
  6725. var getLeftEdge = function (component) {
  6726. return getPart(component, detail, 'left-edge');
  6727. };
  6728. var getRightEdge = function (component) {
  6729. return getPart(component, detail, 'right-edge');
  6730. };
  6731. var getTopEdge = function (component) {
  6732. return getPart(component, detail, 'top-edge');
  6733. };
  6734. var getBottomEdge = function (component) {
  6735. return getPart(component, detail, 'bottom-edge');
  6736. };
  6737. var modelDetail = detail.model;
  6738. var model = modelDetail.manager;
  6739. var refresh = function (slider, thumb) {
  6740. model.setPositionFromValue(slider, thumb, detail, {
  6741. getLeftEdge: getLeftEdge,
  6742. getRightEdge: getRightEdge,
  6743. getTopEdge: getTopEdge,
  6744. getBottomEdge: getBottomEdge,
  6745. getSpectrum: getSpectrum
  6746. });
  6747. };
  6748. var changeValue = function (slider, newValue) {
  6749. modelDetail.value.set(newValue);
  6750. var thumb = getThumb(slider);
  6751. refresh(slider, thumb);
  6752. detail.onChange(slider, thumb, newValue);
  6753. return Option.some(true);
  6754. };
  6755. var resetToMin = function (slider) {
  6756. model.setToMin(slider, detail);
  6757. };
  6758. var resetToMax = function (slider) {
  6759. model.setToMax(slider, detail);
  6760. };
  6761. var touchEvents = [
  6762. run(touchstart(), function (slider, _simulatedEvent) {
  6763. detail.onDragStart(slider, getThumb(slider));
  6764. }),
  6765. run(touchend(), function (slider, _simulatedEvent) {
  6766. detail.onDragEnd(slider, getThumb(slider));
  6767. })
  6768. ];
  6769. var mouseEvents = [
  6770. run(mousedown(), function (slider, simulatedEvent) {
  6771. simulatedEvent.stop();
  6772. detail.onDragStart(slider, getThumb(slider));
  6773. detail.mouseIsDown.set(true);
  6774. }),
  6775. run(mouseup(), function (slider, _simulatedEvent) {
  6776. detail.onDragEnd(slider, getThumb(slider));
  6777. })
  6778. ];
  6779. var uiEventsArr = isTouch$3 ? touchEvents : mouseEvents;
  6780. return {
  6781. uid: detail.uid,
  6782. dom: detail.dom,
  6783. components: components,
  6784. behaviours: augment(detail.sliderBehaviours, flatten([
  6785. !isTouch$3 ? [Keying.config({
  6786. mode: 'special',
  6787. focusIn: function (slider) {
  6788. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  6789. }
  6790. })] : [],
  6791. [
  6792. Representing.config({
  6793. store: {
  6794. mode: 'manual',
  6795. getValue: function (_) {
  6796. return modelDetail.value.get();
  6797. }
  6798. }
  6799. }),
  6800. Receiving.config({
  6801. channels: {
  6802. 'mouse.released': {
  6803. onReceive: function (slider, se) {
  6804. var wasDown = detail.mouseIsDown.get();
  6805. detail.mouseIsDown.set(false);
  6806. if (wasDown) {
  6807. getPart(slider, detail, 'thumb').each(function (thumb) {
  6808. var value = modelDetail.value.get();
  6809. detail.onChoose(slider, thumb, value);
  6810. });
  6811. }
  6812. }
  6813. }
  6814. }
  6815. })
  6816. ]
  6817. ])),
  6818. events: derive([
  6819. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  6820. changeValue(slider, simulatedEvent.event().value());
  6821. }),
  6822. runOnAttached(function (slider, simulatedEvent) {
  6823. var getInitial = modelDetail.getInitialValue();
  6824. modelDetail.value.set(getInitial);
  6825. var thumb = getThumb(slider);
  6826. refresh(slider, thumb);
  6827. var spectrum = getSpectrum(slider);
  6828. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  6829. })
  6830. ].concat(uiEventsArr)),
  6831. apis: {
  6832. resetToMin: resetToMin,
  6833. resetToMax: resetToMax,
  6834. changeValue: changeValue,
  6835. refresh: refresh
  6836. },
  6837. domModification: { styles: { position: 'relative' } }
  6838. };
  6839. };
  6840. var Slider = composite$1({
  6841. name: 'Slider',
  6842. configFields: SliderSchema,
  6843. partFields: SliderParts,
  6844. factory: sketch,
  6845. apis: {
  6846. resetToMin: function (apis, slider) {
  6847. apis.resetToMin(slider);
  6848. },
  6849. resetToMax: function (apis, slider) {
  6850. apis.resetToMax(slider);
  6851. },
  6852. refresh: function (apis, slider) {
  6853. apis.refresh(slider);
  6854. }
  6855. }
  6856. });
  6857. var button = function (realm, clazz, makeItems, editor) {
  6858. return Buttons.forToolbar(clazz, function () {
  6859. var items = makeItems();
  6860. realm.setContextToolbar([{
  6861. label: clazz + ' group',
  6862. items: items
  6863. }]);
  6864. }, {}, editor);
  6865. };
  6866. var BLACK = -1;
  6867. var makeSlider = function (spec$1) {
  6868. var getColor = function (hue) {
  6869. if (hue < 0) {
  6870. return 'black';
  6871. } else if (hue > 360) {
  6872. return 'white';
  6873. } else {
  6874. return 'hsl(' + hue + ', 100%, 50%)';
  6875. }
  6876. };
  6877. var onInit = function (slider, thumb, spectrum, value) {
  6878. var color = getColor(value.x());
  6879. set$3(thumb.element(), 'background-color', color);
  6880. };
  6881. var onChange = function (slider, thumb, value) {
  6882. var color = getColor(value.x());
  6883. set$3(thumb.element(), 'background-color', color);
  6884. spec$1.onChange(slider, thumb, color);
  6885. };
  6886. return Slider.sketch({
  6887. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  6888. components: [
  6889. Slider.parts()['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  6890. Slider.parts().spectrum({
  6891. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  6892. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  6893. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  6894. }),
  6895. Slider.parts()['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  6896. Slider.parts().thumb({
  6897. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6898. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  6899. })
  6900. ],
  6901. onChange: onChange,
  6902. onDragStart: function (slider, thumb) {
  6903. Toggling.on(thumb);
  6904. },
  6905. onDragEnd: function (slider, thumb) {
  6906. Toggling.off(thumb);
  6907. },
  6908. onInit: onInit,
  6909. stepSize: 10,
  6910. model: {
  6911. mode: 'x',
  6912. minX: 0,
  6913. maxX: 360,
  6914. getInitialValue: function () {
  6915. return {
  6916. x: function () {
  6917. return spec$1.getInitialValue();
  6918. }
  6919. };
  6920. }
  6921. },
  6922. sliderBehaviours: derive$1([Receivers.orientation(Slider.refresh)])
  6923. });
  6924. };
  6925. var makeItems = function (spec) {
  6926. return [makeSlider(spec)];
  6927. };
  6928. var sketch$1 = function (realm, editor) {
  6929. var spec = {
  6930. onChange: function (slider, thumb, color) {
  6931. editor.undoManager.transact(function () {
  6932. editor.formatter.apply('forecolor', { value: color });
  6933. editor.nodeChanged();
  6934. });
  6935. },
  6936. getInitialValue: function () {
  6937. return BLACK;
  6938. }
  6939. };
  6940. return button(realm, 'color-levels', function () {
  6941. return makeItems(spec);
  6942. }, editor);
  6943. };
  6944. var ColorSlider = {
  6945. makeItems: makeItems,
  6946. sketch: sketch$1
  6947. };
  6948. var schema$7 = objOfOnly([
  6949. strict$1('getInitialValue'),
  6950. strict$1('onChange'),
  6951. strict$1('category'),
  6952. strict$1('sizes')
  6953. ]);
  6954. var sketch$2 = function (rawSpec) {
  6955. var spec$1 = asRawOrDie('SizeSlider', schema$7, rawSpec);
  6956. var isValidValue = function (valueIndex) {
  6957. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6958. };
  6959. var onChange = function (slider, thumb, valueIndex) {
  6960. var index = valueIndex.x();
  6961. if (isValidValue(index)) {
  6962. spec$1.onChange(index);
  6963. }
  6964. };
  6965. return Slider.sketch({
  6966. dom: {
  6967. tag: 'div',
  6968. classes: [
  6969. Styles.resolve('slider-' + spec$1.category + '-size-container'),
  6970. Styles.resolve('slider'),
  6971. Styles.resolve('slider-size-container')
  6972. ]
  6973. },
  6974. onChange: onChange,
  6975. onDragStart: function (slider, thumb) {
  6976. Toggling.on(thumb);
  6977. },
  6978. onDragEnd: function (slider, thumb) {
  6979. Toggling.off(thumb);
  6980. },
  6981. model: {
  6982. mode: 'x',
  6983. minX: 0,
  6984. maxX: spec$1.sizes.length - 1,
  6985. getInitialValue: function () {
  6986. return {
  6987. x: function () {
  6988. return spec$1.getInitialValue();
  6989. }
  6990. };
  6991. }
  6992. },
  6993. stepSize: 1,
  6994. snapToGrid: true,
  6995. sliderBehaviours: derive$1([Receivers.orientation(Slider.refresh)]),
  6996. components: [
  6997. Slider.parts().spectrum({
  6998. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6999. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  7000. }),
  7001. Slider.parts().thumb({
  7002. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  7003. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  7004. })
  7005. ]
  7006. });
  7007. };
  7008. var SizeSlider = { sketch: sketch$2 };
  7009. var candidates = [
  7010. '9px',
  7011. '10px',
  7012. '11px',
  7013. '12px',
  7014. '14px',
  7015. '16px',
  7016. '18px',
  7017. '20px',
  7018. '24px',
  7019. '32px',
  7020. '36px'
  7021. ];
  7022. var defaultSize = 'medium';
  7023. var defaultIndex = 2;
  7024. var indexToSize = function (index) {
  7025. return Option.from(candidates[index]);
  7026. };
  7027. var sizeToIndex = function (size) {
  7028. return findIndex(candidates, function (v) {
  7029. return v === size;
  7030. });
  7031. };
  7032. var getRawOrComputed = function (isRoot, rawStart) {
  7033. var optStart = isElement(rawStart) ? Option.some(rawStart) : parent(rawStart);
  7034. return optStart.map(function (start) {
  7035. var inline = closest(start, function (elem) {
  7036. return getRaw(elem, 'font-size').isSome();
  7037. }, isRoot).bind(function (elem) {
  7038. return getRaw(elem, 'font-size');
  7039. });
  7040. return inline.getOrThunk(function () {
  7041. return get$4(start, 'font-size');
  7042. });
  7043. }).getOr('');
  7044. };
  7045. var getSize = function (editor) {
  7046. var node = editor.selection.getStart();
  7047. var elem = Element.fromDom(node);
  7048. var root = Element.fromDom(editor.getBody());
  7049. var isRoot = function (e) {
  7050. return eq(root, e);
  7051. };
  7052. var elemSize = getRawOrComputed(isRoot, elem);
  7053. return find$2(candidates, function (size) {
  7054. return elemSize === size;
  7055. }).getOr(defaultSize);
  7056. };
  7057. var applySize = function (editor, value) {
  7058. var currentValue = getSize(editor);
  7059. if (currentValue !== value) {
  7060. editor.execCommand('fontSize', false, value);
  7061. }
  7062. };
  7063. var get$8 = function (editor) {
  7064. var size = getSize(editor);
  7065. return sizeToIndex(size).getOr(defaultIndex);
  7066. };
  7067. var apply$1 = function (editor, index) {
  7068. indexToSize(index).each(function (size) {
  7069. applySize(editor, size);
  7070. });
  7071. };
  7072. var FontSizes = {
  7073. candidates: constant(candidates),
  7074. get: get$8,
  7075. apply: apply$1
  7076. };
  7077. var sizes = FontSizes.candidates();
  7078. var makeSlider$1 = function (spec) {
  7079. return SizeSlider.sketch({
  7080. onChange: spec.onChange,
  7081. sizes: sizes,
  7082. category: 'font',
  7083. getInitialValue: spec.getInitialValue
  7084. });
  7085. };
  7086. var makeItems$1 = function (spec$1) {
  7087. return [
  7088. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  7089. makeSlider$1(spec$1),
  7090. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  7091. ];
  7092. };
  7093. var sketch$3 = function (realm, editor) {
  7094. var spec = {
  7095. onChange: function (value) {
  7096. FontSizes.apply(editor, value);
  7097. },
  7098. getInitialValue: function () {
  7099. return FontSizes.get(editor);
  7100. }
  7101. };
  7102. return button(realm, 'font-size', function () {
  7103. return makeItems$1(spec);
  7104. }, editor);
  7105. };
  7106. var record = function (spec) {
  7107. var uid = isSketchSpec(spec) && hasKey$1(spec, 'uid') ? spec.uid : generate$3('memento');
  7108. var get = function (anyInSystem) {
  7109. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  7110. };
  7111. var getOpt = function (anyInSystem) {
  7112. return anyInSystem.getSystem().getByUid(uid).fold(Option.none, Option.some);
  7113. };
  7114. var asSpec = function () {
  7115. return __assign({}, spec, { uid: uid });
  7116. };
  7117. return {
  7118. get: get,
  7119. getOpt: getOpt,
  7120. asSpec: asSpec
  7121. };
  7122. };
  7123. var Memento = /*#__PURE__*/Object.freeze({
  7124. record: record
  7125. });
  7126. function FileReader () {
  7127. var f = Global$1.getOrDie('FileReader');
  7128. return new f();
  7129. }
  7130. var promise = function () {
  7131. var Promise = function (fn) {
  7132. if (typeof this !== 'object') {
  7133. throw new TypeError('Promises must be constructed via new');
  7134. }
  7135. if (typeof fn !== 'function') {
  7136. throw new TypeError('not a function');
  7137. }
  7138. this._state = null;
  7139. this._value = null;
  7140. this._deferreds = [];
  7141. doResolve(fn, bind(resolve, this), bind(reject, this));
  7142. };
  7143. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  7144. domGlobals.setTimeout(fn, 1);
  7145. };
  7146. function bind(fn, thisArg) {
  7147. return function () {
  7148. return fn.apply(thisArg, arguments);
  7149. };
  7150. }
  7151. var isArray = Array.isArray || function (value) {
  7152. return Object.prototype.toString.call(value) === '[object Array]';
  7153. };
  7154. function handle(deferred) {
  7155. var me = this;
  7156. if (this._state === null) {
  7157. this._deferreds.push(deferred);
  7158. return;
  7159. }
  7160. asap(function () {
  7161. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  7162. if (cb === null) {
  7163. (me._state ? deferred.resolve : deferred.reject)(me._value);
  7164. return;
  7165. }
  7166. var ret;
  7167. try {
  7168. ret = cb(me._value);
  7169. } catch (e) {
  7170. deferred.reject(e);
  7171. return;
  7172. }
  7173. deferred.resolve(ret);
  7174. });
  7175. }
  7176. function resolve(newValue) {
  7177. try {
  7178. if (newValue === this) {
  7179. throw new TypeError('A promise cannot be resolved with itself.');
  7180. }
  7181. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  7182. var then = newValue.then;
  7183. if (typeof then === 'function') {
  7184. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  7185. return;
  7186. }
  7187. }
  7188. this._state = true;
  7189. this._value = newValue;
  7190. finale.call(this);
  7191. } catch (e) {
  7192. reject.call(this, e);
  7193. }
  7194. }
  7195. function reject(newValue) {
  7196. this._state = false;
  7197. this._value = newValue;
  7198. finale.call(this);
  7199. }
  7200. function finale() {
  7201. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  7202. var deferred = _a[_i];
  7203. handle.call(this, deferred);
  7204. }
  7205. this._deferreds = [];
  7206. }
  7207. function Handler(onFulfilled, onRejected, resolve, reject) {
  7208. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  7209. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  7210. this.resolve = resolve;
  7211. this.reject = reject;
  7212. }
  7213. function doResolve(fn, onFulfilled, onRejected) {
  7214. var done = false;
  7215. try {
  7216. fn(function (value) {
  7217. if (done) {
  7218. return;
  7219. }
  7220. done = true;
  7221. onFulfilled(value);
  7222. }, function (reason) {
  7223. if (done) {
  7224. return;
  7225. }
  7226. done = true;
  7227. onRejected(reason);
  7228. });
  7229. } catch (ex) {
  7230. if (done) {
  7231. return;
  7232. }
  7233. done = true;
  7234. onRejected(ex);
  7235. }
  7236. }
  7237. Promise.prototype.catch = function (onRejected) {
  7238. return this.then(null, onRejected);
  7239. };
  7240. Promise.prototype.then = function (onFulfilled, onRejected) {
  7241. var me = this;
  7242. return new Promise(function (resolve, reject) {
  7243. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  7244. });
  7245. };
  7246. Promise.all = function () {
  7247. var values = [];
  7248. for (var _i = 0; _i < arguments.length; _i++) {
  7249. values[_i] = arguments[_i];
  7250. }
  7251. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  7252. return new Promise(function (resolve, reject) {
  7253. if (args.length === 0) {
  7254. return resolve([]);
  7255. }
  7256. var remaining = args.length;
  7257. function res(i, val) {
  7258. try {
  7259. if (val && (typeof val === 'object' || typeof val === 'function')) {
  7260. var then = val.then;
  7261. if (typeof then === 'function') {
  7262. then.call(val, function (val) {
  7263. res(i, val);
  7264. }, reject);
  7265. return;
  7266. }
  7267. }
  7268. args[i] = val;
  7269. if (--remaining === 0) {
  7270. resolve(args);
  7271. }
  7272. } catch (ex) {
  7273. reject(ex);
  7274. }
  7275. }
  7276. for (var i = 0; i < args.length; i++) {
  7277. res(i, args[i]);
  7278. }
  7279. });
  7280. };
  7281. Promise.resolve = function (value) {
  7282. if (value && typeof value === 'object' && value.constructor === Promise) {
  7283. return value;
  7284. }
  7285. return new Promise(function (resolve) {
  7286. resolve(value);
  7287. });
  7288. };
  7289. Promise.reject = function (reason) {
  7290. return new Promise(function (resolve, reject) {
  7291. reject(reason);
  7292. });
  7293. };
  7294. Promise.race = function (values) {
  7295. return new Promise(function (resolve, reject) {
  7296. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  7297. var value = values_1[_i];
  7298. value.then(resolve, reject);
  7299. }
  7300. });
  7301. };
  7302. return Promise;
  7303. };
  7304. var Promise$1 = window.Promise ? window.Promise : promise();
  7305. function blobToDataUri(blob) {
  7306. return new Promise$1(function (resolve) {
  7307. var reader = FileReader();
  7308. reader.onloadend = function () {
  7309. resolve(reader.result);
  7310. };
  7311. reader.readAsDataURL(blob);
  7312. });
  7313. }
  7314. function blobToBase64(blob) {
  7315. return blobToDataUri(blob).then(function (dataUri) {
  7316. return dataUri.split(',')[1];
  7317. });
  7318. }
  7319. var blobToBase64$1 = function (blob) {
  7320. return blobToBase64(blob);
  7321. };
  7322. var addImage = function (editor, blob) {
  7323. blobToBase64$1(blob).then(function (base64) {
  7324. editor.undoManager.transact(function () {
  7325. var cache = editor.editorUpload.blobCache;
  7326. var info = cache.create(generate$1('mceu'), blob, base64);
  7327. cache.add(info);
  7328. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  7329. editor.insertContent(img);
  7330. });
  7331. });
  7332. };
  7333. var extractBlob = function (simulatedEvent) {
  7334. var event = simulatedEvent.event();
  7335. var files = event.raw().target.files || event.raw().dataTransfer.files;
  7336. return Option.from(files[0]);
  7337. };
  7338. var sketch$4 = function (editor) {
  7339. var pickerDom = {
  7340. tag: 'input',
  7341. attributes: {
  7342. accept: 'image/*',
  7343. type: 'file',
  7344. title: ''
  7345. },
  7346. styles: {
  7347. visibility: 'hidden',
  7348. position: 'absolute'
  7349. }
  7350. };
  7351. var memPicker = record({
  7352. dom: pickerDom,
  7353. events: derive([
  7354. cutter(click()),
  7355. run(change(), function (picker, simulatedEvent) {
  7356. extractBlob(simulatedEvent).each(function (blob) {
  7357. addImage(editor, blob);
  7358. });
  7359. })
  7360. ])
  7361. });
  7362. return Button.sketch({
  7363. dom: Buttons.getToolbarIconButton('image', editor),
  7364. components: [memPicker.asSpec()],
  7365. action: function (button) {
  7366. var picker = memPicker.get(button);
  7367. picker.element().dom().click();
  7368. }
  7369. });
  7370. };
  7371. var get$9 = function (element) {
  7372. return element.dom().textContent;
  7373. };
  7374. var set$5 = function (element, value) {
  7375. element.dom().textContent = value;
  7376. };
  7377. var isNotEmpty = function (val) {
  7378. return val.length > 0;
  7379. };
  7380. var defaultToEmpty = function (str) {
  7381. return str === undefined || str === null ? '' : str;
  7382. };
  7383. var noLink = function (editor) {
  7384. var text = editor.selection.getContent({ format: 'text' });
  7385. return {
  7386. url: '',
  7387. text: text,
  7388. title: '',
  7389. target: '',
  7390. link: Option.none()
  7391. };
  7392. };
  7393. var fromLink = function (link) {
  7394. var text = get$9(link);
  7395. var url = get$1(link, 'href');
  7396. var title = get$1(link, 'title');
  7397. var target = get$1(link, 'target');
  7398. return {
  7399. url: defaultToEmpty(url),
  7400. text: text !== url ? defaultToEmpty(text) : '',
  7401. title: defaultToEmpty(title),
  7402. target: defaultToEmpty(target),
  7403. link: Option.some(link)
  7404. };
  7405. };
  7406. var getInfo = function (editor) {
  7407. return query(editor).fold(function () {
  7408. return noLink(editor);
  7409. }, function (link) {
  7410. return fromLink(link);
  7411. });
  7412. };
  7413. var wasSimple = function (link) {
  7414. var prevHref = get$1(link, 'href');
  7415. var prevText = get$9(link);
  7416. return prevHref === prevText;
  7417. };
  7418. var getTextToApply = function (link, url, info) {
  7419. return info.text.toOption().filter(isNotEmpty).fold(function () {
  7420. return wasSimple(link) ? Option.some(url) : Option.none();
  7421. }, Option.some);
  7422. };
  7423. var unlinkIfRequired = function (editor, info) {
  7424. var activeLink = info.link.bind(identity);
  7425. activeLink.each(function (link) {
  7426. editor.execCommand('unlink');
  7427. });
  7428. };
  7429. var getAttrs$1 = function (url, info) {
  7430. var attrs = {};
  7431. attrs.href = url;
  7432. info.title.toOption().filter(isNotEmpty).each(function (title) {
  7433. attrs.title = title;
  7434. });
  7435. info.target.toOption().filter(isNotEmpty).each(function (target) {
  7436. attrs.target = target;
  7437. });
  7438. return attrs;
  7439. };
  7440. var applyInfo = function (editor, info) {
  7441. info.url.toOption().filter(isNotEmpty).fold(function () {
  7442. unlinkIfRequired(editor, info);
  7443. }, function (url) {
  7444. var attrs = getAttrs$1(url, info);
  7445. var activeLink = info.link.bind(identity);
  7446. activeLink.fold(function () {
  7447. var text = info.text.toOption().filter(isNotEmpty).getOr(url);
  7448. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  7449. }, function (link) {
  7450. var text = getTextToApply(link, url, info);
  7451. setAll(link, attrs);
  7452. text.each(function (newText) {
  7453. set$5(link, newText);
  7454. });
  7455. });
  7456. });
  7457. };
  7458. var query = function (editor) {
  7459. var start = Element.fromDom(editor.selection.getStart());
  7460. return closest$2(start, 'a');
  7461. };
  7462. var LinkBridge = {
  7463. getInfo: getInfo,
  7464. applyInfo: applyInfo,
  7465. query: query
  7466. };
  7467. var platform$1 = PlatformDetection$1.detect();
  7468. var preserve$1 = function (f, editor) {
  7469. var rng = editor.selection.getRng();
  7470. f();
  7471. editor.selection.setRng(rng);
  7472. };
  7473. var forAndroid = function (editor, f) {
  7474. var wrapper = platform$1.os.isAndroid() ? preserve$1 : apply;
  7475. wrapper(f, editor);
  7476. };
  7477. var RangePreserver = { forAndroid: forAndroid };
  7478. var events$6 = function (name, eventHandlers) {
  7479. var events = derive(eventHandlers);
  7480. return create$1({
  7481. fields: [strict$1('enabled')],
  7482. name: name,
  7483. active: { events: constant(events) }
  7484. });
  7485. };
  7486. var config = function (name, eventHandlers) {
  7487. var me = events$6(name, eventHandlers);
  7488. return {
  7489. key: name,
  7490. value: {
  7491. config: {},
  7492. me: me,
  7493. configAsRaw: constant({}),
  7494. initialConfig: {},
  7495. state: NoState
  7496. }
  7497. };
  7498. };
  7499. var getCurrent = function (component, composeConfig, composeState) {
  7500. return composeConfig.find(component);
  7501. };
  7502. var ComposeApis = /*#__PURE__*/Object.freeze({
  7503. getCurrent: getCurrent
  7504. });
  7505. var ComposeSchema = [strict$1('find')];
  7506. var Composing = create$1({
  7507. fields: ComposeSchema,
  7508. name: 'composing',
  7509. apis: ComposeApis
  7510. });
  7511. var factory$1 = function (detail) {
  7512. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  7513. return {
  7514. uid: detail.uid,
  7515. dom: __assign({
  7516. tag: 'div',
  7517. attributes: __assign({ role: 'presentation' }, attributes)
  7518. }, domWithoutAttributes),
  7519. components: detail.components,
  7520. behaviours: get$6(detail.containerBehaviours),
  7521. events: detail.events,
  7522. domModification: detail.domModification,
  7523. eventOrder: detail.eventOrder
  7524. };
  7525. };
  7526. var Container = single$2({
  7527. name: 'Container',
  7528. factory: factory$1,
  7529. configFields: [
  7530. defaulted$1('components', []),
  7531. field$1('containerBehaviours', []),
  7532. defaulted$1('events', {}),
  7533. defaulted$1('domModification', {}),
  7534. defaulted$1('eventOrder', {})
  7535. ]
  7536. });
  7537. var factory$2 = function (detail) {
  7538. return {
  7539. uid: detail.uid,
  7540. dom: detail.dom,
  7541. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  7542. Representing.config({
  7543. store: {
  7544. mode: 'memory',
  7545. initialValue: detail.getInitialValue()
  7546. }
  7547. }),
  7548. Composing.config({ find: Option.some })
  7549. ]),
  7550. events: derive([runOnAttached(function (component, simulatedEvent) {
  7551. Representing.setValue(component, detail.getInitialValue());
  7552. })])
  7553. };
  7554. };
  7555. var DataField = single$2({
  7556. name: 'DataField',
  7557. factory: factory$2,
  7558. configFields: [
  7559. strict$1('uid'),
  7560. strict$1('dom'),
  7561. strict$1('getInitialValue'),
  7562. SketchBehaviours.field('dataBehaviours', [
  7563. Representing,
  7564. Composing
  7565. ])
  7566. ]
  7567. });
  7568. var get$a = function (element) {
  7569. return element.dom().value;
  7570. };
  7571. var set$6 = function (element, value) {
  7572. if (value === undefined) {
  7573. throw new Error('Value.set was undefined');
  7574. }
  7575. element.dom().value = value;
  7576. };
  7577. var schema$8 = constant([
  7578. option('data'),
  7579. defaulted$1('inputAttributes', {}),
  7580. defaulted$1('inputStyles', {}),
  7581. defaulted$1('tag', 'input'),
  7582. defaulted$1('inputClasses', []),
  7583. onHandler('onSetValue'),
  7584. defaulted$1('styles', {}),
  7585. defaulted$1('eventOrder', {}),
  7586. field$1('inputBehaviours', [
  7587. Representing,
  7588. Focusing
  7589. ]),
  7590. defaulted$1('selectOnFocus', true)
  7591. ]);
  7592. var focusBehaviours = function (detail) {
  7593. return derive$1([Focusing.config({
  7594. onFocus: detail.selectOnFocus === false ? noop : function (component) {
  7595. var input = component.element();
  7596. var value = get$a(input);
  7597. input.dom().setSelectionRange(0, value.length);
  7598. }
  7599. })]);
  7600. };
  7601. var behaviours = function (detail) {
  7602. return __assign({}, focusBehaviours(detail), augment(detail.inputBehaviours, [Representing.config({
  7603. store: {
  7604. mode: 'manual',
  7605. initialValue: detail.data.getOr(undefined),
  7606. getValue: function (input) {
  7607. return get$a(input.element());
  7608. },
  7609. setValue: function (input, data) {
  7610. var current = get$a(input.element());
  7611. if (current !== data) {
  7612. set$6(input.element(), data);
  7613. }
  7614. }
  7615. },
  7616. onSetValue: detail.onSetValue
  7617. })]));
  7618. };
  7619. var dom$2 = function (detail) {
  7620. return {
  7621. tag: detail.tag,
  7622. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  7623. styles: detail.inputStyles,
  7624. classes: detail.inputClasses
  7625. };
  7626. };
  7627. var factory$3 = function (detail, spec) {
  7628. return {
  7629. uid: detail.uid,
  7630. dom: dom$2(detail),
  7631. components: [],
  7632. behaviours: behaviours(detail),
  7633. eventOrder: detail.eventOrder
  7634. };
  7635. };
  7636. var Input = single$2({
  7637. name: 'Input',
  7638. configFields: schema$8(),
  7639. factory: factory$3
  7640. });
  7641. var exhibit$3 = function (base, tabConfig) {
  7642. return nu$5({
  7643. attributes: wrapAll$1([{
  7644. key: tabConfig.tabAttr,
  7645. value: 'true'
  7646. }])
  7647. });
  7648. };
  7649. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  7650. exhibit: exhibit$3
  7651. });
  7652. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  7653. var Tabstopping = create$1({
  7654. fields: TabstopSchema,
  7655. name: 'tabstopping',
  7656. active: ActiveTabstopping
  7657. });
  7658. var global$2 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  7659. var clearInputBehaviour = 'input-clearing';
  7660. var field$2 = function (name, placeholder) {
  7661. var inputSpec = record(Input.sketch({
  7662. inputAttributes: { placeholder: global$2.translate(placeholder) },
  7663. onSetValue: function (input$1, data) {
  7664. emit(input$1, input());
  7665. },
  7666. inputBehaviours: derive$1([
  7667. Composing.config({ find: Option.some }),
  7668. Tabstopping.config({}),
  7669. Keying.config({ mode: 'execution' })
  7670. ]),
  7671. selectOnFocus: false
  7672. }));
  7673. var buttonSpec = record(Button.sketch({
  7674. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  7675. action: function (button) {
  7676. var input = inputSpec.get(button);
  7677. Representing.setValue(input, '');
  7678. }
  7679. }));
  7680. return {
  7681. name: name,
  7682. spec: Container.sketch({
  7683. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  7684. components: [
  7685. inputSpec.asSpec(),
  7686. buttonSpec.asSpec()
  7687. ],
  7688. containerBehaviours: derive$1([
  7689. Toggling.config({ toggleClass: Styles.resolve('input-container-empty') }),
  7690. Composing.config({
  7691. find: function (comp) {
  7692. return Option.some(inputSpec.get(comp));
  7693. }
  7694. }),
  7695. config(clearInputBehaviour, [run(input(), function (iContainer) {
  7696. var input = inputSpec.get(iContainer);
  7697. var val = Representing.getValue(input);
  7698. var f = val.length > 0 ? Toggling.off : Toggling.on;
  7699. f(iContainer);
  7700. })])
  7701. ])
  7702. })
  7703. };
  7704. };
  7705. var hidden = function (name) {
  7706. return {
  7707. name: name,
  7708. spec: DataField.sketch({
  7709. dom: {
  7710. tag: 'span',
  7711. styles: { display: 'none' }
  7712. },
  7713. getInitialValue: function () {
  7714. return Option.none();
  7715. }
  7716. })
  7717. };
  7718. };
  7719. var nativeDisabled = [
  7720. 'input',
  7721. 'button',
  7722. 'textarea'
  7723. ];
  7724. var onLoad$5 = function (component, disableConfig, disableState) {
  7725. if (disableConfig.disabled) {
  7726. disable(component, disableConfig, disableState);
  7727. }
  7728. };
  7729. var hasNative = function (component) {
  7730. return contains(nativeDisabled, name(component.element()));
  7731. };
  7732. var nativeIsDisabled = function (component) {
  7733. return has$1(component.element(), 'disabled');
  7734. };
  7735. var nativeDisable = function (component) {
  7736. set(component.element(), 'disabled', 'disabled');
  7737. };
  7738. var nativeEnable = function (component) {
  7739. remove$1(component.element(), 'disabled');
  7740. };
  7741. var ariaIsDisabled = function (component) {
  7742. return get$1(component.element(), 'aria-disabled') === 'true';
  7743. };
  7744. var ariaDisable = function (component) {
  7745. set(component.element(), 'aria-disabled', 'true');
  7746. };
  7747. var ariaEnable = function (component) {
  7748. set(component.element(), 'aria-disabled', 'false');
  7749. };
  7750. var disable = function (component, disableConfig, disableState) {
  7751. disableConfig.disableClass.each(function (disableClass) {
  7752. add$2(component.element(), disableClass);
  7753. });
  7754. var f = hasNative(component) ? nativeDisable : ariaDisable;
  7755. f(component);
  7756. };
  7757. var enable = function (component, disableConfig, disableState) {
  7758. disableConfig.disableClass.each(function (disableClass) {
  7759. remove$4(component.element(), disableClass);
  7760. });
  7761. var f = hasNative(component) ? nativeEnable : ariaEnable;
  7762. f(component);
  7763. };
  7764. var isDisabled = function (component) {
  7765. return hasNative(component) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  7766. };
  7767. var set$7 = function (component, disableConfig, disableState, disabled) {
  7768. var f = disabled ? disable : enable;
  7769. f(component, disableConfig, disableState);
  7770. };
  7771. var DisableApis = /*#__PURE__*/Object.freeze({
  7772. enable: enable,
  7773. disable: disable,
  7774. isDisabled: isDisabled,
  7775. onLoad: onLoad$5,
  7776. set: set$7
  7777. });
  7778. var exhibit$4 = function (base, disableConfig, disableState) {
  7779. return nu$5({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  7780. };
  7781. var events$7 = function (disableConfig, disableState) {
  7782. return derive([
  7783. abort(execute(), function (component, simulatedEvent) {
  7784. return isDisabled(component);
  7785. }),
  7786. loadEvent(disableConfig, disableState, onLoad$5)
  7787. ]);
  7788. };
  7789. var ActiveDisable = /*#__PURE__*/Object.freeze({
  7790. exhibit: exhibit$4,
  7791. events: events$7
  7792. });
  7793. var DisableSchema = [
  7794. defaulted$1('disabled', false),
  7795. option('disableClass')
  7796. ];
  7797. var Disabling = create$1({
  7798. fields: DisableSchema,
  7799. name: 'disabling',
  7800. active: ActiveDisable,
  7801. apis: DisableApis
  7802. });
  7803. var owner$1 = 'form';
  7804. var schema$9 = [field$1('formBehaviours', [Representing])];
  7805. var getPartName = function (name) {
  7806. return '<alloy.field.' + name + '>';
  7807. };
  7808. var sketch$5 = function (fSpec) {
  7809. var parts = function () {
  7810. var record = [];
  7811. var field = function (name, config) {
  7812. record.push(name);
  7813. return generateOne(owner$1, getPartName(name), config);
  7814. };
  7815. return {
  7816. field: field,
  7817. record: function () {
  7818. return record;
  7819. }
  7820. };
  7821. }();
  7822. var spec = fSpec(parts);
  7823. var partNames = parts.record();
  7824. var fieldParts = map$1(partNames, function (n) {
  7825. return required({
  7826. name: n,
  7827. pname: getPartName(n)
  7828. });
  7829. });
  7830. return composite(owner$1, schema$9, fieldParts, make, spec);
  7831. };
  7832. var toResult$1 = function (o, e) {
  7833. return o.fold(function () {
  7834. return Result.error(e);
  7835. }, Result.value);
  7836. };
  7837. var make = function (detail, components, spec) {
  7838. return {
  7839. 'uid': detail.uid,
  7840. 'dom': detail.dom,
  7841. 'components': components,
  7842. 'behaviours': augment(detail.formBehaviours, [Representing.config({
  7843. store: {
  7844. mode: 'manual',
  7845. getValue: function (form) {
  7846. var resPs = getAllParts(form, detail);
  7847. return map(resPs, function (resPThunk, pName) {
  7848. return resPThunk().bind(function (v) {
  7849. var opt = Composing.getCurrent(v);
  7850. return toResult$1(opt, 'missing current');
  7851. }).map(Representing.getValue);
  7852. });
  7853. },
  7854. setValue: function (form, values) {
  7855. each(values, function (newValue, key) {
  7856. getPart(form, detail, key).each(function (wrapper) {
  7857. Composing.getCurrent(wrapper).each(function (field) {
  7858. Representing.setValue(field, newValue);
  7859. });
  7860. });
  7861. });
  7862. }
  7863. }
  7864. })]),
  7865. 'apis': {
  7866. getField: function (form, key) {
  7867. return getPart(form, detail, key).bind(Composing.getCurrent);
  7868. }
  7869. }
  7870. };
  7871. };
  7872. var Form = {
  7873. getField: makeApi(function (apis, component, key) {
  7874. return apis.getField(component, key);
  7875. }),
  7876. sketch: sketch$5
  7877. };
  7878. var api$2 = function () {
  7879. var subject = Cell(Option.none());
  7880. var revoke = function () {
  7881. subject.get().each(function (s) {
  7882. s.destroy();
  7883. });
  7884. };
  7885. var clear = function () {
  7886. revoke();
  7887. subject.set(Option.none());
  7888. };
  7889. var set = function (s) {
  7890. revoke();
  7891. subject.set(Option.some(s));
  7892. };
  7893. var run = function (f) {
  7894. subject.get().each(f);
  7895. };
  7896. var isSet = function () {
  7897. return subject.get().isSome();
  7898. };
  7899. return {
  7900. clear: clear,
  7901. isSet: isSet,
  7902. set: set,
  7903. run: run
  7904. };
  7905. };
  7906. var value$3 = function () {
  7907. var subject = Cell(Option.none());
  7908. var clear = function () {
  7909. subject.set(Option.none());
  7910. };
  7911. var set = function (s) {
  7912. subject.set(Option.some(s));
  7913. };
  7914. var on = function (f) {
  7915. subject.get().each(f);
  7916. };
  7917. var isSet = function () {
  7918. return subject.get().isSome();
  7919. };
  7920. return {
  7921. clear: clear,
  7922. set: set,
  7923. isSet: isSet,
  7924. on: on
  7925. };
  7926. };
  7927. var SWIPING_LEFT = 1;
  7928. var SWIPING_RIGHT = -1;
  7929. var SWIPING_NONE = 0;
  7930. var init$2 = function (xValue) {
  7931. return {
  7932. xValue: xValue,
  7933. points: []
  7934. };
  7935. };
  7936. var move$1 = function (model, xValue) {
  7937. if (xValue === model.xValue) {
  7938. return model;
  7939. }
  7940. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7941. var newPoint = {
  7942. direction: currentDirection,
  7943. xValue: xValue
  7944. };
  7945. var priorPoints = function () {
  7946. if (model.points.length === 0) {
  7947. return [];
  7948. } else {
  7949. var prev = model.points[model.points.length - 1];
  7950. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7951. }
  7952. }();
  7953. return {
  7954. xValue: xValue,
  7955. points: priorPoints.concat([newPoint])
  7956. };
  7957. };
  7958. var complete = function (model) {
  7959. if (model.points.length === 0) {
  7960. return SWIPING_NONE;
  7961. } else {
  7962. var firstDirection = model.points[0].direction;
  7963. var lastDirection = model.points[model.points.length - 1].direction;
  7964. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7965. }
  7966. };
  7967. var SwipingModel = {
  7968. init: init$2,
  7969. move: move$1,
  7970. complete: complete
  7971. };
  7972. var sketch$6 = function (rawSpec) {
  7973. var navigateEvent = 'navigateEvent';
  7974. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7975. var formAdhocEvents = 'form-events';
  7976. var schema = objOf([
  7977. strict$1('fields'),
  7978. defaulted$1('maxFieldIndex', rawSpec.fields.length - 1),
  7979. strict$1('onExecute'),
  7980. strict$1('getInitialValue'),
  7981. state$1('state', function () {
  7982. return {
  7983. dialogSwipeState: value$3(),
  7984. currentScreen: Cell(0)
  7985. };
  7986. })
  7987. ]);
  7988. var spec$1 = asRawOrDie('SerialisedDialog', schema, rawSpec);
  7989. var navigationButton = function (direction, directionName, enabled) {
  7990. return Button.sketch({
  7991. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7992. action: function (button) {
  7993. emitWith(button, navigateEvent, { direction: direction });
  7994. },
  7995. buttonBehaviours: derive$1([Disabling.config({
  7996. disableClass: Styles.resolve('toolbar-navigation-disabled'),
  7997. disabled: !enabled
  7998. })])
  7999. });
  8000. };
  8001. var reposition = function (dialog, message) {
  8002. descendant$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
  8003. set$3(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  8004. });
  8005. };
  8006. var navigate = function (dialog, direction) {
  8007. var screens = descendants(dialog.element(), '.' + Styles.resolve('serialised-dialog-screen'));
  8008. descendant$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
  8009. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  8010. getRaw(parent, 'left').each(function (left) {
  8011. var currentLeft = parseInt(left, 10);
  8012. var w = get$7(screens[0]);
  8013. set$3(parent, 'left', currentLeft - direction * w + 'px');
  8014. });
  8015. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  8016. }
  8017. });
  8018. };
  8019. var focusInput = function (dialog) {
  8020. var inputs = descendants(dialog.element(), 'input');
  8021. var optInput = Option.from(inputs[spec$1.state.currentScreen.get()]);
  8022. optInput.each(function (input) {
  8023. dialog.getSystem().getByDom(input).each(function (inputComp) {
  8024. dispatchFocus(dialog, inputComp.element());
  8025. });
  8026. });
  8027. var dotitems = memDots.get(dialog);
  8028. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  8029. };
  8030. var resetState = function () {
  8031. spec$1.state.currentScreen.set(0);
  8032. spec$1.state.dialogSwipeState.clear();
  8033. };
  8034. var memForm = record(Form.sketch(function (parts) {
  8035. return {
  8036. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  8037. components: [Container.sketch({
  8038. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  8039. components: map$1(spec$1.fields, function (field, i) {
  8040. return i <= spec$1.maxFieldIndex ? Container.sketch({
  8041. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  8042. components: [
  8043. navigationButton(-1, 'previous', i > 0),
  8044. parts.field(field.name, field.spec),
  8045. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  8046. ]
  8047. }) : parts.field(field.name, field.spec);
  8048. })
  8049. })],
  8050. formBehaviours: derive$1([
  8051. Receivers.orientation(function (dialog, message) {
  8052. reposition(dialog, message);
  8053. }),
  8054. Keying.config({
  8055. mode: 'special',
  8056. focusIn: function (dialog) {
  8057. focusInput(dialog);
  8058. },
  8059. onTab: function (dialog) {
  8060. navigate(dialog, +1);
  8061. return Option.some(true);
  8062. },
  8063. onShiftTab: function (dialog) {
  8064. navigate(dialog, -1);
  8065. return Option.some(true);
  8066. }
  8067. }),
  8068. config(formAdhocEvents, [
  8069. runOnAttached(function (dialog, simulatedEvent) {
  8070. resetState();
  8071. var dotitems = memDots.get(dialog);
  8072. Highlighting.highlightFirst(dotitems);
  8073. spec$1.getInitialValue(dialog).each(function (v) {
  8074. Representing.setValue(dialog, v);
  8075. });
  8076. }),
  8077. runOnExecute(spec$1.onExecute),
  8078. run(transitionend(), function (dialog, simulatedEvent) {
  8079. var event = simulatedEvent.event();
  8080. if (event.raw().propertyName === 'left') {
  8081. focusInput(dialog);
  8082. }
  8083. }),
  8084. run(navigateEvent, function (dialog, simulatedEvent) {
  8085. var event = simulatedEvent.event();
  8086. var direction = event.direction();
  8087. navigate(dialog, direction);
  8088. })
  8089. ])
  8090. ])
  8091. };
  8092. }));
  8093. var memDots = record({
  8094. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  8095. behaviours: derive$1([Highlighting.config({
  8096. highlightClass: Styles.resolve('dot-active'),
  8097. itemClass: Styles.resolve('dot-item')
  8098. })]),
  8099. components: bind(spec$1.fields, function (_f, i) {
  8100. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  8101. })
  8102. });
  8103. return {
  8104. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  8105. components: [
  8106. memForm.asSpec(),
  8107. memDots.asSpec()
  8108. ],
  8109. behaviours: derive$1([
  8110. Keying.config({
  8111. mode: 'special',
  8112. focusIn: function (wrapper) {
  8113. var form = memForm.get(wrapper);
  8114. Keying.focusIn(form);
  8115. }
  8116. }),
  8117. config(wrapperAdhocEvents, [
  8118. run(touchstart(), function (wrapper, simulatedEvent) {
  8119. var event = simulatedEvent.event();
  8120. spec$1.state.dialogSwipeState.set(SwipingModel.init(event.raw().touches[0].clientX));
  8121. }),
  8122. run(touchmove(), function (wrapper, simulatedEvent) {
  8123. var event = simulatedEvent.event();
  8124. spec$1.state.dialogSwipeState.on(function (state) {
  8125. simulatedEvent.event().prevent();
  8126. spec$1.state.dialogSwipeState.set(SwipingModel.move(state, event.raw().touches[0].clientX));
  8127. });
  8128. }),
  8129. run(touchend(), function (wrapper) {
  8130. spec$1.state.dialogSwipeState.on(function (state) {
  8131. var dialog = memForm.get(wrapper);
  8132. var direction = -1 * SwipingModel.complete(state);
  8133. navigate(dialog, direction);
  8134. });
  8135. })
  8136. ])
  8137. ])
  8138. };
  8139. };
  8140. var getGroups = cached(function (realm, editor) {
  8141. return [{
  8142. label: 'the link group',
  8143. items: [sketch$6({
  8144. fields: [
  8145. field$2('url', 'Type or paste URL'),
  8146. field$2('text', 'Link text'),
  8147. field$2('title', 'Link title'),
  8148. field$2('target', 'Link target'),
  8149. hidden('link')
  8150. ],
  8151. maxFieldIndex: [
  8152. 'url',
  8153. 'text',
  8154. 'title',
  8155. 'target'
  8156. ].length - 1,
  8157. getInitialValue: function () {
  8158. return Option.some(LinkBridge.getInfo(editor));
  8159. },
  8160. onExecute: function (dialog) {
  8161. var info = Representing.getValue(dialog);
  8162. LinkBridge.applyInfo(editor, info);
  8163. realm.restoreToolbar();
  8164. editor.focus();
  8165. }
  8166. })]
  8167. }];
  8168. });
  8169. var sketch$7 = function (realm, editor) {
  8170. return Buttons.forToolbarStateAction(editor, 'link', 'link', function () {
  8171. var groups = getGroups(realm, editor);
  8172. realm.setContextToolbar(groups);
  8173. RangePreserver.forAndroid(editor, function () {
  8174. realm.focusToolbar();
  8175. });
  8176. LinkBridge.query(editor).each(function (link) {
  8177. editor.selection.select(link.dom());
  8178. });
  8179. });
  8180. };
  8181. var DefaultStyleFormats = [
  8182. {
  8183. title: 'Headings',
  8184. items: [
  8185. {
  8186. title: 'Heading 1',
  8187. format: 'h1'
  8188. },
  8189. {
  8190. title: 'Heading 2',
  8191. format: 'h2'
  8192. },
  8193. {
  8194. title: 'Heading 3',
  8195. format: 'h3'
  8196. },
  8197. {
  8198. title: 'Heading 4',
  8199. format: 'h4'
  8200. },
  8201. {
  8202. title: 'Heading 5',
  8203. format: 'h5'
  8204. },
  8205. {
  8206. title: 'Heading 6',
  8207. format: 'h6'
  8208. }
  8209. ]
  8210. },
  8211. {
  8212. title: 'Inline',
  8213. items: [
  8214. {
  8215. title: 'Bold',
  8216. icon: 'bold',
  8217. format: 'bold'
  8218. },
  8219. {
  8220. title: 'Italic',
  8221. icon: 'italic',
  8222. format: 'italic'
  8223. },
  8224. {
  8225. title: 'Underline',
  8226. icon: 'underline',
  8227. format: 'underline'
  8228. },
  8229. {
  8230. title: 'Strikethrough',
  8231. icon: 'strikethrough',
  8232. format: 'strikethrough'
  8233. },
  8234. {
  8235. title: 'Superscript',
  8236. icon: 'superscript',
  8237. format: 'superscript'
  8238. },
  8239. {
  8240. title: 'Subscript',
  8241. icon: 'subscript',
  8242. format: 'subscript'
  8243. },
  8244. {
  8245. title: 'Code',
  8246. icon: 'code',
  8247. format: 'code'
  8248. }
  8249. ]
  8250. },
  8251. {
  8252. title: 'Blocks',
  8253. items: [
  8254. {
  8255. title: 'Paragraph',
  8256. format: 'p'
  8257. },
  8258. {
  8259. title: 'Blockquote',
  8260. format: 'blockquote'
  8261. },
  8262. {
  8263. title: 'Div',
  8264. format: 'div'
  8265. },
  8266. {
  8267. title: 'Pre',
  8268. format: 'pre'
  8269. }
  8270. ]
  8271. },
  8272. {
  8273. title: 'Alignment',
  8274. items: [
  8275. {
  8276. title: 'Left',
  8277. icon: 'alignleft',
  8278. format: 'alignleft'
  8279. },
  8280. {
  8281. title: 'Center',
  8282. icon: 'aligncenter',
  8283. format: 'aligncenter'
  8284. },
  8285. {
  8286. title: 'Right',
  8287. icon: 'alignright',
  8288. format: 'alignright'
  8289. },
  8290. {
  8291. title: 'Justify',
  8292. icon: 'alignjustify',
  8293. format: 'alignjustify'
  8294. }
  8295. ]
  8296. }
  8297. ];
  8298. var isRecursive = function (component, originator, target) {
  8299. return eq(originator, component.element()) && !eq(originator, target);
  8300. };
  8301. var events$8 = derive([can(focus(), function (component, simulatedEvent) {
  8302. var originator = simulatedEvent.event().originator();
  8303. var target = simulatedEvent.event().target();
  8304. if (isRecursive(component, originator, target)) {
  8305. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  8306. return false;
  8307. } else {
  8308. return true;
  8309. }
  8310. })]);
  8311. var DefaultEvents = /*#__PURE__*/Object.freeze({
  8312. events: events$8
  8313. });
  8314. var make$1 = identity;
  8315. var NoContextApi = function (getComp) {
  8316. var fail = function (event) {
  8317. return function () {
  8318. throw new Error('The component must be in a context to send: ' + event + '\n' + element(getComp().element()) + ' is not in context.');
  8319. };
  8320. };
  8321. return {
  8322. debugInfo: constant('fake'),
  8323. triggerEvent: fail('triggerEvent'),
  8324. triggerFocus: fail('triggerFocus'),
  8325. triggerEscape: fail('triggerEscape'),
  8326. build: fail('build'),
  8327. addToWorld: fail('addToWorld'),
  8328. removeFromWorld: fail('removeFromWorld'),
  8329. addToGui: fail('addToGui'),
  8330. removeFromGui: fail('removeFromGui'),
  8331. getByUid: fail('getByUid'),
  8332. getByDom: fail('getByDom'),
  8333. broadcast: fail('broadcast'),
  8334. broadcastOn: fail('broadcastOn'),
  8335. broadcastEvent: fail('broadcastEvent'),
  8336. isConnected: constant(false)
  8337. };
  8338. };
  8339. var singleton = NoContextApi();
  8340. var generateFrom = function (spec, all) {
  8341. var schema = map$1(all, function (a) {
  8342. return optionObjOf(a.name(), [
  8343. strict$1('config'),
  8344. defaulted$1('state', NoState)
  8345. ]);
  8346. });
  8347. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  8348. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + Json.stringify(spec, null, 2));
  8349. }, function (v) {
  8350. return v;
  8351. });
  8352. return {
  8353. list: all,
  8354. data: map(validated, function (optBlobThunk) {
  8355. var optBlob = optBlobThunk;
  8356. var output = optBlob.map(function (blob) {
  8357. return {
  8358. config: blob.config,
  8359. state: blob.state.init(blob.config)
  8360. };
  8361. });
  8362. return function () {
  8363. return output;
  8364. };
  8365. })
  8366. };
  8367. };
  8368. var getBehaviours = function (bData) {
  8369. return bData.list;
  8370. };
  8371. var getData = function (bData) {
  8372. return bData.data;
  8373. };
  8374. var byInnerKey = function (data, tuple) {
  8375. var r = {};
  8376. each(data, function (detail, key) {
  8377. each(detail, function (value, indexKey) {
  8378. var chain = readOr$1(indexKey, [])(r);
  8379. r[indexKey] = chain.concat([tuple(key, value)]);
  8380. });
  8381. });
  8382. return r;
  8383. };
  8384. var combine$1 = function (info, baseMod, behaviours, base) {
  8385. var modsByBehaviour = __assign({}, baseMod);
  8386. each$1(behaviours, function (behaviour) {
  8387. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  8388. });
  8389. var nameAndMod = function (name, modification) {
  8390. return {
  8391. name: name,
  8392. modification: modification
  8393. };
  8394. };
  8395. var byAspect = byInnerKey(modsByBehaviour, nameAndMod);
  8396. var combineObjects = function (objects) {
  8397. return foldr(objects, function (b, a) {
  8398. return __assign({}, a.modification, b);
  8399. }, {});
  8400. };
  8401. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  8402. return a.modification.concat(b);
  8403. }, []);
  8404. var combinedAttributes = combineObjects(byAspect.attributes);
  8405. var combinedStyles = combineObjects(byAspect.styles);
  8406. return nu$5({
  8407. classes: combinedClasses,
  8408. attributes: combinedAttributes,
  8409. styles: combinedStyles
  8410. });
  8411. };
  8412. var sortKeys = function (label, keyName, array, order) {
  8413. var sliced = array.slice(0);
  8414. try {
  8415. var sorted = sliced.sort(function (a, b) {
  8416. var aKey = a[keyName]();
  8417. var bKey = b[keyName]();
  8418. var aIndex = order.indexOf(aKey);
  8419. var bIndex = order.indexOf(bKey);
  8420. if (aIndex === -1) {
  8421. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + Json.stringify(order, null, 2));
  8422. }
  8423. if (bIndex === -1) {
  8424. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + Json.stringify(order, null, 2));
  8425. }
  8426. if (aIndex < bIndex) {
  8427. return -1;
  8428. } else if (bIndex < aIndex) {
  8429. return 1;
  8430. } else {
  8431. return 0;
  8432. }
  8433. });
  8434. return Result.value(sorted);
  8435. } catch (err) {
  8436. return Result.error([err]);
  8437. }
  8438. };
  8439. var uncurried = function (handler, purpose) {
  8440. return {
  8441. handler: handler,
  8442. purpose: constant(purpose)
  8443. };
  8444. };
  8445. var curried = function (handler, purpose) {
  8446. return {
  8447. cHandler: handler,
  8448. purpose: constant(purpose)
  8449. };
  8450. };
  8451. var curryArgs = function (descHandler, extraArgs) {
  8452. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  8453. };
  8454. var getCurried = function (descHandler) {
  8455. return descHandler.cHandler;
  8456. };
  8457. var behaviourTuple = function (name, handler) {
  8458. return {
  8459. name: constant(name),
  8460. handler: constant(handler)
  8461. };
  8462. };
  8463. var nameToHandlers = function (behaviours, info) {
  8464. var r = {};
  8465. each$1(behaviours, function (behaviour) {
  8466. r[behaviour.name()] = behaviour.handlers(info);
  8467. });
  8468. return r;
  8469. };
  8470. var groupByEvents = function (info, behaviours, base) {
  8471. var behaviourEvents = __assign({}, base, nameToHandlers(behaviours, info));
  8472. return byInnerKey(behaviourEvents, behaviourTuple);
  8473. };
  8474. var combine$2 = function (info, eventOrder, behaviours, base) {
  8475. var byEventName = groupByEvents(info, behaviours, base);
  8476. return combineGroups(byEventName, eventOrder);
  8477. };
  8478. var assemble = function (rawHandler) {
  8479. var handler = read(rawHandler);
  8480. return function (component, simulatedEvent) {
  8481. var rest = [];
  8482. for (var _i = 2; _i < arguments.length; _i++) {
  8483. rest[_i - 2] = arguments[_i];
  8484. }
  8485. var args = [
  8486. component,
  8487. simulatedEvent
  8488. ].concat(rest);
  8489. if (handler.abort.apply(undefined, args)) {
  8490. simulatedEvent.stop();
  8491. } else if (handler.can.apply(undefined, args)) {
  8492. handler.run.apply(undefined, args);
  8493. }
  8494. };
  8495. };
  8496. var missingOrderError = function (eventName, tuples) {
  8497. 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) {
  8498. return c.name();
  8499. }), null, 2)]);
  8500. };
  8501. var fuse$1 = function (tuples, eventOrder, eventName) {
  8502. var order = eventOrder[eventName];
  8503. if (!order) {
  8504. return missingOrderError(eventName, tuples);
  8505. } else {
  8506. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  8507. var handlers = map$1(sortedTuples, function (tuple) {
  8508. return tuple.handler();
  8509. });
  8510. return fuse(handlers);
  8511. });
  8512. }
  8513. };
  8514. var combineGroups = function (byEventName, eventOrder) {
  8515. var r = mapToArray(byEventName, function (tuples, eventName) {
  8516. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  8517. return combined.map(function (handler) {
  8518. var assembled = assemble(handler);
  8519. var purpose = tuples.length > 1 ? filter(eventOrder, function (o) {
  8520. return contains(tuples, function (t) {
  8521. return t.name() === o;
  8522. });
  8523. }).join(' > ') : tuples[0].name();
  8524. return wrap$1(eventName, uncurried(assembled, purpose));
  8525. });
  8526. });
  8527. return consolidate(r, {});
  8528. };
  8529. var toInfo = function (spec) {
  8530. return asRaw('custom.definition', objOf([
  8531. field('dom', 'dom', strict(), objOf([
  8532. strict$1('tag'),
  8533. defaulted$1('styles', {}),
  8534. defaulted$1('classes', []),
  8535. defaulted$1('attributes', {}),
  8536. option('value'),
  8537. option('innerHtml')
  8538. ])),
  8539. strict$1('components'),
  8540. strict$1('uid'),
  8541. defaulted$1('events', {}),
  8542. defaulted$1('apis', {}),
  8543. field('eventOrder', 'eventOrder', mergeWith({
  8544. 'alloy.execute': [
  8545. 'disabling',
  8546. 'alloy.base.behaviour',
  8547. 'toggling',
  8548. 'typeaheadevents'
  8549. ],
  8550. 'alloy.focus': [
  8551. 'alloy.base.behaviour',
  8552. 'focusing',
  8553. 'keying'
  8554. ],
  8555. 'alloy.system.init': [
  8556. 'alloy.base.behaviour',
  8557. 'disabling',
  8558. 'toggling',
  8559. 'representing'
  8560. ],
  8561. 'input': [
  8562. 'alloy.base.behaviour',
  8563. 'representing',
  8564. 'streaming',
  8565. 'invalidating'
  8566. ],
  8567. 'alloy.system.detached': [
  8568. 'alloy.base.behaviour',
  8569. 'representing',
  8570. 'item-events',
  8571. 'tooltipping'
  8572. ],
  8573. 'mousedown': [
  8574. 'focusing',
  8575. 'alloy.base.behaviour',
  8576. 'item-type-events'
  8577. ],
  8578. 'mouseover': [
  8579. 'item-type-events',
  8580. 'tooltipping'
  8581. ]
  8582. }), anyValue$1()),
  8583. option('domModification')
  8584. ]), spec);
  8585. };
  8586. var toDefinition = function (detail) {
  8587. return __assign({}, detail.dom, {
  8588. uid: detail.uid,
  8589. domChildren: map$1(detail.components, function (comp) {
  8590. return comp.element();
  8591. })
  8592. });
  8593. };
  8594. var toModification = function (detail) {
  8595. return detail.domModification.fold(function () {
  8596. return nu$5({});
  8597. }, nu$5);
  8598. };
  8599. var toEvents = function (info) {
  8600. return info.events;
  8601. };
  8602. var add$3 = function (element, classes) {
  8603. each$1(classes, function (x) {
  8604. add$2(element, x);
  8605. });
  8606. };
  8607. var remove$6 = function (element, classes) {
  8608. each$1(classes, function (x) {
  8609. remove$4(element, x);
  8610. });
  8611. };
  8612. var renderToDom = function (definition) {
  8613. var subject = Element.fromTag(definition.tag);
  8614. setAll(subject, definition.attributes);
  8615. add$3(subject, definition.classes);
  8616. setAll$1(subject, definition.styles);
  8617. definition.innerHtml.each(function (html) {
  8618. return set$1(subject, html);
  8619. });
  8620. var children = definition.domChildren;
  8621. append$1(subject, children);
  8622. definition.value.each(function (value) {
  8623. set$6(subject, value);
  8624. });
  8625. if (!definition.uid) {
  8626. debugger;
  8627. }
  8628. writeOnly(subject, definition.uid);
  8629. return subject;
  8630. };
  8631. var getBehaviours$1 = function (spec) {
  8632. var behaviours = readOr$1('behaviours', {})(spec);
  8633. var keys$1 = filter(keys(behaviours), function (k) {
  8634. return behaviours[k] !== undefined;
  8635. });
  8636. return map$1(keys$1, function (k) {
  8637. return behaviours[k].me;
  8638. });
  8639. };
  8640. var generateFrom$1 = function (spec, all) {
  8641. return generateFrom(spec, all);
  8642. };
  8643. var generate$4 = function (spec) {
  8644. var all = getBehaviours$1(spec);
  8645. return generateFrom$1(spec, all);
  8646. };
  8647. var getDomDefinition = function (info, bList, bData) {
  8648. var definition = toDefinition(info);
  8649. var infoModification = toModification(info);
  8650. var baseModification = { 'alloy.base.modification': infoModification };
  8651. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  8652. return merge$1(definition, modification);
  8653. };
  8654. var getEvents = function (info, bList, bData) {
  8655. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  8656. return combine$2(bData, info.eventOrder, bList, baseEvents).getOrDie();
  8657. };
  8658. var build = function (spec) {
  8659. var getMe = function () {
  8660. return me;
  8661. };
  8662. var systemApi = Cell(singleton);
  8663. var info = getOrDie$1(toInfo(spec));
  8664. var bBlob = generate$4(spec);
  8665. var bList = getBehaviours(bBlob);
  8666. var bData = getData(bBlob);
  8667. var modDefinition = getDomDefinition(info, bList, bData);
  8668. var item = renderToDom(modDefinition);
  8669. var events = getEvents(info, bList, bData);
  8670. var subcomponents = Cell(info.components);
  8671. var connect = function (newApi) {
  8672. systemApi.set(newApi);
  8673. };
  8674. var disconnect = function () {
  8675. systemApi.set(NoContextApi(getMe));
  8676. };
  8677. var syncComponents = function () {
  8678. var children$1 = children(item);
  8679. var subs = bind(children$1, function (child) {
  8680. return systemApi.get().getByDom(child).fold(function () {
  8681. return [];
  8682. }, function (c) {
  8683. return [c];
  8684. });
  8685. });
  8686. subcomponents.set(subs);
  8687. };
  8688. var config = function (behaviour) {
  8689. var b = bData;
  8690. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  8691. throw new Error('Could not find ' + behaviour.name() + ' in ' + Json.stringify(spec, null, 2));
  8692. };
  8693. return f();
  8694. };
  8695. var hasConfigured = function (behaviour) {
  8696. return isFunction(bData[behaviour.name()]);
  8697. };
  8698. var getApis = function () {
  8699. return info.apis;
  8700. };
  8701. var readState = function (behaviourName) {
  8702. return bData[behaviourName]().map(function (b) {
  8703. return b.state.readState();
  8704. }).getOr('not enabled');
  8705. };
  8706. var me = {
  8707. getSystem: systemApi.get,
  8708. config: config,
  8709. hasConfigured: hasConfigured,
  8710. spec: constant(spec),
  8711. readState: readState,
  8712. getApis: getApis,
  8713. connect: connect,
  8714. disconnect: disconnect,
  8715. element: constant(item),
  8716. syncComponents: syncComponents,
  8717. components: subcomponents.get,
  8718. events: constant(events)
  8719. };
  8720. return me;
  8721. };
  8722. var buildSubcomponents = function (spec) {
  8723. var components = readOr$1('components', [])(spec);
  8724. return map$1(components, build$1);
  8725. };
  8726. var buildFromSpec = function (userSpec) {
  8727. var _a = make$1(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  8728. var components = buildSubcomponents(spec);
  8729. var completeSpec = __assign({}, spec, {
  8730. events: __assign({}, DefaultEvents, specEvents),
  8731. components: components
  8732. });
  8733. return Result.value(build(completeSpec));
  8734. };
  8735. var text = function (textContent) {
  8736. var element = Element.fromText(textContent);
  8737. return external({ element: element });
  8738. };
  8739. var external = function (spec) {
  8740. var extSpec = asRawOrDie('external.component', objOfOnly([
  8741. strict$1('element'),
  8742. option('uid')
  8743. ]), spec);
  8744. var systemApi = Cell(NoContextApi());
  8745. var connect = function (newApi) {
  8746. systemApi.set(newApi);
  8747. };
  8748. var disconnect = function () {
  8749. systemApi.set(NoContextApi(function () {
  8750. return me;
  8751. }));
  8752. };
  8753. extSpec.uid.each(function (uid) {
  8754. writeOnly(extSpec.element, uid);
  8755. });
  8756. var me = {
  8757. getSystem: systemApi.get,
  8758. config: Option.none,
  8759. hasConfigured: constant(false),
  8760. connect: connect,
  8761. disconnect: disconnect,
  8762. getApis: function () {
  8763. return {};
  8764. },
  8765. element: constant(extSpec.element),
  8766. spec: constant(spec),
  8767. readState: constant('No state'),
  8768. syncComponents: noop,
  8769. components: constant([]),
  8770. events: constant({})
  8771. };
  8772. return premade(me);
  8773. };
  8774. var uids = generate$3;
  8775. var build$1 = function (spec) {
  8776. return getPremade(spec).fold(function () {
  8777. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  8778. return buildFromSpec(userSpecWithUid).getOrDie();
  8779. }, function (prebuilt) {
  8780. return prebuilt;
  8781. });
  8782. };
  8783. var premade$1 = premade;
  8784. var hoverEvent = 'alloy.item-hover';
  8785. var focusEvent = 'alloy.item-focus';
  8786. var onHover = function (item) {
  8787. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  8788. if (!Focusing.isFocused(item)) {
  8789. Focusing.focus(item);
  8790. }
  8791. emitWith(item, hoverEvent, { item: item });
  8792. }
  8793. };
  8794. var onFocus = function (item) {
  8795. emitWith(item, focusEvent, { item: item });
  8796. };
  8797. var hover = constant(hoverEvent);
  8798. var focus$3 = constant(focusEvent);
  8799. var builder = function (detail) {
  8800. return {
  8801. dom: detail.dom,
  8802. domModification: __assign({}, detail.domModification, { attributes: __assign({ 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem' }, detail.domModification.attributes, { 'aria-haspopup': detail.hasSubmenu }, detail.hasSubmenu ? { 'aria-expanded': false } : {}) }),
  8803. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  8804. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  8805. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  8806. }),
  8807. Focusing.config({
  8808. ignore: detail.ignoreFocus,
  8809. stopMousedown: detail.ignoreFocus,
  8810. onFocus: function (component) {
  8811. onFocus(component);
  8812. }
  8813. }),
  8814. Keying.config({ mode: 'execution' }),
  8815. Representing.config({
  8816. store: {
  8817. mode: 'memory',
  8818. initialValue: detail.data
  8819. }
  8820. }),
  8821. config('item-type-events', [
  8822. run(tapOrClick(), emitExecute),
  8823. cutter(mousedown()),
  8824. run(mouseover(), onHover),
  8825. run(focusItem(), Focusing.focus)
  8826. ])
  8827. ]),
  8828. components: detail.components,
  8829. eventOrder: detail.eventOrder
  8830. };
  8831. };
  8832. var schema$a = [
  8833. strict$1('data'),
  8834. strict$1('components'),
  8835. strict$1('dom'),
  8836. defaulted$1('hasSubmenu', false),
  8837. option('toggling'),
  8838. SketchBehaviours.field('itemBehaviours', [
  8839. Toggling,
  8840. Focusing,
  8841. Keying,
  8842. Representing
  8843. ]),
  8844. defaulted$1('ignoreFocus', false),
  8845. defaulted$1('domModification', {}),
  8846. output('builder', builder),
  8847. defaulted$1('eventOrder', {})
  8848. ];
  8849. var builder$1 = function (detail) {
  8850. return {
  8851. dom: detail.dom,
  8852. components: detail.components,
  8853. events: derive([stopper(focusItem())])
  8854. };
  8855. };
  8856. var schema$b = [
  8857. strict$1('dom'),
  8858. strict$1('components'),
  8859. output('builder', builder$1)
  8860. ];
  8861. var owner$2 = function () {
  8862. return 'item-widget';
  8863. };
  8864. var parts = constant([required({
  8865. name: 'widget',
  8866. overrides: function (detail) {
  8867. return {
  8868. behaviours: derive$1([Representing.config({
  8869. store: {
  8870. mode: 'manual',
  8871. getValue: function (component) {
  8872. return detail.data;
  8873. },
  8874. setValue: function () {
  8875. }
  8876. }
  8877. })])
  8878. };
  8879. }
  8880. })]);
  8881. var builder$2 = function (detail) {
  8882. var subs = substitutes(owner$2(), detail, parts());
  8883. var components$1 = components(owner$2(), detail, subs.internals());
  8884. var focusWidget = function (component) {
  8885. return getPart(component, detail, 'widget').map(function (widget) {
  8886. Keying.focusIn(widget);
  8887. return widget;
  8888. });
  8889. };
  8890. var onHorizontalArrow = function (component, simulatedEvent) {
  8891. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  8892. if (detail.autofocus) {
  8893. simulatedEvent.setSource(component.element());
  8894. return Option.none();
  8895. } else {
  8896. return Option.none();
  8897. }
  8898. }();
  8899. };
  8900. return {
  8901. dom: detail.dom,
  8902. components: components$1,
  8903. domModification: detail.domModification,
  8904. events: derive([
  8905. runOnExecute(function (component, simulatedEvent) {
  8906. focusWidget(component).each(function (widget) {
  8907. simulatedEvent.stop();
  8908. });
  8909. }),
  8910. run(mouseover(), onHover),
  8911. run(focusItem(), function (component, simulatedEvent) {
  8912. if (detail.autofocus) {
  8913. focusWidget(component);
  8914. } else {
  8915. Focusing.focus(component);
  8916. }
  8917. })
  8918. ]),
  8919. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  8920. Representing.config({
  8921. store: {
  8922. mode: 'memory',
  8923. initialValue: detail.data
  8924. }
  8925. }),
  8926. Focusing.config({
  8927. ignore: detail.ignoreFocus,
  8928. onFocus: function (component) {
  8929. onFocus(component);
  8930. }
  8931. }),
  8932. Keying.config({
  8933. mode: 'special',
  8934. focusIn: detail.autofocus ? function (component) {
  8935. focusWidget(component);
  8936. } : revoke(),
  8937. onLeft: onHorizontalArrow,
  8938. onRight: onHorizontalArrow,
  8939. onEscape: function (component, simulatedEvent) {
  8940. if (!Focusing.isFocused(component) && !detail.autofocus) {
  8941. Focusing.focus(component);
  8942. return Option.some(true);
  8943. } else if (detail.autofocus) {
  8944. simulatedEvent.setSource(component.element());
  8945. return Option.none();
  8946. } else {
  8947. return Option.none();
  8948. }
  8949. }
  8950. })
  8951. ])
  8952. };
  8953. };
  8954. var schema$c = [
  8955. strict$1('uid'),
  8956. strict$1('data'),
  8957. strict$1('components'),
  8958. strict$1('dom'),
  8959. defaulted$1('autofocus', false),
  8960. defaulted$1('ignoreFocus', false),
  8961. SketchBehaviours.field('widgetBehaviours', [
  8962. Representing,
  8963. Focusing,
  8964. Keying
  8965. ]),
  8966. defaulted$1('domModification', {}),
  8967. defaultUidsSchema(parts()),
  8968. output('builder', builder$2)
  8969. ];
  8970. var itemSchema$1 = choose$1('type', {
  8971. widget: schema$c,
  8972. item: schema$a,
  8973. separator: schema$b
  8974. });
  8975. var configureGrid = function (detail, movementInfo) {
  8976. return {
  8977. mode: 'flatgrid',
  8978. selector: '.' + detail.markers.item,
  8979. initSize: {
  8980. numColumns: movementInfo.initSize.numColumns,
  8981. numRows: movementInfo.initSize.numRows
  8982. },
  8983. focusManager: detail.focusManager
  8984. };
  8985. };
  8986. var configureMatrix = function (detail, movementInfo) {
  8987. return {
  8988. mode: 'matrix',
  8989. selectors: {
  8990. row: movementInfo.rowSelector,
  8991. cell: '.' + detail.markers.item
  8992. },
  8993. focusManager: detail.focusManager
  8994. };
  8995. };
  8996. var configureMenu = function (detail, movementInfo) {
  8997. return {
  8998. mode: 'menu',
  8999. selector: '.' + detail.markers.item,
  9000. moveOnTab: movementInfo.moveOnTab,
  9001. focusManager: detail.focusManager
  9002. };
  9003. };
  9004. var parts$1 = constant([group({
  9005. factory: {
  9006. sketch: function (spec) {
  9007. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  9008. return itemInfo.builder(itemInfo);
  9009. }
  9010. },
  9011. name: 'items',
  9012. unit: 'item',
  9013. defaults: function (detail, u) {
  9014. return u.hasOwnProperty('uid') ? u : __assign({}, u, { uid: generate$3('item') });
  9015. },
  9016. overrides: function (detail, u) {
  9017. return {
  9018. type: u.type,
  9019. ignoreFocus: detail.fakeFocus,
  9020. domModification: { classes: [detail.markers.item] }
  9021. };
  9022. }
  9023. })]);
  9024. var schema$d = constant([
  9025. strict$1('value'),
  9026. strict$1('items'),
  9027. strict$1('dom'),
  9028. strict$1('components'),
  9029. defaulted$1('eventOrder', {}),
  9030. field$1('menuBehaviours', [
  9031. Highlighting,
  9032. Representing,
  9033. Composing,
  9034. Keying
  9035. ]),
  9036. defaultedOf('movement', {
  9037. mode: 'menu',
  9038. moveOnTab: true
  9039. }, choose$1('mode', {
  9040. grid: [
  9041. initSize(),
  9042. output('config', configureGrid)
  9043. ],
  9044. matrix: [
  9045. output('config', configureMatrix),
  9046. strict$1('rowSelector')
  9047. ],
  9048. menu: [
  9049. defaulted$1('moveOnTab', true),
  9050. output('config', configureMenu)
  9051. ]
  9052. })),
  9053. itemMarkers(),
  9054. defaulted$1('fakeFocus', false),
  9055. defaulted$1('focusManager', dom()),
  9056. onHandler('onHighlight')
  9057. ]);
  9058. var focus$4 = constant('alloy.menu-focus');
  9059. var make$2 = function (detail, components, spec, externals) {
  9060. return {
  9061. uid: detail.uid,
  9062. dom: detail.dom,
  9063. markers: detail.markers,
  9064. behaviours: augment(detail.menuBehaviours, [
  9065. Highlighting.config({
  9066. highlightClass: detail.markers.selectedItem,
  9067. itemClass: detail.markers.item,
  9068. onHighlight: detail.onHighlight
  9069. }),
  9070. Representing.config({
  9071. store: {
  9072. mode: 'memory',
  9073. initialValue: detail.value
  9074. }
  9075. }),
  9076. Composing.config({ find: Option.some }),
  9077. Keying.config(detail.movement.config(detail, detail.movement))
  9078. ]),
  9079. events: derive([
  9080. run(focus$3(), function (menu, simulatedEvent) {
  9081. var event = simulatedEvent.event();
  9082. menu.getSystem().getByDom(event.target()).each(function (item) {
  9083. Highlighting.highlight(menu, item);
  9084. simulatedEvent.stop();
  9085. emitWith(menu, focus$4(), {
  9086. menu: menu,
  9087. item: item
  9088. });
  9089. });
  9090. }),
  9091. run(hover(), function (menu, simulatedEvent) {
  9092. var item = simulatedEvent.event().item();
  9093. Highlighting.highlight(menu, item);
  9094. })
  9095. ]),
  9096. components: components,
  9097. eventOrder: detail.eventOrder,
  9098. domModification: { attributes: { role: 'menu' } }
  9099. };
  9100. };
  9101. var Menu = composite$1({
  9102. name: 'Menu',
  9103. configFields: schema$d(),
  9104. partFields: parts$1(),
  9105. factory: make$2
  9106. });
  9107. var preserve$2 = function (f, container) {
  9108. var ownerDoc = owner(container);
  9109. var refocus = active(ownerDoc).bind(function (focused) {
  9110. var hasFocus = function (elem) {
  9111. return eq(focused, elem);
  9112. };
  9113. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  9114. });
  9115. var result = f(container);
  9116. refocus.each(function (oldFocus) {
  9117. active(ownerDoc).filter(function (newFocus) {
  9118. return eq(newFocus, oldFocus);
  9119. }).fold(function () {
  9120. focus$1(oldFocus);
  9121. }, noop);
  9122. });
  9123. return result;
  9124. };
  9125. var set$8 = function (component, replaceConfig, replaceState, data) {
  9126. detachChildren(component);
  9127. preserve$2(function () {
  9128. var children = map$1(data, component.getSystem().build);
  9129. each$1(children, function (l) {
  9130. attach(component, l);
  9131. });
  9132. }, component.element());
  9133. };
  9134. var insert = function (component, replaceConfig, insertion, childSpec) {
  9135. var child = component.getSystem().build(childSpec);
  9136. attachWith(component, child, insertion);
  9137. };
  9138. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  9139. insert(component, replaceConfig, append, appendee);
  9140. };
  9141. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  9142. insert(component, replaceConfig, prepend, prependee);
  9143. };
  9144. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  9145. var children = contents(component, replaceConfig);
  9146. var foundChild = find$2(children, function (child) {
  9147. return eq(removee.element(), child.element());
  9148. });
  9149. foundChild.each(detach);
  9150. };
  9151. var contents = function (component, replaceConfig) {
  9152. return component.components();
  9153. };
  9154. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  9155. var children = contents(component, replaceConfig);
  9156. return Option.from(children[replaceeIndex]).map(function (replacee) {
  9157. remove$7(component, replaceConfig, replaceState, replacee);
  9158. replacer.each(function (r) {
  9159. insert(component, replaceConfig, function (p, c) {
  9160. appendAt(p, c, replaceeIndex);
  9161. }, r);
  9162. });
  9163. return replacee;
  9164. });
  9165. };
  9166. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  9167. var children = contents(component, replaceConfig);
  9168. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  9169. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  9170. });
  9171. };
  9172. var ReplaceApis = /*#__PURE__*/Object.freeze({
  9173. append: append$2,
  9174. prepend: prepend$1,
  9175. remove: remove$7,
  9176. replaceAt: replaceAt,
  9177. replaceBy: replaceBy,
  9178. set: set$8,
  9179. contents: contents
  9180. });
  9181. var Replacing = create$1({
  9182. fields: [],
  9183. name: 'replacing',
  9184. apis: ReplaceApis
  9185. });
  9186. var transpose = function (obj) {
  9187. return tupleMap(obj, function (v, k) {
  9188. return {
  9189. k: v,
  9190. v: k
  9191. };
  9192. });
  9193. };
  9194. var trace = function (items, byItem, byMenu, finish) {
  9195. return readOptFrom$1(byMenu, finish).bind(function (triggerItem) {
  9196. return readOptFrom$1(items, triggerItem).bind(function (triggerMenu) {
  9197. var rest = trace(items, byItem, byMenu, triggerMenu);
  9198. return Option.some([triggerMenu].concat(rest));
  9199. });
  9200. }).getOr([]);
  9201. };
  9202. var generate$5 = function (menus, expansions) {
  9203. var items = {};
  9204. each(menus, function (menuItems, menu) {
  9205. each$1(menuItems, function (item) {
  9206. items[item] = menu;
  9207. });
  9208. });
  9209. var byItem = expansions;
  9210. var byMenu = transpose(expansions);
  9211. var menuPaths = map(byMenu, function (_triggerItem, submenu) {
  9212. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  9213. });
  9214. return map(items, function (menu) {
  9215. return readOptFrom$1(menuPaths, menu).getOr([menu]);
  9216. });
  9217. };
  9218. var init$3 = function () {
  9219. var expansions = Cell({});
  9220. var menus = Cell({});
  9221. var paths = Cell({});
  9222. var primary = Cell(Option.none());
  9223. var directory = Cell({});
  9224. var clear = function () {
  9225. expansions.set({});
  9226. menus.set({});
  9227. paths.set({});
  9228. primary.set(Option.none());
  9229. };
  9230. var isClear = function () {
  9231. return primary.get().isNone();
  9232. };
  9233. var setMenuBuilt = function (menuName, built) {
  9234. var _a;
  9235. menus.set(__assign({}, menus.get(), (_a = {}, _a[menuName] = {
  9236. type: 'prepared',
  9237. menu: built
  9238. }, _a)));
  9239. };
  9240. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  9241. primary.set(Option.some(sPrimary));
  9242. expansions.set(sExpansions);
  9243. menus.set(sMenus);
  9244. directory.set(dir);
  9245. var sPaths = generate$5(dir, sExpansions);
  9246. paths.set(sPaths);
  9247. };
  9248. var expand = function (itemValue) {
  9249. return readOptFrom$1(expansions.get(), itemValue).map(function (menu) {
  9250. var current = readOptFrom$1(paths.get(), itemValue).getOr([]);
  9251. return [menu].concat(current);
  9252. });
  9253. };
  9254. var collapse = function (itemValue) {
  9255. return readOptFrom$1(paths.get(), itemValue).bind(function (path) {
  9256. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  9257. });
  9258. };
  9259. var refresh = function (itemValue) {
  9260. return readOptFrom$1(paths.get(), itemValue);
  9261. };
  9262. var lookupMenu = function (menuValue) {
  9263. return readOptFrom$1(menus.get(), menuValue);
  9264. };
  9265. var otherMenus = function (path) {
  9266. var menuValues = directory.get();
  9267. return difference(keys(menuValues), path);
  9268. };
  9269. var getPrimary = function () {
  9270. return primary.get().bind(function (primaryName) {
  9271. return lookupMenu(primaryName).bind(function (prep) {
  9272. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  9273. });
  9274. });
  9275. };
  9276. var getMenus = function () {
  9277. return menus.get();
  9278. };
  9279. return {
  9280. setMenuBuilt: setMenuBuilt,
  9281. setContents: setContents,
  9282. expand: expand,
  9283. refresh: refresh,
  9284. collapse: collapse,
  9285. lookupMenu: lookupMenu,
  9286. otherMenus: otherMenus,
  9287. getPrimary: getPrimary,
  9288. getMenus: getMenus,
  9289. clear: clear,
  9290. isClear: isClear
  9291. };
  9292. };
  9293. var LayeredState = { init: init$3 };
  9294. var make$3 = function (detail, rawUiSpec) {
  9295. var submenuParentItems = Cell(Option.none());
  9296. var buildMenus = function (container, primaryName, menus) {
  9297. return map(menus, function (spec, name) {
  9298. var makeSketch = function () {
  9299. return Menu.sketch(__assign({ dom: spec.dom }, spec, {
  9300. value: name,
  9301. items: spec.items,
  9302. markers: detail.markers,
  9303. fakeFocus: detail.fakeFocus,
  9304. onHighlight: detail.onHighlight,
  9305. focusManager: detail.fakeFocus ? highlights() : dom()
  9306. }));
  9307. };
  9308. return name === primaryName ? {
  9309. type: 'prepared',
  9310. menu: container.getSystem().build(makeSketch())
  9311. } : {
  9312. type: 'notbuilt',
  9313. nbMenu: makeSketch
  9314. };
  9315. });
  9316. };
  9317. var layeredState = LayeredState.init();
  9318. var setup = function (container) {
  9319. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  9320. var directory = toDirectory(container);
  9321. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  9322. return layeredState.getPrimary();
  9323. };
  9324. var getItemValue = function (item) {
  9325. return Representing.getValue(item).value;
  9326. };
  9327. var toDirectory = function (container) {
  9328. return map(detail.data.menus, function (data, menuName) {
  9329. return bind(data.items, function (item) {
  9330. return item.type === 'separator' ? [] : [item.data.value];
  9331. });
  9332. });
  9333. };
  9334. var setActiveMenu = function (container, menu) {
  9335. Highlighting.highlight(container, menu);
  9336. Highlighting.getHighlighted(menu).orThunk(function () {
  9337. return Highlighting.getFirst(menu);
  9338. }).each(function (item) {
  9339. dispatch(container, item.element(), focusItem());
  9340. });
  9341. };
  9342. var getMenus = function (state, menuValues) {
  9343. return cat(map$1(menuValues, function (mv) {
  9344. return state.lookupMenu(mv).bind(function (prep) {
  9345. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  9346. });
  9347. }));
  9348. };
  9349. var closeOthers = function (container, state, path) {
  9350. var others = getMenus(state, state.otherMenus(path));
  9351. each$1(others, function (o) {
  9352. remove$6(o.element(), [detail.markers.backgroundMenu]);
  9353. if (!detail.stayInDom) {
  9354. Replacing.remove(container, o);
  9355. }
  9356. });
  9357. };
  9358. var getSubmenuParents = function (container) {
  9359. return submenuParentItems.get().getOrThunk(function () {
  9360. var r = {};
  9361. var items = descendants(container.element(), '.' + detail.markers.item);
  9362. var parentItems = filter(items, function (i) {
  9363. return get$1(i, 'aria-haspopup') === 'true';
  9364. });
  9365. each$1(parentItems, function (i) {
  9366. container.getSystem().getByDom(i).each(function (itemComp) {
  9367. var key = getItemValue(itemComp);
  9368. r[key] = itemComp;
  9369. });
  9370. });
  9371. submenuParentItems.set(Option.some(r));
  9372. return r;
  9373. });
  9374. };
  9375. var updateAriaExpansions = function (container, path) {
  9376. var parentItems = getSubmenuParents(container);
  9377. each(parentItems, function (v, k) {
  9378. var expanded = contains(path, k);
  9379. set(v.element(), 'aria-expanded', expanded);
  9380. });
  9381. };
  9382. var updateMenuPath = function (container, state, path) {
  9383. return Option.from(path[0]).bind(function (latestMenuName) {
  9384. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  9385. if (menuPrep.type === 'notbuilt') {
  9386. return Option.none();
  9387. } else {
  9388. var activeMenu = menuPrep.menu;
  9389. var rest = getMenus(state, path.slice(1));
  9390. each$1(rest, function (r) {
  9391. add$2(r.element(), detail.markers.backgroundMenu);
  9392. });
  9393. if (!inBody(activeMenu.element())) {
  9394. Replacing.append(container, premade$1(activeMenu));
  9395. }
  9396. remove$6(activeMenu.element(), [detail.markers.backgroundMenu]);
  9397. setActiveMenu(container, activeMenu);
  9398. closeOthers(container, state, path);
  9399. return Option.some(activeMenu);
  9400. }
  9401. });
  9402. });
  9403. };
  9404. var ExpandHighlightDecision;
  9405. (function (ExpandHighlightDecision) {
  9406. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  9407. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  9408. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  9409. var buildIfRequired = function (container, menuName, menuPrep) {
  9410. if (menuPrep.type === 'notbuilt') {
  9411. var menu = container.getSystem().build(menuPrep.nbMenu());
  9412. layeredState.setMenuBuilt(menuName, menu);
  9413. return menu;
  9414. } else {
  9415. return menuPrep.menu;
  9416. }
  9417. };
  9418. var expandRight = function (container, item, decision) {
  9419. if (decision === void 0) {
  9420. decision = ExpandHighlightDecision.HighlightSubmenu;
  9421. }
  9422. var value = getItemValue(item);
  9423. return layeredState.expand(value).bind(function (path) {
  9424. updateAriaExpansions(container, path);
  9425. return Option.from(path[0]).bind(function (menuName) {
  9426. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  9427. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  9428. if (!inBody(activeMenu.element())) {
  9429. Replacing.append(container, premade$1(activeMenu));
  9430. }
  9431. detail.onOpenSubmenu(container, item, activeMenu);
  9432. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  9433. Highlighting.highlightFirst(activeMenu);
  9434. return updateMenuPath(container, layeredState, path);
  9435. } else {
  9436. Highlighting.dehighlightAll(activeMenu);
  9437. return Option.some(item);
  9438. }
  9439. });
  9440. });
  9441. });
  9442. };
  9443. var collapseLeft = function (container, item) {
  9444. var value = getItemValue(item);
  9445. return layeredState.collapse(value).bind(function (path) {
  9446. updateAriaExpansions(container, path);
  9447. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  9448. detail.onCollapseMenu(container, item, activeMenu);
  9449. return activeMenu;
  9450. });
  9451. });
  9452. };
  9453. var updateView = function (container, item) {
  9454. var value = getItemValue(item);
  9455. return layeredState.refresh(value).bind(function (path) {
  9456. updateAriaExpansions(container, path);
  9457. return updateMenuPath(container, layeredState, path);
  9458. });
  9459. };
  9460. var onRight = function (container, item) {
  9461. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  9462. };
  9463. var onLeft = function (container, item) {
  9464. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  9465. };
  9466. var onEscape = function (container, item) {
  9467. return collapseLeft(container, item).orThunk(function () {
  9468. return detail.onEscape(container, item).map(function () {
  9469. return container;
  9470. });
  9471. });
  9472. };
  9473. var keyOnItem = function (f) {
  9474. return function (container, simulatedEvent) {
  9475. return closest$2(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  9476. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  9477. return f(container, item).map(function () {
  9478. return true;
  9479. });
  9480. });
  9481. });
  9482. };
  9483. };
  9484. var events = derive([
  9485. run(focus$4(), function (sandbox, simulatedEvent) {
  9486. var menu = simulatedEvent.event().menu();
  9487. Highlighting.highlight(sandbox, menu);
  9488. var value = getItemValue(simulatedEvent.event().item());
  9489. layeredState.refresh(value).each(function (path) {
  9490. return closeOthers(sandbox, layeredState, path);
  9491. });
  9492. }),
  9493. runOnExecute(function (component, simulatedEvent) {
  9494. var target = simulatedEvent.event().target();
  9495. component.getSystem().getByDom(target).each(function (item) {
  9496. var itemValue = getItemValue(item);
  9497. if (itemValue.indexOf('collapse-item') === 0) {
  9498. collapseLeft(component, item);
  9499. }
  9500. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  9501. detail.onExecute(component, item);
  9502. }, function () {
  9503. });
  9504. });
  9505. }),
  9506. runOnAttached(function (container, simulatedEvent) {
  9507. setup(container).each(function (primary) {
  9508. Replacing.append(container, premade$1(primary));
  9509. detail.onOpenMenu(container, primary);
  9510. if (detail.highlightImmediately) {
  9511. setActiveMenu(container, primary);
  9512. }
  9513. });
  9514. })
  9515. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  9516. var item = simulatedEvent.event().item();
  9517. updateView(sandbox, item);
  9518. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  9519. detail.onHover(sandbox, item);
  9520. })] : []));
  9521. var collapseMenuApi = function (container) {
  9522. Highlighting.getHighlighted(container).each(function (currentMenu) {
  9523. Highlighting.getHighlighted(currentMenu).each(function (currentItem) {
  9524. collapseLeft(container, currentItem);
  9525. });
  9526. });
  9527. };
  9528. var highlightPrimary = function (container) {
  9529. layeredState.getPrimary().each(function (primary) {
  9530. setActiveMenu(container, primary);
  9531. });
  9532. };
  9533. var apis = {
  9534. collapseMenu: collapseMenuApi,
  9535. highlightPrimary: highlightPrimary
  9536. };
  9537. return {
  9538. uid: detail.uid,
  9539. dom: detail.dom,
  9540. markers: detail.markers,
  9541. behaviours: augment(detail.tmenuBehaviours, [
  9542. Keying.config({
  9543. mode: 'special',
  9544. onRight: keyOnItem(onRight),
  9545. onLeft: keyOnItem(onLeft),
  9546. onEscape: keyOnItem(onEscape),
  9547. focusIn: function (container, keyInfo) {
  9548. layeredState.getPrimary().each(function (primary) {
  9549. dispatch(container, primary.element(), focusItem());
  9550. });
  9551. }
  9552. }),
  9553. Highlighting.config({
  9554. highlightClass: detail.markers.selectedMenu,
  9555. itemClass: detail.markers.menu
  9556. }),
  9557. Composing.config({
  9558. find: function (container) {
  9559. return Highlighting.getHighlighted(container);
  9560. }
  9561. }),
  9562. Replacing.config({})
  9563. ]),
  9564. eventOrder: detail.eventOrder,
  9565. apis: apis,
  9566. events: events
  9567. };
  9568. };
  9569. var collapseItem = constant('collapse-item');
  9570. var tieredData = function (primary, menus, expansions) {
  9571. return {
  9572. primary: primary,
  9573. menus: menus,
  9574. expansions: expansions
  9575. };
  9576. };
  9577. var singleData = function (name, menu) {
  9578. return {
  9579. primary: name,
  9580. menus: wrap$1(name, menu),
  9581. expansions: {}
  9582. };
  9583. };
  9584. var collapseItem$1 = function (text) {
  9585. return {
  9586. value: generate$1(collapseItem()),
  9587. meta: { text: text }
  9588. };
  9589. };
  9590. var tieredMenu = single$2({
  9591. name: 'TieredMenu',
  9592. configFields: [
  9593. onStrictKeyboardHandler('onExecute'),
  9594. onStrictKeyboardHandler('onEscape'),
  9595. onStrictHandler('onOpenMenu'),
  9596. onStrictHandler('onOpenSubmenu'),
  9597. onHandler('onCollapseMenu'),
  9598. defaulted$1('highlightImmediately', true),
  9599. strictObjOf('data', [
  9600. strict$1('primary'),
  9601. strict$1('menus'),
  9602. strict$1('expansions')
  9603. ]),
  9604. defaulted$1('fakeFocus', false),
  9605. onHandler('onHighlight'),
  9606. onHandler('onHover'),
  9607. tieredMenuMarkers(),
  9608. strict$1('dom'),
  9609. defaulted$1('navigateOnHover', true),
  9610. defaulted$1('stayInDom', false),
  9611. field$1('tmenuBehaviours', [
  9612. Keying,
  9613. Highlighting,
  9614. Composing,
  9615. Replacing
  9616. ]),
  9617. defaulted$1('eventOrder', {})
  9618. ],
  9619. apis: {
  9620. collapseMenu: function (apis, tmenu) {
  9621. apis.collapseMenu(tmenu);
  9622. },
  9623. highlightPrimary: function (apis, tmenu) {
  9624. apis.highlightPrimary(tmenu);
  9625. }
  9626. },
  9627. factory: make$3,
  9628. extraApis: {
  9629. tieredData: tieredData,
  9630. singleData: singleData,
  9631. collapseItem: collapseItem$1
  9632. }
  9633. });
  9634. var findRoute = function (component, transConfig, transState, route) {
  9635. return readOptFrom$1(transConfig.routes, route.start).bind(function (sConfig) {
  9636. return readOptFrom$1(sConfig, route.destination);
  9637. });
  9638. };
  9639. var getTransition = function (comp, transConfig, transState) {
  9640. var route = getCurrentRoute(comp, transConfig, transState);
  9641. return route.bind(function (r) {
  9642. return getTransitionOf(comp, transConfig, transState, r);
  9643. });
  9644. };
  9645. var getTransitionOf = function (comp, transConfig, transState, route) {
  9646. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  9647. return r.transition.map(function (t) {
  9648. return {
  9649. transition: t,
  9650. route: r
  9651. };
  9652. });
  9653. });
  9654. };
  9655. var disableTransition = function (comp, transConfig, transState) {
  9656. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  9657. var t = routeTransition.transition;
  9658. remove$4(comp.element(), t.transitionClass);
  9659. remove$1(comp.element(), transConfig.destinationAttr);
  9660. });
  9661. };
  9662. var getNewRoute = function (comp, transConfig, transState, destination) {
  9663. return {
  9664. start: get$1(comp.element(), transConfig.stateAttr),
  9665. destination: destination
  9666. };
  9667. };
  9668. var getCurrentRoute = function (comp, transConfig, transState) {
  9669. var el = comp.element();
  9670. return has$1(el, transConfig.destinationAttr) ? Option.some({
  9671. start: get$1(comp.element(), transConfig.stateAttr),
  9672. destination: get$1(comp.element(), transConfig.destinationAttr)
  9673. }) : Option.none();
  9674. };
  9675. var jumpTo = function (comp, transConfig, transState, destination) {
  9676. disableTransition(comp, transConfig, transState);
  9677. if (has$1(comp.element(), transConfig.stateAttr) && get$1(comp.element(), transConfig.stateAttr) !== destination) {
  9678. transConfig.onFinish(comp, destination);
  9679. }
  9680. set(comp.element(), transConfig.stateAttr, destination);
  9681. };
  9682. var fasttrack = function (comp, transConfig, transState, destination) {
  9683. if (has$1(comp.element(), transConfig.destinationAttr)) {
  9684. set(comp.element(), transConfig.stateAttr, get$1(comp.element(), transConfig.destinationAttr));
  9685. remove$1(comp.element(), transConfig.destinationAttr);
  9686. }
  9687. };
  9688. var progressTo = function (comp, transConfig, transState, destination) {
  9689. fasttrack(comp, transConfig, transState, destination);
  9690. var route = getNewRoute(comp, transConfig, transState, destination);
  9691. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  9692. jumpTo(comp, transConfig, transState, destination);
  9693. }, function (routeTransition) {
  9694. disableTransition(comp, transConfig, transState);
  9695. var t = routeTransition.transition;
  9696. add$2(comp.element(), t.transitionClass);
  9697. set(comp.element(), transConfig.destinationAttr, destination);
  9698. });
  9699. };
  9700. var getState$1 = function (comp, transConfig, transState) {
  9701. var e = comp.element();
  9702. return has$1(e, transConfig.stateAttr) ? Option.some(get$1(e, transConfig.stateAttr)) : Option.none();
  9703. };
  9704. var TransitionApis = /*#__PURE__*/Object.freeze({
  9705. findRoute: findRoute,
  9706. disableTransition: disableTransition,
  9707. getCurrentRoute: getCurrentRoute,
  9708. jumpTo: jumpTo,
  9709. progressTo: progressTo,
  9710. getState: getState$1
  9711. });
  9712. var events$9 = function (transConfig, transState) {
  9713. return derive([
  9714. run(transitionend(), function (component, simulatedEvent) {
  9715. var raw = simulatedEvent.event().raw();
  9716. getCurrentRoute(component, transConfig, transState).each(function (route) {
  9717. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  9718. rInfo.transition.each(function (rTransition) {
  9719. if (raw.propertyName === rTransition.property) {
  9720. jumpTo(component, transConfig, transState, route.destination);
  9721. transConfig.onTransition(component, route);
  9722. }
  9723. });
  9724. });
  9725. });
  9726. }),
  9727. runOnAttached(function (comp, se) {
  9728. jumpTo(comp, transConfig, transState, transConfig.initialState);
  9729. })
  9730. ]);
  9731. };
  9732. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  9733. events: events$9
  9734. });
  9735. var TransitionSchema = [
  9736. defaulted$1('destinationAttr', 'data-transitioning-destination'),
  9737. defaulted$1('stateAttr', 'data-transitioning-state'),
  9738. strict$1('initialState'),
  9739. onHandler('onTransition'),
  9740. onHandler('onFinish'),
  9741. strictOf('routes', setOf$1(Result.value, setOf$1(Result.value, objOfOnly([optionObjOfOnly('transition', [
  9742. strict$1('property'),
  9743. strict$1('transitionClass')
  9744. ])]))))
  9745. ];
  9746. var createRoutes = function (routes) {
  9747. var r = {};
  9748. each(routes, function (v, k) {
  9749. var waypoints = k.split('<->');
  9750. r[waypoints[0]] = wrap$1(waypoints[1], v);
  9751. r[waypoints[1]] = wrap$1(waypoints[0], v);
  9752. });
  9753. return r;
  9754. };
  9755. var createBistate = function (first, second, transitions) {
  9756. return wrapAll$1([
  9757. {
  9758. key: first,
  9759. value: wrap$1(second, transitions)
  9760. },
  9761. {
  9762. key: second,
  9763. value: wrap$1(first, transitions)
  9764. }
  9765. ]);
  9766. };
  9767. var createTristate = function (first, second, third, transitions) {
  9768. return wrapAll$1([
  9769. {
  9770. key: first,
  9771. value: wrapAll$1([
  9772. {
  9773. key: second,
  9774. value: transitions
  9775. },
  9776. {
  9777. key: third,
  9778. value: transitions
  9779. }
  9780. ])
  9781. },
  9782. {
  9783. key: second,
  9784. value: wrapAll$1([
  9785. {
  9786. key: first,
  9787. value: transitions
  9788. },
  9789. {
  9790. key: third,
  9791. value: transitions
  9792. }
  9793. ])
  9794. },
  9795. {
  9796. key: third,
  9797. value: wrapAll$1([
  9798. {
  9799. key: first,
  9800. value: transitions
  9801. },
  9802. {
  9803. key: second,
  9804. value: transitions
  9805. }
  9806. ])
  9807. }
  9808. ]);
  9809. };
  9810. var Transitioning = create$1({
  9811. fields: TransitionSchema,
  9812. name: 'transitioning',
  9813. active: ActiveTransitioning,
  9814. apis: TransitionApis,
  9815. extra: {
  9816. createRoutes: createRoutes,
  9817. createBistate: createBistate,
  9818. createTristate: createTristate
  9819. }
  9820. });
  9821. var scrollable = Styles.resolve('scrollable');
  9822. var register = function (element) {
  9823. add$2(element, scrollable);
  9824. };
  9825. var deregister = function (element) {
  9826. remove$4(element, scrollable);
  9827. };
  9828. var Scrollable = {
  9829. register: register,
  9830. deregister: deregister,
  9831. scrollable: constant(scrollable)
  9832. };
  9833. var getValue$4 = function (item) {
  9834. return readOptFrom$1(item, 'format').getOr(item.title);
  9835. };
  9836. var convert$1 = function (formats, memMenuThunk) {
  9837. var mainMenu = makeMenu('Styles', [].concat(map$1(formats.items, function (k) {
  9838. return makeItem(getValue$4(k), k.title, k.isSelected(), k.getPreview(), hasKey$1(formats.expansions, getValue$4(k)));
  9839. })), memMenuThunk, false);
  9840. var submenus = map(formats.menus, function (menuItems, menuName) {
  9841. var items = map$1(menuItems, function (item) {
  9842. return makeItem(getValue$4(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasKey$1(formats.expansions, getValue$4(item)));
  9843. });
  9844. return makeMenu(menuName, items, memMenuThunk, true);
  9845. });
  9846. var menus = deepMerge(submenus, wrap$1('styles', mainMenu));
  9847. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  9848. return { tmenu: tmenu };
  9849. };
  9850. var makeItem = function (value, text, selected, preview, isMenu) {
  9851. return {
  9852. data: {
  9853. value: value,
  9854. text: text
  9855. },
  9856. type: 'item',
  9857. dom: {
  9858. tag: 'div',
  9859. classes: isMenu ? [Styles.resolve('styles-item-is-menu')] : []
  9860. },
  9861. toggling: {
  9862. toggleOnExecute: false,
  9863. toggleClass: Styles.resolve('format-matches'),
  9864. selected: selected
  9865. },
  9866. itemBehaviours: derive$1(isMenu ? [] : [Receivers.format(value, function (comp, status) {
  9867. var toggle = status ? Toggling.on : Toggling.off;
  9868. toggle(comp);
  9869. })]),
  9870. components: [{
  9871. dom: {
  9872. tag: 'div',
  9873. attributes: { style: preview },
  9874. innerHtml: text
  9875. }
  9876. }]
  9877. };
  9878. };
  9879. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  9880. return {
  9881. value: value,
  9882. dom: { tag: 'div' },
  9883. components: [
  9884. Button.sketch({
  9885. dom: {
  9886. tag: 'div',
  9887. classes: [Styles.resolve('styles-collapser')]
  9888. },
  9889. components: collapsable ? [
  9890. {
  9891. dom: {
  9892. tag: 'span',
  9893. classes: [Styles.resolve('styles-collapse-icon')]
  9894. }
  9895. },
  9896. text(value)
  9897. ] : [text(value)],
  9898. action: function (item) {
  9899. if (collapsable) {
  9900. var comp = memMenuThunk().get(item);
  9901. tieredMenu.collapseMenu(comp);
  9902. }
  9903. }
  9904. }),
  9905. {
  9906. dom: {
  9907. tag: 'div',
  9908. classes: [Styles.resolve('styles-menu-items-container')]
  9909. },
  9910. components: [Menu.parts().items({})],
  9911. behaviours: derive$1([config('adhoc-scrollable-menu', [
  9912. runOnAttached(function (component, simulatedEvent) {
  9913. set$3(component.element(), 'overflow-y', 'auto');
  9914. set$3(component.element(), '-webkit-overflow-scrolling', 'touch');
  9915. Scrollable.register(component.element());
  9916. }),
  9917. runOnDetached(function (component) {
  9918. remove$5(component.element(), 'overflow-y');
  9919. remove$5(component.element(), '-webkit-overflow-scrolling');
  9920. Scrollable.deregister(component.element());
  9921. })
  9922. ])])
  9923. }
  9924. ],
  9925. items: items,
  9926. menuBehaviours: derive$1([Transitioning.config({
  9927. initialState: 'after',
  9928. routes: Transitioning.createTristate('before', 'current', 'after', {
  9929. transition: {
  9930. property: 'transform',
  9931. transitionClass: 'transitioning'
  9932. }
  9933. })
  9934. })])
  9935. };
  9936. };
  9937. var sketch$8 = function (settings) {
  9938. var dataset = convert$1(settings.formats, function () {
  9939. return memMenu;
  9940. });
  9941. var memMenu = record(tieredMenu.sketch({
  9942. dom: {
  9943. tag: 'div',
  9944. classes: [Styles.resolve('styles-menu')]
  9945. },
  9946. components: [],
  9947. fakeFocus: true,
  9948. stayInDom: true,
  9949. onExecute: function (tmenu, item) {
  9950. var v = Representing.getValue(item);
  9951. settings.handle(item, v.value);
  9952. return Option.none();
  9953. },
  9954. onEscape: function () {
  9955. return Option.none();
  9956. },
  9957. onOpenMenu: function (container, menu) {
  9958. var w = get$7(container.element());
  9959. set$4(menu.element(), w);
  9960. Transitioning.jumpTo(menu, 'current');
  9961. },
  9962. onOpenSubmenu: function (container, item, submenu) {
  9963. var w = get$7(container.element());
  9964. var menu = ancestor$1(item.element(), '[role="menu"]').getOrDie('hacky');
  9965. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9966. set$4(submenu.element(), w);
  9967. Transitioning.progressTo(menuComp, 'before');
  9968. Transitioning.jumpTo(submenu, 'after');
  9969. Transitioning.progressTo(submenu, 'current');
  9970. },
  9971. onCollapseMenu: function (container, item, menu) {
  9972. var submenu = ancestor$1(item.element(), '[role="menu"]').getOrDie('hacky');
  9973. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9974. Transitioning.progressTo(submenuComp, 'after');
  9975. Transitioning.progressTo(menu, 'current');
  9976. },
  9977. navigateOnHover: false,
  9978. highlightImmediately: true,
  9979. data: dataset.tmenu,
  9980. markers: {
  9981. backgroundMenu: Styles.resolve('styles-background-menu'),
  9982. menu: Styles.resolve('styles-menu'),
  9983. selectedMenu: Styles.resolve('styles-selected-menu'),
  9984. item: Styles.resolve('styles-item'),
  9985. selectedItem: Styles.resolve('styles-selected-item')
  9986. }
  9987. }));
  9988. return memMenu.asSpec();
  9989. };
  9990. var StylesMenu = { sketch: sketch$8 };
  9991. var getFromExpandingItem = function (item) {
  9992. var newItem = deepMerge(exclude$1(item, ['items']), { menu: true });
  9993. var rest = expand(item.items);
  9994. var newMenus = deepMerge(rest.menus, wrap$1(item.title, rest.items));
  9995. var newExpansions = deepMerge(rest.expansions, wrap$1(item.title, item.title));
  9996. return {
  9997. item: newItem,
  9998. menus: newMenus,
  9999. expansions: newExpansions
  10000. };
  10001. };
  10002. var getFromItem = function (item) {
  10003. return hasKey$1(item, 'items') ? getFromExpandingItem(item) : {
  10004. item: item,
  10005. menus: {},
  10006. expansions: {}
  10007. };
  10008. };
  10009. var expand = function (items) {
  10010. return foldr(items, function (acc, item) {
  10011. var newData = getFromItem(item);
  10012. return {
  10013. menus: deepMerge(acc.menus, newData.menus),
  10014. items: [newData.item].concat(acc.items),
  10015. expansions: deepMerge(acc.expansions, newData.expansions)
  10016. };
  10017. }, {
  10018. menus: {},
  10019. expansions: {},
  10020. items: []
  10021. });
  10022. };
  10023. var StyleConversions = { expand: expand };
  10024. var register$1 = function (editor, settings) {
  10025. var isSelectedFor = function (format) {
  10026. return function () {
  10027. return editor.formatter.match(format);
  10028. };
  10029. };
  10030. var getPreview = function (format) {
  10031. return function () {
  10032. var styles = editor.formatter.getCssText(format);
  10033. return styles;
  10034. };
  10035. };
  10036. var enrichSupported = function (item) {
  10037. return deepMerge(item, {
  10038. isSelected: isSelectedFor(item.format),
  10039. getPreview: getPreview(item.format)
  10040. });
  10041. };
  10042. var enrichMenu = function (item) {
  10043. return deepMerge(item, {
  10044. isSelected: constant(false),
  10045. getPreview: constant('')
  10046. });
  10047. };
  10048. var enrichCustom = function (item) {
  10049. var formatName = generate$1(item.title);
  10050. var newItem = deepMerge(item, {
  10051. format: formatName,
  10052. isSelected: isSelectedFor(formatName),
  10053. getPreview: getPreview(formatName)
  10054. });
  10055. editor.formatter.register(formatName, newItem);
  10056. return newItem;
  10057. };
  10058. var formats = readOptFrom$1(settings, 'style_formats').getOr(DefaultStyleFormats);
  10059. var doEnrich = function (items) {
  10060. return map$1(items, function (item) {
  10061. if (hasKey$1(item, 'items')) {
  10062. var newItems = doEnrich(item.items);
  10063. return deepMerge(enrichMenu(item), { items: newItems });
  10064. } else if (hasKey$1(item, 'format')) {
  10065. return enrichSupported(item);
  10066. } else {
  10067. return enrichCustom(item);
  10068. }
  10069. });
  10070. };
  10071. return doEnrich(formats);
  10072. };
  10073. var prune = function (editor, formats) {
  10074. var doPrune = function (items) {
  10075. return bind(items, function (item) {
  10076. if (item.items !== undefined) {
  10077. var newItems = doPrune(item.items);
  10078. return newItems.length > 0 ? [item] : [];
  10079. } else {
  10080. var keep = hasKey$1(item, 'format') ? editor.formatter.canApply(item.format) : true;
  10081. return keep ? [item] : [];
  10082. }
  10083. });
  10084. };
  10085. var prunedItems = doPrune(formats);
  10086. return StyleConversions.expand(prunedItems);
  10087. };
  10088. var ui = function (editor, formats, onDone) {
  10089. var pruned = prune(editor, formats);
  10090. return StylesMenu.sketch({
  10091. formats: pruned,
  10092. handle: function (item, value) {
  10093. editor.undoManager.transact(function () {
  10094. if (Toggling.isOn(item)) {
  10095. editor.formatter.remove(value);
  10096. } else {
  10097. editor.formatter.apply(value);
  10098. }
  10099. });
  10100. onDone();
  10101. }
  10102. });
  10103. };
  10104. var StyleFormats = {
  10105. register: register$1,
  10106. ui: ui
  10107. };
  10108. var defaults = [
  10109. 'undo',
  10110. 'bold',
  10111. 'italic',
  10112. 'link',
  10113. 'image',
  10114. 'bullist',
  10115. 'styleselect'
  10116. ];
  10117. var extract$1 = function (rawToolbar) {
  10118. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  10119. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  10120. };
  10121. var identifyFromArray = function (toolbar) {
  10122. return bind(toolbar, function (item) {
  10123. return isArray(item) ? identifyFromArray(item) : extract$1(item);
  10124. });
  10125. };
  10126. var identify = function (settings) {
  10127. var toolbar = settings.toolbar !== undefined ? settings.toolbar : defaults;
  10128. return isArray(toolbar) ? identifyFromArray(toolbar) : extract$1(toolbar);
  10129. };
  10130. var setup = function (realm, editor) {
  10131. var commandSketch = function (name) {
  10132. return function () {
  10133. return Buttons.forToolbarCommand(editor, name);
  10134. };
  10135. };
  10136. var stateCommandSketch = function (name) {
  10137. return function () {
  10138. return Buttons.forToolbarStateCommand(editor, name);
  10139. };
  10140. };
  10141. var actionSketch = function (name, query, action) {
  10142. return function () {
  10143. return Buttons.forToolbarStateAction(editor, name, query, action);
  10144. };
  10145. };
  10146. var undo = commandSketch('undo');
  10147. var redo = commandSketch('redo');
  10148. var bold = stateCommandSketch('bold');
  10149. var italic = stateCommandSketch('italic');
  10150. var underline = stateCommandSketch('underline');
  10151. var removeformat = commandSketch('removeformat');
  10152. var link = function () {
  10153. return sketch$7(realm, editor);
  10154. };
  10155. var unlink = actionSketch('unlink', 'link', function () {
  10156. editor.execCommand('unlink', null, false);
  10157. });
  10158. var image = function () {
  10159. return sketch$4(editor);
  10160. };
  10161. var bullist = actionSketch('unordered-list', 'ul', function () {
  10162. editor.execCommand('InsertUnorderedList', null, false);
  10163. });
  10164. var numlist = actionSketch('ordered-list', 'ol', function () {
  10165. editor.execCommand('InsertOrderedList', null, false);
  10166. });
  10167. var fontsizeselect = function () {
  10168. return sketch$3(realm, editor);
  10169. };
  10170. var forecolor = function () {
  10171. return ColorSlider.sketch(realm, editor);
  10172. };
  10173. var styleFormats = StyleFormats.register(editor, editor.settings);
  10174. var styleFormatsMenu = function () {
  10175. return StyleFormats.ui(editor, styleFormats, function () {
  10176. editor.fire('scrollIntoView');
  10177. });
  10178. };
  10179. var styleselect = function () {
  10180. return Buttons.forToolbar('style-formats', function (button) {
  10181. editor.fire('toReading');
  10182. realm.dropup().appear(styleFormatsMenu, Toggling.on, button);
  10183. }, derive$1([
  10184. Toggling.config({
  10185. toggleClass: Styles.resolve('toolbar-button-selected'),
  10186. toggleOnExecute: false,
  10187. aria: { mode: 'pressed' }
  10188. }),
  10189. Receiving.config({
  10190. channels: wrapAll$1([
  10191. Receivers.receive(TinyChannels.orientationChanged(), Toggling.off),
  10192. Receivers.receive(TinyChannels.dropupDismissed(), Toggling.off)
  10193. ])
  10194. })
  10195. ]), editor);
  10196. };
  10197. var feature = function (prereq, sketch) {
  10198. return {
  10199. isSupported: function () {
  10200. var buttons = editor.ui.registry.getAll().buttons;
  10201. return prereq.forall(function (p) {
  10202. return hasKey$1(buttons, p);
  10203. });
  10204. },
  10205. sketch: sketch
  10206. };
  10207. };
  10208. return {
  10209. undo: feature(Option.none(), undo),
  10210. redo: feature(Option.none(), redo),
  10211. bold: feature(Option.none(), bold),
  10212. italic: feature(Option.none(), italic),
  10213. underline: feature(Option.none(), underline),
  10214. removeformat: feature(Option.none(), removeformat),
  10215. link: feature(Option.none(), link),
  10216. unlink: feature(Option.none(), unlink),
  10217. image: feature(Option.none(), image),
  10218. bullist: feature(Option.some('bullist'), bullist),
  10219. numlist: feature(Option.some('numlist'), numlist),
  10220. fontsizeselect: feature(Option.none(), fontsizeselect),
  10221. forecolor: feature(Option.none(), forecolor),
  10222. styleselect: feature(Option.none(), styleselect)
  10223. };
  10224. };
  10225. var detect$4 = function (settings, features) {
  10226. var itemNames = identify(settings);
  10227. var present = {};
  10228. return bind(itemNames, function (iName) {
  10229. var r = !hasKey$1(present, iName) && hasKey$1(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  10230. present[iName] = true;
  10231. return r;
  10232. });
  10233. };
  10234. var Features = {
  10235. identify: identify,
  10236. setup: setup,
  10237. detect: detect$4
  10238. };
  10239. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  10240. return {
  10241. target: constant(target),
  10242. x: constant(x),
  10243. y: constant(y),
  10244. stop: stop,
  10245. prevent: prevent,
  10246. kill: kill,
  10247. raw: constant(raw)
  10248. };
  10249. };
  10250. var handle = function (filter, handler) {
  10251. return function (rawEvent) {
  10252. if (!filter(rawEvent)) {
  10253. return;
  10254. }
  10255. var target = Element.fromDom(rawEvent.target);
  10256. var stop = function () {
  10257. rawEvent.stopPropagation();
  10258. };
  10259. var prevent = function () {
  10260. rawEvent.preventDefault();
  10261. };
  10262. var kill = compose(prevent, stop);
  10263. var evt = mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  10264. handler(evt);
  10265. };
  10266. };
  10267. var binder = function (element, event, filter, handler, useCapture) {
  10268. var wrapped = handle(filter, handler);
  10269. element.dom().addEventListener(event, wrapped, useCapture);
  10270. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  10271. };
  10272. var bind$2 = function (element, event, filter, handler) {
  10273. return binder(element, event, filter, handler, false);
  10274. };
  10275. var capture = function (element, event, filter, handler) {
  10276. return binder(element, event, filter, handler, true);
  10277. };
  10278. var unbind = function (element, event, handler, useCapture) {
  10279. element.dom().removeEventListener(event, handler, useCapture);
  10280. };
  10281. var filter$1 = constant(true);
  10282. var bind$3 = function (element, event, handler) {
  10283. return bind$2(element, event, filter$1, handler);
  10284. };
  10285. var capture$1 = function (element, event, handler) {
  10286. return capture(element, event, filter$1, handler);
  10287. };
  10288. var global$3 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  10289. var INTERVAL = 50;
  10290. var INSURANCE = 1000 / INTERVAL;
  10291. var get$b = function (outerWindow) {
  10292. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  10293. return { isPortrait: constant(isPortrait) };
  10294. };
  10295. var getActualWidth = function (outerWindow) {
  10296. var isIos = PlatformDetection$1.detect().os.isiOS();
  10297. var isPortrait = get$b(outerWindow).isPortrait();
  10298. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  10299. };
  10300. var onChange = function (outerWindow, listeners) {
  10301. var win = Element.fromDom(outerWindow);
  10302. var poller = null;
  10303. var change = function () {
  10304. global$3.clearInterval(poller);
  10305. var orientation = get$b(outerWindow);
  10306. listeners.onChange(orientation);
  10307. onAdjustment(function () {
  10308. listeners.onReady(orientation);
  10309. });
  10310. };
  10311. var orientationHandle = bind$3(win, 'orientationchange', change);
  10312. var onAdjustment = function (f) {
  10313. global$3.clearInterval(poller);
  10314. var flag = outerWindow.innerHeight;
  10315. var insurance = 0;
  10316. poller = global$3.setInterval(function () {
  10317. if (flag !== outerWindow.innerHeight) {
  10318. global$3.clearInterval(poller);
  10319. f(Option.some(outerWindow.innerHeight));
  10320. } else if (insurance > INSURANCE) {
  10321. global$3.clearInterval(poller);
  10322. f(Option.none());
  10323. }
  10324. insurance++;
  10325. }, INTERVAL);
  10326. };
  10327. var destroy = function () {
  10328. orientationHandle.unbind();
  10329. };
  10330. return {
  10331. onAdjustment: onAdjustment,
  10332. destroy: destroy
  10333. };
  10334. };
  10335. var Orientation = {
  10336. get: get$b,
  10337. onChange: onChange,
  10338. getActualWidth: getActualWidth
  10339. };
  10340. function DelayedFunction (fun, delay) {
  10341. var ref = null;
  10342. var schedule = function () {
  10343. var args = [];
  10344. for (var _i = 0; _i < arguments.length; _i++) {
  10345. args[_i] = arguments[_i];
  10346. }
  10347. ref = domGlobals.setTimeout(function () {
  10348. fun.apply(null, args);
  10349. ref = null;
  10350. }, delay);
  10351. };
  10352. var cancel = function () {
  10353. if (ref !== null) {
  10354. domGlobals.clearTimeout(ref);
  10355. ref = null;
  10356. }
  10357. };
  10358. return {
  10359. cancel: cancel,
  10360. schedule: schedule
  10361. };
  10362. }
  10363. var SIGNIFICANT_MOVE = 5;
  10364. var LONGPRESS_DELAY = 400;
  10365. var getTouch = function (event) {
  10366. var raw = event.raw();
  10367. if (raw.touches === undefined || raw.touches.length !== 1) {
  10368. return Option.none();
  10369. }
  10370. return Option.some(raw.touches[0]);
  10371. };
  10372. var isFarEnough = function (touch, data) {
  10373. var distX = Math.abs(touch.clientX - data.x());
  10374. var distY = Math.abs(touch.clientY - data.y());
  10375. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  10376. };
  10377. var monitor = function (settings) {
  10378. var startData = Cell(Option.none());
  10379. var longpress$1 = DelayedFunction(function (event) {
  10380. startData.set(Option.none());
  10381. settings.triggerEvent(longpress(), event);
  10382. }, LONGPRESS_DELAY);
  10383. var handleTouchstart = function (event) {
  10384. getTouch(event).each(function (touch) {
  10385. longpress$1.cancel();
  10386. var data = {
  10387. x: constant(touch.clientX),
  10388. y: constant(touch.clientY),
  10389. target: event.target
  10390. };
  10391. longpress$1.schedule(event);
  10392. startData.set(Option.some(data));
  10393. });
  10394. return Option.none();
  10395. };
  10396. var handleTouchmove = function (event) {
  10397. longpress$1.cancel();
  10398. getTouch(event).each(function (touch) {
  10399. startData.get().each(function (data) {
  10400. if (isFarEnough(touch, data)) {
  10401. startData.set(Option.none());
  10402. }
  10403. });
  10404. });
  10405. return Option.none();
  10406. };
  10407. var handleTouchend = function (event) {
  10408. longpress$1.cancel();
  10409. var isSame = function (data) {
  10410. return eq(data.target(), event.target());
  10411. };
  10412. return startData.get().filter(isSame).map(function (data) {
  10413. return settings.triggerEvent(tap(), event);
  10414. });
  10415. };
  10416. var handlers = wrapAll$1([
  10417. {
  10418. key: touchstart(),
  10419. value: handleTouchstart
  10420. },
  10421. {
  10422. key: touchmove(),
  10423. value: handleTouchmove
  10424. },
  10425. {
  10426. key: touchend(),
  10427. value: handleTouchend
  10428. }
  10429. ]);
  10430. var fireIfReady = function (event, type) {
  10431. return readOptFrom$1(handlers, type).bind(function (handler) {
  10432. return handler(event);
  10433. });
  10434. };
  10435. return { fireIfReady: fireIfReady };
  10436. };
  10437. var monitor$1 = function (editorApi) {
  10438. var tapEvent = monitor({
  10439. triggerEvent: function (type, evt) {
  10440. editorApi.onTapContent(evt);
  10441. }
  10442. });
  10443. var onTouchend = function () {
  10444. return bind$3(editorApi.body(), 'touchend', function (evt) {
  10445. tapEvent.fireIfReady(evt, 'touchend');
  10446. });
  10447. };
  10448. var onTouchmove = function () {
  10449. return bind$3(editorApi.body(), 'touchmove', function (evt) {
  10450. tapEvent.fireIfReady(evt, 'touchmove');
  10451. });
  10452. };
  10453. var fireTouchstart = function (evt) {
  10454. tapEvent.fireIfReady(evt, 'touchstart');
  10455. };
  10456. return {
  10457. fireTouchstart: fireTouchstart,
  10458. onTouchend: onTouchend,
  10459. onTouchmove: onTouchmove
  10460. };
  10461. };
  10462. var TappingEvent = { monitor: monitor$1 };
  10463. var isAndroid6 = PlatformDetection$1.detect().os.version.major >= 6;
  10464. var initEvents = function (editorApi, toolstrip, alloy) {
  10465. var tapping = TappingEvent.monitor(editorApi);
  10466. var outerDoc = owner(toolstrip);
  10467. var isRanged = function (sel) {
  10468. return !eq(sel.start(), sel.finish()) || sel.soffset() !== sel.foffset();
  10469. };
  10470. var hasRangeInUi = function () {
  10471. return active(outerDoc).filter(function (input) {
  10472. return name(input) === 'input';
  10473. }).exists(function (input) {
  10474. return input.dom().selectionStart !== input.dom().selectionEnd;
  10475. });
  10476. };
  10477. var updateMargin = function () {
  10478. var rangeInContent = editorApi.doc().dom().hasFocus() && editorApi.getSelection().exists(isRanged);
  10479. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  10480. };
  10481. var listeners = [
  10482. bind$3(editorApi.body(), 'touchstart', function (evt) {
  10483. editorApi.onTouchContent();
  10484. tapping.fireTouchstart(evt);
  10485. }),
  10486. tapping.onTouchmove(),
  10487. tapping.onTouchend(),
  10488. bind$3(toolstrip, 'touchstart', function (evt) {
  10489. editorApi.onTouchToolstrip();
  10490. }),
  10491. editorApi.onToReading(function () {
  10492. blur(editorApi.body());
  10493. }),
  10494. editorApi.onToEditing(noop),
  10495. editorApi.onScrollToCursor(function (tinyEvent) {
  10496. tinyEvent.preventDefault();
  10497. editorApi.getCursorBox().each(function (bounds) {
  10498. var cWin = editorApi.win();
  10499. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  10500. var cScrollBy = isOutside ? bounds.bottom() - cWin.innerHeight + 50 : 0;
  10501. if (cScrollBy !== 0) {
  10502. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10503. }
  10504. });
  10505. })
  10506. ].concat(isAndroid6 === true ? [] : [
  10507. bind$3(Element.fromDom(editorApi.win()), 'blur', function () {
  10508. alloy.getByDom(toolstrip).each(Toggling.off);
  10509. }),
  10510. bind$3(outerDoc, 'select', updateMargin),
  10511. bind$3(editorApi.doc(), 'selectionchange', updateMargin)
  10512. ]);
  10513. var destroy = function () {
  10514. each$1(listeners, function (l) {
  10515. l.unbind();
  10516. });
  10517. };
  10518. return { destroy: destroy };
  10519. };
  10520. var AndroidEvents = { initEvents: initEvents };
  10521. var safeParse = function (element, attribute) {
  10522. var parsed = parseInt(get$1(element, attribute), 10);
  10523. return isNaN(parsed) ? 0 : parsed;
  10524. };
  10525. var DataAttributes = { safeParse: safeParse };
  10526. function NodeValue (is, name) {
  10527. var get = function (element) {
  10528. if (!is(element)) {
  10529. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10530. }
  10531. return getOption(element).getOr('');
  10532. };
  10533. var getOptionIE10 = function (element) {
  10534. try {
  10535. return getOptionSafe(element);
  10536. } catch (e) {
  10537. return Option.none();
  10538. }
  10539. };
  10540. var getOptionSafe = function (element) {
  10541. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  10542. };
  10543. var browser = PlatformDetection$1.detect().browser;
  10544. var getOption = browser.isIE() && browser.version.major === 10 ? getOptionIE10 : getOptionSafe;
  10545. var set = function (element, value) {
  10546. if (!is(element)) {
  10547. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10548. }
  10549. element.dom().nodeValue = value;
  10550. };
  10551. return {
  10552. get: get,
  10553. getOption: getOption,
  10554. set: set
  10555. };
  10556. }
  10557. var api$3 = NodeValue(isText, 'text');
  10558. var get$c = function (element) {
  10559. return api$3.get(element);
  10560. };
  10561. var getOption = function (element) {
  10562. return api$3.getOption(element);
  10563. };
  10564. var getEnd = function (element) {
  10565. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  10566. return children(element).length;
  10567. }, function (v) {
  10568. return v.length;
  10569. });
  10570. };
  10571. var NBSP = '\xA0';
  10572. var isTextNodeWithCursorPosition = function (el) {
  10573. return getOption(el).filter(function (text) {
  10574. return text.trim().length !== 0 || text.indexOf(NBSP) > -1;
  10575. }).isSome();
  10576. };
  10577. var elementsWithCursorPosition = [
  10578. 'img',
  10579. 'br'
  10580. ];
  10581. var isCursorPosition = function (elem) {
  10582. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  10583. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  10584. };
  10585. var adt$4 = Adt.generate([
  10586. { before: ['element'] },
  10587. {
  10588. on: [
  10589. 'element',
  10590. 'offset'
  10591. ]
  10592. },
  10593. { after: ['element'] }
  10594. ]);
  10595. var cata = function (subject, onBefore, onOn, onAfter) {
  10596. return subject.fold(onBefore, onOn, onAfter);
  10597. };
  10598. var getStart = function (situ) {
  10599. return situ.fold(identity, identity, identity);
  10600. };
  10601. var before$1 = adt$4.before;
  10602. var on$1 = adt$4.on;
  10603. var after$1 = adt$4.after;
  10604. var Situ = {
  10605. before: before$1,
  10606. on: on$1,
  10607. after: after$1,
  10608. cata: cata,
  10609. getStart: getStart
  10610. };
  10611. var type$1 = Adt.generate([
  10612. { domRange: ['rng'] },
  10613. {
  10614. relative: [
  10615. 'startSitu',
  10616. 'finishSitu'
  10617. ]
  10618. },
  10619. {
  10620. exact: [
  10621. 'start',
  10622. 'soffset',
  10623. 'finish',
  10624. 'foffset'
  10625. ]
  10626. }
  10627. ]);
  10628. var range$2 = Immutable('start', 'soffset', 'finish', 'foffset');
  10629. var relative = type$1.relative;
  10630. var exact = type$1.exact;
  10631. var makeRange = function (start, soffset, finish, foffset) {
  10632. var doc = owner(start);
  10633. var rng = doc.dom().createRange();
  10634. rng.setStart(start.dom(), soffset);
  10635. rng.setEnd(finish.dom(), foffset);
  10636. return rng;
  10637. };
  10638. var after$2 = function (start, soffset, finish, foffset) {
  10639. var r = makeRange(start, soffset, finish, foffset);
  10640. var same = eq(start, finish) && soffset === foffset;
  10641. return r.collapsed && !same;
  10642. };
  10643. var setStart = function (rng, situ) {
  10644. situ.fold(function (e) {
  10645. rng.setStartBefore(e.dom());
  10646. }, function (e, o) {
  10647. rng.setStart(e.dom(), o);
  10648. }, function (e) {
  10649. rng.setStartAfter(e.dom());
  10650. });
  10651. };
  10652. var setFinish = function (rng, situ) {
  10653. situ.fold(function (e) {
  10654. rng.setEndBefore(e.dom());
  10655. }, function (e, o) {
  10656. rng.setEnd(e.dom(), o);
  10657. }, function (e) {
  10658. rng.setEndAfter(e.dom());
  10659. });
  10660. };
  10661. var relativeToNative = function (win, startSitu, finishSitu) {
  10662. var range = win.document.createRange();
  10663. setStart(range, startSitu);
  10664. setFinish(range, finishSitu);
  10665. return range;
  10666. };
  10667. var exactToNative = function (win, start, soffset, finish, foffset) {
  10668. var rng = win.document.createRange();
  10669. rng.setStart(start.dom(), soffset);
  10670. rng.setEnd(finish.dom(), foffset);
  10671. return rng;
  10672. };
  10673. var toRect = function (rect) {
  10674. return {
  10675. left: constant(rect.left),
  10676. top: constant(rect.top),
  10677. right: constant(rect.right),
  10678. bottom: constant(rect.bottom),
  10679. width: constant(rect.width),
  10680. height: constant(rect.height)
  10681. };
  10682. };
  10683. var getFirstRect = function (rng) {
  10684. var rects = rng.getClientRects();
  10685. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  10686. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  10687. };
  10688. var adt$5 = Adt.generate([
  10689. {
  10690. ltr: [
  10691. 'start',
  10692. 'soffset',
  10693. 'finish',
  10694. 'foffset'
  10695. ]
  10696. },
  10697. {
  10698. rtl: [
  10699. 'start',
  10700. 'soffset',
  10701. 'finish',
  10702. 'foffset'
  10703. ]
  10704. }
  10705. ]);
  10706. var fromRange = function (win, type, range) {
  10707. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  10708. };
  10709. var getRanges = function (win, selection) {
  10710. return selection.match({
  10711. domRange: function (rng) {
  10712. return {
  10713. ltr: constant(rng),
  10714. rtl: Option.none
  10715. };
  10716. },
  10717. relative: function (startSitu, finishSitu) {
  10718. return {
  10719. ltr: cached(function () {
  10720. return relativeToNative(win, startSitu, finishSitu);
  10721. }),
  10722. rtl: cached(function () {
  10723. return Option.some(relativeToNative(win, finishSitu, startSitu));
  10724. })
  10725. };
  10726. },
  10727. exact: function (start, soffset, finish, foffset) {
  10728. return {
  10729. ltr: cached(function () {
  10730. return exactToNative(win, start, soffset, finish, foffset);
  10731. }),
  10732. rtl: cached(function () {
  10733. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  10734. })
  10735. };
  10736. }
  10737. });
  10738. };
  10739. var doDiagnose = function (win, ranges) {
  10740. var rng = ranges.ltr();
  10741. if (rng.collapsed) {
  10742. var reversed = ranges.rtl().filter(function (rev) {
  10743. return rev.collapsed === false;
  10744. });
  10745. return reversed.map(function (rev) {
  10746. return adt$5.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  10747. }).getOrThunk(function () {
  10748. return fromRange(win, adt$5.ltr, rng);
  10749. });
  10750. } else {
  10751. return fromRange(win, adt$5.ltr, rng);
  10752. }
  10753. };
  10754. var diagnose = function (win, selection) {
  10755. var ranges = getRanges(win, selection);
  10756. return doDiagnose(win, ranges);
  10757. };
  10758. var asLtrRange = function (win, selection) {
  10759. var diagnosis = diagnose(win, selection);
  10760. return diagnosis.match({
  10761. ltr: function (start, soffset, finish, foffset) {
  10762. var rng = win.document.createRange();
  10763. rng.setStart(start.dom(), soffset);
  10764. rng.setEnd(finish.dom(), foffset);
  10765. return rng;
  10766. },
  10767. rtl: function (start, soffset, finish, foffset) {
  10768. var rng = win.document.createRange();
  10769. rng.setStart(finish.dom(), foffset);
  10770. rng.setEnd(start.dom(), soffset);
  10771. return rng;
  10772. }
  10773. });
  10774. };
  10775. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  10776. if (length === 0) {
  10777. return 0;
  10778. } else if (x === maxX) {
  10779. return length - 1;
  10780. }
  10781. var xDelta = maxX;
  10782. for (var i = 1; i < length; i++) {
  10783. var rect = rectForOffset(i);
  10784. var curDeltaX = Math.abs(x - rect.left);
  10785. if (y <= rect.bottom) {
  10786. if (y < rect.top || curDeltaX > xDelta) {
  10787. return i - 1;
  10788. } else {
  10789. xDelta = curDeltaX;
  10790. }
  10791. }
  10792. }
  10793. return 0;
  10794. };
  10795. var inRect = function (rect, x, y) {
  10796. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  10797. };
  10798. var locateOffset = function (doc, textnode, x, y, rect) {
  10799. var rangeForOffset = function (o) {
  10800. var r = doc.dom().createRange();
  10801. r.setStart(textnode.dom(), o);
  10802. r.collapse(true);
  10803. return r;
  10804. };
  10805. var rectForOffset = function (o) {
  10806. var r = rangeForOffset(o);
  10807. return r.getBoundingClientRect();
  10808. };
  10809. var length = get$c(textnode).length;
  10810. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  10811. return rangeForOffset(offset);
  10812. };
  10813. var locate$1 = function (doc, node, x, y) {
  10814. var r = doc.dom().createRange();
  10815. r.selectNode(node.dom());
  10816. var rects = r.getClientRects();
  10817. var foundRect = findMap(rects, function (rect) {
  10818. return inRect(rect, x, y) ? Option.some(rect) : Option.none();
  10819. });
  10820. return foundRect.map(function (rect) {
  10821. return locateOffset(doc, node, x, y, rect);
  10822. });
  10823. };
  10824. var TextPoint = /*#__PURE__*/Object.freeze({
  10825. locate: locate$1
  10826. });
  10827. var searchInChildren = function (doc, node, x, y) {
  10828. var r = doc.dom().createRange();
  10829. var nodes = children(node);
  10830. return findMap(nodes, function (n) {
  10831. r.selectNode(n.dom());
  10832. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none();
  10833. });
  10834. };
  10835. var locateNode = function (doc, node, x, y) {
  10836. var locator = isText(node) ? locate$1 : searchInChildren;
  10837. return locator(doc, node, x, y);
  10838. };
  10839. var locate$2 = function (doc, node, x, y) {
  10840. var r = doc.dom().createRange();
  10841. r.selectNode(node.dom());
  10842. var rect = r.getBoundingClientRect();
  10843. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  10844. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  10845. return locateNode(doc, node, boundedX, boundedY);
  10846. };
  10847. var first$1 = function (element) {
  10848. return descendant(element, isCursorPosition);
  10849. };
  10850. var last$1 = function (element) {
  10851. return descendantRtl(element, isCursorPosition);
  10852. };
  10853. var descendantRtl = function (scope, predicate) {
  10854. var descend = function (element) {
  10855. var children$1 = children(element);
  10856. for (var i = children$1.length - 1; i >= 0; i--) {
  10857. var child = children$1[i];
  10858. if (predicate(child)) {
  10859. return Option.some(child);
  10860. }
  10861. var res = descend(child);
  10862. if (res.isSome()) {
  10863. return res;
  10864. }
  10865. }
  10866. return Option.none();
  10867. };
  10868. return descend(scope);
  10869. };
  10870. var COLLAPSE_TO_LEFT = true;
  10871. var COLLAPSE_TO_RIGHT = false;
  10872. var getCollapseDirection = function (rect, x) {
  10873. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  10874. };
  10875. var createCollapsedNode = function (doc, target, collapseDirection) {
  10876. var r = doc.dom().createRange();
  10877. r.selectNode(target.dom());
  10878. r.collapse(collapseDirection);
  10879. return r;
  10880. };
  10881. var locateInElement = function (doc, node, x) {
  10882. var cursorRange = doc.dom().createRange();
  10883. cursorRange.selectNode(node.dom());
  10884. var rect = cursorRange.getBoundingClientRect();
  10885. var collapseDirection = getCollapseDirection(rect, x);
  10886. var f = collapseDirection === COLLAPSE_TO_LEFT ? first$1 : last$1;
  10887. return f(node).map(function (target) {
  10888. return createCollapsedNode(doc, target, collapseDirection);
  10889. });
  10890. };
  10891. var locateInEmpty = function (doc, node, x) {
  10892. var rect = node.dom().getBoundingClientRect();
  10893. var collapseDirection = getCollapseDirection(rect, x);
  10894. return Option.some(createCollapsedNode(doc, node, collapseDirection));
  10895. };
  10896. var search$1 = function (doc, node, x) {
  10897. var f = children(node).length === 0 ? locateInEmpty : locateInElement;
  10898. return f(doc, node, x);
  10899. };
  10900. var caretPositionFromPoint = function (doc, x, y) {
  10901. return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) {
  10902. if (pos.offsetNode === null) {
  10903. return Option.none();
  10904. }
  10905. var r = doc.dom().createRange();
  10906. r.setStart(pos.offsetNode, pos.offset);
  10907. r.collapse();
  10908. return Option.some(r);
  10909. });
  10910. };
  10911. var caretRangeFromPoint = function (doc, x, y) {
  10912. return Option.from(doc.dom().caretRangeFromPoint(x, y));
  10913. };
  10914. var searchTextNodes = function (doc, node, x, y) {
  10915. var r = doc.dom().createRange();
  10916. r.selectNode(node.dom());
  10917. var rect = r.getBoundingClientRect();
  10918. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  10919. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  10920. return locate$2(doc, node, boundedX, boundedY);
  10921. };
  10922. var searchFromPoint = function (doc, x, y) {
  10923. return Element.fromPoint(doc, x, y).bind(function (elem) {
  10924. var fallback = function () {
  10925. return search$1(doc, elem, x);
  10926. };
  10927. return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  10928. });
  10929. };
  10930. var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
  10931. var beforeSpecial = function (element, offset) {
  10932. var name$1 = name(element);
  10933. if ('input' === name$1) {
  10934. return Situ.after(element);
  10935. } else if (!contains([
  10936. 'br',
  10937. 'img'
  10938. ], name$1)) {
  10939. return Situ.on(element, offset);
  10940. } else {
  10941. return offset === 0 ? Situ.before(element) : Situ.after(element);
  10942. }
  10943. };
  10944. var preprocessExact = function (start, soffset, finish, foffset) {
  10945. var startSitu = beforeSpecial(start, soffset);
  10946. var finishSitu = beforeSpecial(finish, foffset);
  10947. return relative(startSitu, finishSitu);
  10948. };
  10949. var doSetNativeRange = function (win, rng) {
  10950. Option.from(win.getSelection()).each(function (selection) {
  10951. selection.removeAllRanges();
  10952. selection.addRange(rng);
  10953. });
  10954. };
  10955. var doSetRange = function (win, start, soffset, finish, foffset) {
  10956. var rng = exactToNative(win, start, soffset, finish, foffset);
  10957. doSetNativeRange(win, rng);
  10958. };
  10959. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  10960. selection.collapse(start.dom(), soffset);
  10961. selection.extend(finish.dom(), foffset);
  10962. };
  10963. var setRangeFromRelative = function (win, relative) {
  10964. return diagnose(win, relative).match({
  10965. ltr: function (start, soffset, finish, foffset) {
  10966. doSetRange(win, start, soffset, finish, foffset);
  10967. },
  10968. rtl: function (start, soffset, finish, foffset) {
  10969. var selection = win.getSelection();
  10970. if (selection.setBaseAndExtent) {
  10971. selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
  10972. } else if (selection.extend) {
  10973. try {
  10974. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  10975. } catch (e) {
  10976. doSetRange(win, finish, foffset, start, soffset);
  10977. }
  10978. } else {
  10979. doSetRange(win, finish, foffset, start, soffset);
  10980. }
  10981. }
  10982. });
  10983. };
  10984. var setExact = function (win, start, soffset, finish, foffset) {
  10985. var relative = preprocessExact(start, soffset, finish, foffset);
  10986. setRangeFromRelative(win, relative);
  10987. };
  10988. var readRange = function (selection) {
  10989. if (selection.rangeCount > 0) {
  10990. var firstRng = selection.getRangeAt(0);
  10991. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  10992. return Option.some(range$2(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  10993. } else {
  10994. return Option.none();
  10995. }
  10996. };
  10997. var doGetExact = function (selection) {
  10998. var anchor = Element.fromDom(selection.anchorNode);
  10999. var focus = Element.fromDom(selection.focusNode);
  11000. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(range$2(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  11001. };
  11002. var getExact = function (win) {
  11003. return Option.from(win.getSelection()).filter(function (sel) {
  11004. return sel.rangeCount > 0;
  11005. }).bind(doGetExact);
  11006. };
  11007. var get$d = function (win) {
  11008. return getExact(win).map(function (range) {
  11009. return exact(range.start(), range.soffset(), range.finish(), range.foffset());
  11010. });
  11011. };
  11012. var getFirstRect$1 = function (win, selection) {
  11013. var rng = asLtrRange(win, selection);
  11014. return getFirstRect(rng);
  11015. };
  11016. var clear$1 = function (win) {
  11017. var selection = win.getSelection();
  11018. selection.removeAllRanges();
  11019. };
  11020. var COLLAPSED_WIDTH = 2;
  11021. var collapsedRect = function (rect) {
  11022. return {
  11023. left: rect.left,
  11024. top: rect.top,
  11025. right: rect.right,
  11026. bottom: rect.bottom,
  11027. width: constant(COLLAPSED_WIDTH),
  11028. height: rect.height
  11029. };
  11030. };
  11031. var toRect$1 = function (rawRect) {
  11032. return {
  11033. left: constant(rawRect.left),
  11034. top: constant(rawRect.top),
  11035. right: constant(rawRect.right),
  11036. bottom: constant(rawRect.bottom),
  11037. width: constant(rawRect.width),
  11038. height: constant(rawRect.height)
  11039. };
  11040. };
  11041. var getRectsFromRange = function (range) {
  11042. if (!range.collapsed) {
  11043. return map$1(range.getClientRects(), toRect$1);
  11044. } else {
  11045. var start_1 = Element.fromDom(range.startContainer);
  11046. return parent(start_1).bind(function (parent) {
  11047. var selection = exact(start_1, range.startOffset, parent, getEnd(parent));
  11048. var optRect = getFirstRect$1(range.startContainer.ownerDocument.defaultView, selection);
  11049. return optRect.map(collapsedRect).map(pure);
  11050. }).getOr([]);
  11051. }
  11052. };
  11053. var getRectangles = function (cWin) {
  11054. var sel = cWin.getSelection();
  11055. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  11056. };
  11057. var Rectangles = { getRectangles: getRectangles };
  11058. var autocompleteHack = function () {
  11059. return function (f) {
  11060. global$3.setTimeout(function () {
  11061. f();
  11062. }, 0);
  11063. };
  11064. };
  11065. var resume = function (cWin) {
  11066. cWin.focus();
  11067. var iBody = Element.fromDom(cWin.document.body);
  11068. var inInput = active().exists(function (elem) {
  11069. return contains([
  11070. 'input',
  11071. 'textarea'
  11072. ], name(elem));
  11073. });
  11074. var transaction = inInput ? autocompleteHack() : apply;
  11075. transaction(function () {
  11076. active().each(blur);
  11077. focus$1(iBody);
  11078. });
  11079. };
  11080. var ResumeEditing = { resume: resume };
  11081. var EXTRA_SPACING = 50;
  11082. var data = 'data-' + Styles.resolve('last-outer-height');
  11083. var setLastHeight = function (cBody, value) {
  11084. set(cBody, data, value);
  11085. };
  11086. var getLastHeight = function (cBody) {
  11087. return DataAttributes.safeParse(cBody, data);
  11088. };
  11089. var getBoundsFrom = function (rect) {
  11090. return {
  11091. top: constant(rect.top()),
  11092. bottom: constant(rect.top() + rect.height())
  11093. };
  11094. };
  11095. var getBounds$1 = function (cWin) {
  11096. var rects = Rectangles.getRectangles(cWin);
  11097. return rects.length > 0 ? Option.some(rects[0]).map(getBoundsFrom) : Option.none();
  11098. };
  11099. var findDelta = function (outerWindow, cBody) {
  11100. var last = getLastHeight(cBody);
  11101. var current = outerWindow.innerHeight;
  11102. return last > current ? Option.some(last - current) : Option.none();
  11103. };
  11104. var calculate = function (cWin, bounds, delta) {
  11105. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  11106. return isOutside ? Math.min(delta, bounds.bottom() - cWin.innerHeight + EXTRA_SPACING) : 0;
  11107. };
  11108. var setup$1 = function (outerWindow, cWin) {
  11109. var cBody = Element.fromDom(cWin.document.body);
  11110. var toEditing = function () {
  11111. ResumeEditing.resume(cWin);
  11112. };
  11113. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  11114. findDelta(outerWindow, cBody).each(function (delta) {
  11115. getBounds$1(cWin).each(function (bounds) {
  11116. var cScrollBy = calculate(cWin, bounds, delta);
  11117. if (cScrollBy !== 0) {
  11118. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  11119. }
  11120. });
  11121. });
  11122. setLastHeight(cBody, outerWindow.innerHeight);
  11123. });
  11124. setLastHeight(cBody, outerWindow.innerHeight);
  11125. var destroy = function () {
  11126. onResize.unbind();
  11127. };
  11128. return {
  11129. toEditing: toEditing,
  11130. destroy: destroy
  11131. };
  11132. };
  11133. var AndroidSetup = { setup: setup$1 };
  11134. var getBodyFromFrame = function (frame) {
  11135. return Option.some(Element.fromDom(frame.dom().contentWindow.document.body));
  11136. };
  11137. var getDocFromFrame = function (frame) {
  11138. return Option.some(Element.fromDom(frame.dom().contentWindow.document));
  11139. };
  11140. var getWinFromFrame = function (frame) {
  11141. return Option.from(frame.dom().contentWindow);
  11142. };
  11143. var getSelectionFromFrame = function (frame) {
  11144. var optWin = getWinFromFrame(frame);
  11145. return optWin.bind(getExact);
  11146. };
  11147. var getFrame = function (editor) {
  11148. return editor.getFrame();
  11149. };
  11150. var getOrDerive = function (name, f) {
  11151. return function (editor) {
  11152. var g = editor[name].getOrThunk(function () {
  11153. var frame = getFrame(editor);
  11154. return function () {
  11155. return f(frame);
  11156. };
  11157. });
  11158. return g();
  11159. };
  11160. };
  11161. var getOrListen = function (editor, doc, name, type) {
  11162. return editor[name].getOrThunk(function () {
  11163. return function (handler) {
  11164. return bind$3(doc, type, handler);
  11165. };
  11166. });
  11167. };
  11168. var toRect$2 = function (rect) {
  11169. return {
  11170. left: constant(rect.left),
  11171. top: constant(rect.top),
  11172. right: constant(rect.right),
  11173. bottom: constant(rect.bottom),
  11174. width: constant(rect.width),
  11175. height: constant(rect.height)
  11176. };
  11177. };
  11178. var getActiveApi = function (editor) {
  11179. var frame = getFrame(editor);
  11180. var tryFallbackBox = function (win) {
  11181. var isCollapsed = function (sel) {
  11182. return eq(sel.start(), sel.finish()) && sel.soffset() === sel.foffset();
  11183. };
  11184. var toStartRect = function (sel) {
  11185. var rect = sel.start().dom().getBoundingClientRect();
  11186. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect$2) : Option.none();
  11187. };
  11188. return getExact(win).filter(isCollapsed).bind(toStartRect);
  11189. };
  11190. return getBodyFromFrame(frame).bind(function (body) {
  11191. return getDocFromFrame(frame).bind(function (doc) {
  11192. return getWinFromFrame(frame).map(function (win) {
  11193. var html = Element.fromDom(doc.dom().documentElement);
  11194. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  11195. return function () {
  11196. return get$d(win).bind(function (sel) {
  11197. return getFirstRect$1(win, sel).orThunk(function () {
  11198. return tryFallbackBox(win);
  11199. });
  11200. });
  11201. };
  11202. });
  11203. var setSelection = editor.setSelection.getOrThunk(function () {
  11204. return function (start, soffset, finish, foffset) {
  11205. setExact(win, start, soffset, finish, foffset);
  11206. };
  11207. });
  11208. var clearSelection = editor.clearSelection.getOrThunk(function () {
  11209. return function () {
  11210. clear$1(win);
  11211. };
  11212. });
  11213. return {
  11214. body: constant(body),
  11215. doc: constant(doc),
  11216. win: constant(win),
  11217. html: constant(html),
  11218. getSelection: curry(getSelectionFromFrame, frame),
  11219. setSelection: setSelection,
  11220. clearSelection: clearSelection,
  11221. frame: constant(frame),
  11222. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  11223. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  11224. onDomChanged: editor.onDomChanged,
  11225. onScrollToCursor: editor.onScrollToCursor,
  11226. onScrollToElement: editor.onScrollToElement,
  11227. onToReading: editor.onToReading,
  11228. onToEditing: editor.onToEditing,
  11229. onToolbarScrollStart: editor.onToolbarScrollStart,
  11230. onTouchContent: editor.onTouchContent,
  11231. onTapContent: editor.onTapContent,
  11232. onTouchToolstrip: editor.onTouchToolstrip,
  11233. getCursorBox: getCursorBox
  11234. };
  11235. });
  11236. });
  11237. });
  11238. };
  11239. var PlatformEditor = {
  11240. getBody: getOrDerive('getBody', getBodyFromFrame),
  11241. getDoc: getOrDerive('getDoc', getDocFromFrame),
  11242. getWin: getOrDerive('getWin', getWinFromFrame),
  11243. getSelection: getOrDerive('getSelection', getSelectionFromFrame),
  11244. getFrame: getFrame,
  11245. getActiveApi: getActiveApi
  11246. };
  11247. var attr = 'data-ephox-mobile-fullscreen-style';
  11248. var siblingStyles = 'display:none!important;';
  11249. var ancestorPosition = 'position:absolute!important;';
  11250. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  11251. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  11252. var isAndroid = PlatformDetection$1.detect().os.isAndroid();
  11253. var matchColor = function (editorBody) {
  11254. var color = get$4(editorBody, 'background-color');
  11255. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  11256. };
  11257. var clobberStyles = function (container, editorBody) {
  11258. var gatherSibilings = function (element) {
  11259. var siblings = siblings$2(element, '*');
  11260. return siblings;
  11261. };
  11262. var clobber = function (clobberStyle) {
  11263. return function (element) {
  11264. var styles = get$1(element, 'style');
  11265. var backup = styles === undefined ? 'no-styles' : styles.trim();
  11266. if (backup === clobberStyle) {
  11267. return;
  11268. } else {
  11269. set(element, attr, backup);
  11270. set(element, 'style', clobberStyle);
  11271. }
  11272. };
  11273. };
  11274. var ancestors = ancestors$1(container, '*');
  11275. var siblings = bind(ancestors, gatherSibilings);
  11276. var bgColor = matchColor(editorBody);
  11277. each$1(siblings, clobber(siblingStyles));
  11278. each$1(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor));
  11279. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  11280. clobber(containerStyles + ancestorStyles + bgColor)(container);
  11281. };
  11282. var restoreStyles = function () {
  11283. var clobberedEls = all$2('[' + attr + ']');
  11284. each$1(clobberedEls, function (element) {
  11285. var restore = get$1(element, attr);
  11286. if (restore !== 'no-styles') {
  11287. set(element, 'style', restore);
  11288. } else {
  11289. remove$1(element, 'style');
  11290. }
  11291. remove$1(element, attr);
  11292. });
  11293. };
  11294. var Thor = {
  11295. clobberStyles: clobberStyles,
  11296. restoreStyles: restoreStyles
  11297. };
  11298. var tag = function () {
  11299. var head = first('head').getOrDie();
  11300. var nu = function () {
  11301. var meta = Element.fromTag('meta');
  11302. set(meta, 'name', 'viewport');
  11303. append(head, meta);
  11304. return meta;
  11305. };
  11306. var element = first('meta[name="viewport"]').getOrThunk(nu);
  11307. var backup = get$1(element, 'content');
  11308. var maximize = function () {
  11309. set(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  11310. };
  11311. var restore = function () {
  11312. if (backup !== undefined && backup !== null && backup.length > 0) {
  11313. set(element, 'content', backup);
  11314. } else {
  11315. set(element, 'content', 'user-scalable=yes');
  11316. }
  11317. };
  11318. return {
  11319. maximize: maximize,
  11320. restore: restore
  11321. };
  11322. };
  11323. var MetaViewport = { tag: tag };
  11324. var create$3 = function (platform, mask) {
  11325. var meta = MetaViewport.tag();
  11326. var androidApi = api$2();
  11327. var androidEvents = api$2();
  11328. var enter = function () {
  11329. mask.hide();
  11330. add$2(platform.container, Styles.resolve('fullscreen-maximized'));
  11331. add$2(platform.container, Styles.resolve('android-maximized'));
  11332. meta.maximize();
  11333. add$2(platform.body, Styles.resolve('android-scroll-reload'));
  11334. androidApi.set(AndroidSetup.setup(platform.win, PlatformEditor.getWin(platform.editor).getOrDie('no')));
  11335. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  11336. Thor.clobberStyles(platform.container, editorApi.body());
  11337. androidEvents.set(AndroidEvents.initEvents(editorApi, platform.toolstrip, platform.alloy));
  11338. });
  11339. };
  11340. var exit = function () {
  11341. meta.restore();
  11342. mask.show();
  11343. remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
  11344. remove$4(platform.container, Styles.resolve('android-maximized'));
  11345. Thor.restoreStyles();
  11346. remove$4(platform.body, Styles.resolve('android-scroll-reload'));
  11347. androidEvents.clear();
  11348. androidApi.clear();
  11349. };
  11350. return {
  11351. enter: enter,
  11352. exit: exit
  11353. };
  11354. };
  11355. var AndroidMode = { create: create$3 };
  11356. var adaptable = function (fn, rate) {
  11357. var timer = null;
  11358. var args = null;
  11359. var cancel = function () {
  11360. if (timer !== null) {
  11361. domGlobals.clearTimeout(timer);
  11362. timer = null;
  11363. args = null;
  11364. }
  11365. };
  11366. var throttle = function () {
  11367. var newArgs = [];
  11368. for (var _i = 0; _i < arguments.length; _i++) {
  11369. newArgs[_i] = arguments[_i];
  11370. }
  11371. args = newArgs;
  11372. if (timer === null) {
  11373. timer = domGlobals.setTimeout(function () {
  11374. fn.apply(null, args);
  11375. timer = null;
  11376. args = null;
  11377. }, rate);
  11378. }
  11379. };
  11380. return {
  11381. cancel: cancel,
  11382. throttle: throttle
  11383. };
  11384. };
  11385. var first$2 = function (fn, rate) {
  11386. var timer = null;
  11387. var cancel = function () {
  11388. if (timer !== null) {
  11389. domGlobals.clearTimeout(timer);
  11390. timer = null;
  11391. }
  11392. };
  11393. var throttle = function () {
  11394. var args = [];
  11395. for (var _i = 0; _i < arguments.length; _i++) {
  11396. args[_i] = arguments[_i];
  11397. }
  11398. if (timer === null) {
  11399. timer = domGlobals.setTimeout(function () {
  11400. fn.apply(null, args);
  11401. timer = null;
  11402. }, rate);
  11403. }
  11404. };
  11405. return {
  11406. cancel: cancel,
  11407. throttle: throttle
  11408. };
  11409. };
  11410. var last$2 = function (fn, rate) {
  11411. var timer = null;
  11412. var cancel = function () {
  11413. if (timer !== null) {
  11414. domGlobals.clearTimeout(timer);
  11415. timer = null;
  11416. }
  11417. };
  11418. var throttle = function () {
  11419. var args = [];
  11420. for (var _i = 0; _i < arguments.length; _i++) {
  11421. args[_i] = arguments[_i];
  11422. }
  11423. if (timer !== null)
  11424. domGlobals.clearTimeout(timer);
  11425. timer = domGlobals.setTimeout(function () {
  11426. fn.apply(null, args);
  11427. timer = null;
  11428. }, rate);
  11429. };
  11430. return {
  11431. cancel: cancel,
  11432. throttle: throttle
  11433. };
  11434. };
  11435. var Throttler = /*#__PURE__*/Object.freeze({
  11436. adaptable: adaptable,
  11437. first: first$2,
  11438. last: last$2
  11439. });
  11440. var sketch$9 = function (onView, translate) {
  11441. var memIcon = record(Container.sketch({
  11442. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  11443. containerBehaviours: derive$1([Toggling.config({
  11444. toggleClass: Styles.resolve('mask-tap-icon-selected'),
  11445. toggleOnExecute: false
  11446. })])
  11447. }));
  11448. var onViewThrottle = first$2(onView, 200);
  11449. return Container.sketch({
  11450. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  11451. components: [Container.sketch({
  11452. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  11453. components: [Button.sketch({
  11454. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  11455. components: [memIcon.asSpec()],
  11456. action: function (button) {
  11457. onViewThrottle.throttle();
  11458. },
  11459. buttonBehaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('mask-tap-icon-selected') })])
  11460. })]
  11461. })]
  11462. });
  11463. };
  11464. var TapToEditMask = { sketch: sketch$9 };
  11465. var MobileSchema = objOf([
  11466. strictObjOf('editor', [
  11467. strict$1('getFrame'),
  11468. option('getBody'),
  11469. option('getDoc'),
  11470. option('getWin'),
  11471. option('getSelection'),
  11472. option('setSelection'),
  11473. option('clearSelection'),
  11474. option('cursorSaver'),
  11475. option('onKeyup'),
  11476. option('onNodeChanged'),
  11477. option('getCursorBox'),
  11478. strict$1('onDomChanged'),
  11479. defaulted$1('onTouchContent', noop),
  11480. defaulted$1('onTapContent', noop),
  11481. defaulted$1('onTouchToolstrip', noop),
  11482. defaulted$1('onScrollToCursor', constant({ unbind: noop })),
  11483. defaulted$1('onScrollToElement', constant({ unbind: noop })),
  11484. defaulted$1('onToEditing', constant({ unbind: noop })),
  11485. defaulted$1('onToReading', constant({ unbind: noop })),
  11486. defaulted$1('onToolbarScrollStart', identity)
  11487. ]),
  11488. strict$1('socket'),
  11489. strict$1('toolstrip'),
  11490. strict$1('dropup'),
  11491. strict$1('toolbar'),
  11492. strict$1('container'),
  11493. strict$1('alloy'),
  11494. state$1('win', function (spec) {
  11495. return owner(spec.socket).dom().defaultView;
  11496. }),
  11497. state$1('body', function (spec) {
  11498. return Element.fromDom(spec.socket.dom().ownerDocument.body);
  11499. }),
  11500. defaulted$1('translate', identity),
  11501. defaulted$1('setReadOnly', noop),
  11502. defaulted$1('readOnlyOnInit', constant(true))
  11503. ]);
  11504. var produce = function (raw) {
  11505. var mobile = asRawOrDie('Getting AndroidWebapp schema', MobileSchema, raw);
  11506. set$3(mobile.toolstrip, 'width', '100%');
  11507. var onTap = function () {
  11508. mobile.setReadOnly(mobile.readOnlyOnInit());
  11509. mode.enter();
  11510. };
  11511. var mask = build$1(TapToEditMask.sketch(onTap, mobile.translate));
  11512. mobile.alloy.add(mask);
  11513. var maskApi = {
  11514. show: function () {
  11515. mobile.alloy.add(mask);
  11516. },
  11517. hide: function () {
  11518. mobile.alloy.remove(mask);
  11519. }
  11520. };
  11521. append(mobile.container, mask.element());
  11522. var mode = AndroidMode.create(mobile, maskApi);
  11523. return {
  11524. setReadOnly: mobile.setReadOnly,
  11525. refreshStructure: noop,
  11526. enter: mode.enter,
  11527. exit: mode.exit,
  11528. destroy: noop
  11529. };
  11530. };
  11531. var AndroidWebapp = { produce: produce };
  11532. var schema$e = constant([
  11533. strict$1('dom'),
  11534. defaulted$1('shell', true),
  11535. field$1('toolbarBehaviours', [Replacing])
  11536. ]);
  11537. var enhanceGroups = function (detail) {
  11538. return { behaviours: derive$1([Replacing.config({})]) };
  11539. };
  11540. var parts$2 = constant([optional({
  11541. name: 'groups',
  11542. overrides: enhanceGroups
  11543. })]);
  11544. var factory$4 = function (detail, components, spec, _externals) {
  11545. var setGroups = function (toolbar, groups) {
  11546. getGroupContainer(toolbar).fold(function () {
  11547. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  11548. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  11549. }, function (container) {
  11550. Replacing.set(container, groups);
  11551. });
  11552. };
  11553. var getGroupContainer = function (component) {
  11554. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  11555. };
  11556. var extra = detail.shell ? {
  11557. behaviours: [Replacing.config({})],
  11558. components: []
  11559. } : {
  11560. behaviours: [],
  11561. components: components
  11562. };
  11563. return {
  11564. uid: detail.uid,
  11565. dom: detail.dom,
  11566. components: extra.components,
  11567. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  11568. apis: { setGroups: setGroups },
  11569. domModification: { attributes: { role: 'group' } }
  11570. };
  11571. };
  11572. var Toolbar = composite$1({
  11573. name: 'Toolbar',
  11574. configFields: schema$e(),
  11575. partFields: parts$2(),
  11576. factory: factory$4,
  11577. apis: {
  11578. setGroups: function (apis, toolbar, groups) {
  11579. apis.setGroups(toolbar, groups);
  11580. }
  11581. }
  11582. });
  11583. var schema$f = constant([
  11584. strict$1('items'),
  11585. markers(['itemSelector']),
  11586. field$1('tgroupBehaviours', [Keying])
  11587. ]);
  11588. var parts$3 = constant([group({
  11589. name: 'items',
  11590. unit: 'item'
  11591. })]);
  11592. var factory$5 = function (detail, components, spec, _externals) {
  11593. return {
  11594. 'uid': detail.uid,
  11595. 'dom': detail.dom,
  11596. 'components': components,
  11597. 'behaviours': augment(detail.tgroupBehaviours, [Keying.config({
  11598. mode: 'flow',
  11599. selector: detail.markers.itemSelector
  11600. })]),
  11601. domModification: { attributes: { role: 'toolbar' } }
  11602. };
  11603. };
  11604. var ToolbarGroup = composite$1({
  11605. name: 'ToolbarGroup',
  11606. configFields: schema$f(),
  11607. partFields: parts$3(),
  11608. factory: factory$5
  11609. });
  11610. var dataHorizontal = 'data-' + Styles.resolve('horizontal-scroll');
  11611. var canScrollVertically = function (container) {
  11612. container.dom().scrollTop = 1;
  11613. var result = container.dom().scrollTop !== 0;
  11614. container.dom().scrollTop = 0;
  11615. return result;
  11616. };
  11617. var canScrollHorizontally = function (container) {
  11618. container.dom().scrollLeft = 1;
  11619. var result = container.dom().scrollLeft !== 0;
  11620. container.dom().scrollLeft = 0;
  11621. return result;
  11622. };
  11623. var hasVerticalScroll = function (container) {
  11624. return container.dom().scrollTop > 0 || canScrollVertically(container);
  11625. };
  11626. var hasHorizontalScroll = function (container) {
  11627. return container.dom().scrollLeft > 0 || canScrollHorizontally(container);
  11628. };
  11629. var markAsHorizontal = function (container) {
  11630. set(container, dataHorizontal, 'true');
  11631. };
  11632. var hasScroll = function (container) {
  11633. return get$1(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  11634. };
  11635. var exclusive = function (scope, selector) {
  11636. return bind$3(scope, 'touchmove', function (event) {
  11637. closest$2(event.target(), selector).filter(hasScroll).fold(function () {
  11638. event.raw().preventDefault();
  11639. }, noop);
  11640. });
  11641. };
  11642. var Scrollables = {
  11643. exclusive: exclusive,
  11644. markAsHorizontal: markAsHorizontal
  11645. };
  11646. function ScrollingToolbar () {
  11647. var makeGroup = function (gSpec) {
  11648. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  11649. return {
  11650. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  11651. tgroupBehaviours: derive$1([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, simulatedEvent) {
  11652. set$3(component.element(), 'overflow-x', 'auto');
  11653. Scrollables.markAsHorizontal(component.element());
  11654. Scrollable.register(component.element());
  11655. })] : [])]),
  11656. components: [Container.sketch({ components: [ToolbarGroup.parts().items({})] })],
  11657. markers: { itemSelector: '.' + Styles.resolve('toolbar-group-item') },
  11658. items: gSpec.items
  11659. };
  11660. };
  11661. var toolbar = build$1(Toolbar.sketch({
  11662. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  11663. components: [Toolbar.parts().groups({})],
  11664. toolbarBehaviours: derive$1([
  11665. Toggling.config({
  11666. toggleClass: Styles.resolve('context-toolbar'),
  11667. toggleOnExecute: false,
  11668. aria: { mode: 'none' }
  11669. }),
  11670. Keying.config({ mode: 'cyclic' })
  11671. ]),
  11672. shell: true
  11673. }));
  11674. var wrapper = build$1(Container.sketch({
  11675. dom: { classes: [Styles.resolve('toolstrip')] },
  11676. components: [premade$1(toolbar)],
  11677. containerBehaviours: derive$1([Toggling.config({
  11678. toggleClass: Styles.resolve('android-selection-context-toolbar'),
  11679. toggleOnExecute: false
  11680. })])
  11681. }));
  11682. var resetGroups = function () {
  11683. Toolbar.setGroups(toolbar, initGroups.get());
  11684. Toggling.off(toolbar);
  11685. };
  11686. var initGroups = Cell([]);
  11687. var setGroups = function (gs) {
  11688. initGroups.set(gs);
  11689. resetGroups();
  11690. };
  11691. var createGroups = function (gs) {
  11692. return map$1(gs, compose(ToolbarGroup.sketch, makeGroup));
  11693. };
  11694. var refresh = function () {
  11695. };
  11696. var setContextToolbar = function (gs) {
  11697. Toggling.on(toolbar);
  11698. Toolbar.setGroups(toolbar, gs);
  11699. };
  11700. var restoreToolbar = function () {
  11701. if (Toggling.isOn(toolbar)) {
  11702. resetGroups();
  11703. }
  11704. };
  11705. var focus = function () {
  11706. Keying.focusIn(toolbar);
  11707. };
  11708. return {
  11709. wrapper: constant(wrapper),
  11710. toolbar: constant(toolbar),
  11711. createGroups: createGroups,
  11712. setGroups: setGroups,
  11713. setContextToolbar: setContextToolbar,
  11714. restoreToolbar: restoreToolbar,
  11715. refresh: refresh,
  11716. focus: focus
  11717. };
  11718. }
  11719. var makeEditSwitch = function (webapp) {
  11720. return build$1(Button.sketch({
  11721. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  11722. action: function () {
  11723. webapp.run(function (w) {
  11724. w.setReadOnly(false);
  11725. });
  11726. }
  11727. }));
  11728. };
  11729. var makeSocket = function () {
  11730. return build$1(Container.sketch({
  11731. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  11732. components: [],
  11733. containerBehaviours: derive$1([Replacing.config({})])
  11734. }));
  11735. };
  11736. var showEdit = function (socket, switchToEdit) {
  11737. Replacing.append(socket, premade$1(switchToEdit));
  11738. };
  11739. var hideEdit = function (socket, switchToEdit) {
  11740. Replacing.remove(socket, switchToEdit);
  11741. };
  11742. var updateMode = function (socket, switchToEdit, readOnly, root) {
  11743. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  11744. swap(root);
  11745. var f = readOnly ? showEdit : hideEdit;
  11746. f(socket, switchToEdit);
  11747. };
  11748. var CommonRealm = {
  11749. makeEditSwitch: makeEditSwitch,
  11750. makeSocket: makeSocket,
  11751. updateMode: updateMode
  11752. };
  11753. var getAnimationRoot = function (component, slideConfig) {
  11754. return slideConfig.getAnimationRoot.fold(function () {
  11755. return component.element();
  11756. }, function (get) {
  11757. return get(component);
  11758. });
  11759. };
  11760. var getDimensionProperty = function (slideConfig) {
  11761. return slideConfig.dimension.property;
  11762. };
  11763. var getDimension = function (slideConfig, elem) {
  11764. return slideConfig.dimension.getDimension(elem);
  11765. };
  11766. var disableTransitions = function (component, slideConfig) {
  11767. var root = getAnimationRoot(component, slideConfig);
  11768. remove$6(root, [
  11769. slideConfig.shrinkingClass,
  11770. slideConfig.growingClass
  11771. ]);
  11772. };
  11773. var setShrunk = function (component, slideConfig) {
  11774. remove$4(component.element(), slideConfig.openClass);
  11775. add$2(component.element(), slideConfig.closedClass);
  11776. set$3(component.element(), getDimensionProperty(slideConfig), '0px');
  11777. reflow(component.element());
  11778. };
  11779. var setGrown = function (component, slideConfig) {
  11780. remove$4(component.element(), slideConfig.closedClass);
  11781. add$2(component.element(), slideConfig.openClass);
  11782. remove$5(component.element(), getDimensionProperty(slideConfig));
  11783. };
  11784. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  11785. slideState.setCollapsed();
  11786. set$3(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  11787. reflow(component.element());
  11788. disableTransitions(component, slideConfig);
  11789. setShrunk(component, slideConfig);
  11790. slideConfig.onStartShrink(component);
  11791. slideConfig.onShrunk(component);
  11792. };
  11793. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  11794. var size = calculatedSize.getOrThunk(function () {
  11795. return getDimension(slideConfig, component.element());
  11796. });
  11797. slideState.setCollapsed();
  11798. set$3(component.element(), getDimensionProperty(slideConfig), size);
  11799. reflow(component.element());
  11800. var root = getAnimationRoot(component, slideConfig);
  11801. remove$4(root, slideConfig.growingClass);
  11802. add$2(root, slideConfig.shrinkingClass);
  11803. setShrunk(component, slideConfig);
  11804. slideConfig.onStartShrink(component);
  11805. };
  11806. var doStartSmartShrink = function (component, slideConfig, slideState) {
  11807. var size = getDimension(slideConfig, component.element());
  11808. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  11809. shrinker(component, slideConfig, slideState, Option.some(size));
  11810. };
  11811. var doStartGrow = function (component, slideConfig, slideState) {
  11812. var root = getAnimationRoot(component, slideConfig);
  11813. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  11814. var beforeSize = getDimension(slideConfig, component.element());
  11815. setGrown(component, slideConfig);
  11816. var fullSize = getDimension(slideConfig, component.element());
  11817. var startPartialGrow = function () {
  11818. set$3(component.element(), getDimensionProperty(slideConfig), beforeSize);
  11819. reflow(component.element());
  11820. };
  11821. var startCompleteGrow = function () {
  11822. setShrunk(component, slideConfig);
  11823. };
  11824. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  11825. setStartSize();
  11826. remove$4(root, slideConfig.shrinkingClass);
  11827. add$2(root, slideConfig.growingClass);
  11828. setGrown(component, slideConfig);
  11829. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  11830. slideState.setExpanded();
  11831. slideConfig.onStartGrow(component);
  11832. };
  11833. var refresh = function (component, slideConfig, slideState) {
  11834. if (slideState.isExpanded()) {
  11835. remove$5(component.element(), getDimensionProperty(slideConfig));
  11836. var fullSize = getDimension(slideConfig, component.element());
  11837. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  11838. }
  11839. };
  11840. var grow = function (component, slideConfig, slideState) {
  11841. if (!slideState.isExpanded()) {
  11842. doStartGrow(component, slideConfig, slideState);
  11843. }
  11844. };
  11845. var shrink = function (component, slideConfig, slideState) {
  11846. if (slideState.isExpanded()) {
  11847. doStartSmartShrink(component, slideConfig, slideState);
  11848. }
  11849. };
  11850. var immediateShrink = function (component, slideConfig, slideState) {
  11851. if (slideState.isExpanded()) {
  11852. doImmediateShrink(component, slideConfig, slideState, Option.none());
  11853. }
  11854. };
  11855. var hasGrown = function (component, slideConfig, slideState) {
  11856. return slideState.isExpanded();
  11857. };
  11858. var hasShrunk = function (component, slideConfig, slideState) {
  11859. return slideState.isCollapsed();
  11860. };
  11861. var isGrowing = function (component, slideConfig, slideState) {
  11862. var root = getAnimationRoot(component, slideConfig);
  11863. return has$2(root, slideConfig.growingClass) === true;
  11864. };
  11865. var isShrinking = function (component, slideConfig, slideState) {
  11866. var root = getAnimationRoot(component, slideConfig);
  11867. return has$2(root, slideConfig.shrinkingClass) === true;
  11868. };
  11869. var isTransitioning = function (component, slideConfig, slideState) {
  11870. return isGrowing(component, slideConfig, slideState) === true || isShrinking(component, slideConfig, slideState) === true;
  11871. };
  11872. var toggleGrow = function (component, slideConfig, slideState) {
  11873. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  11874. f(component, slideConfig, slideState);
  11875. };
  11876. var SlidingApis = /*#__PURE__*/Object.freeze({
  11877. refresh: refresh,
  11878. grow: grow,
  11879. shrink: shrink,
  11880. immediateShrink: immediateShrink,
  11881. hasGrown: hasGrown,
  11882. hasShrunk: hasShrunk,
  11883. isGrowing: isGrowing,
  11884. isShrinking: isShrinking,
  11885. isTransitioning: isTransitioning,
  11886. toggleGrow: toggleGrow,
  11887. disableTransitions: disableTransitions
  11888. });
  11889. var exhibit$5 = function (base, slideConfig) {
  11890. var expanded = slideConfig.expanded;
  11891. return expanded ? nu$5({
  11892. classes: [slideConfig.openClass],
  11893. styles: {}
  11894. }) : nu$5({
  11895. classes: [slideConfig.closedClass],
  11896. styles: wrap$1(slideConfig.dimension.property, '0px')
  11897. });
  11898. };
  11899. var events$a = function (slideConfig, slideState) {
  11900. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  11901. var raw = simulatedEvent.event().raw();
  11902. if (raw.propertyName === slideConfig.dimension.property) {
  11903. disableTransitions(component, slideConfig);
  11904. if (slideState.isExpanded()) {
  11905. remove$5(component.element(), slideConfig.dimension.property);
  11906. }
  11907. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  11908. notify(component);
  11909. }
  11910. })]);
  11911. };
  11912. var ActiveSliding = /*#__PURE__*/Object.freeze({
  11913. exhibit: exhibit$5,
  11914. events: events$a
  11915. });
  11916. var SlidingSchema = [
  11917. strict$1('closedClass'),
  11918. strict$1('openClass'),
  11919. strict$1('shrinkingClass'),
  11920. strict$1('growingClass'),
  11921. option('getAnimationRoot'),
  11922. onHandler('onShrunk'),
  11923. onHandler('onStartShrink'),
  11924. onHandler('onGrown'),
  11925. onHandler('onStartGrow'),
  11926. defaulted$1('expanded', false),
  11927. strictOf('dimension', choose$1('property', {
  11928. width: [
  11929. output('property', 'width'),
  11930. output('getDimension', function (elem) {
  11931. return get$7(elem) + 'px';
  11932. })
  11933. ],
  11934. height: [
  11935. output('property', 'height'),
  11936. output('getDimension', function (elem) {
  11937. return get$5(elem) + 'px';
  11938. })
  11939. ]
  11940. }))
  11941. ];
  11942. var init$4 = function (spec) {
  11943. var state = Cell(spec.expanded);
  11944. var readState = function () {
  11945. return 'expanded: ' + state.get();
  11946. };
  11947. return nu$6({
  11948. isExpanded: function () {
  11949. return state.get() === true;
  11950. },
  11951. isCollapsed: function () {
  11952. return state.get() === false;
  11953. },
  11954. setCollapsed: curry(state.set, false),
  11955. setExpanded: curry(state.set, true),
  11956. readState: readState
  11957. });
  11958. };
  11959. var SlidingState = /*#__PURE__*/Object.freeze({
  11960. init: init$4
  11961. });
  11962. var Sliding = create$1({
  11963. fields: SlidingSchema,
  11964. name: 'sliding',
  11965. active: ActiveSliding,
  11966. apis: SlidingApis,
  11967. state: SlidingState
  11968. });
  11969. var build$2 = function (refresh, scrollIntoView) {
  11970. var dropup = build$1(Container.sketch({
  11971. dom: {
  11972. tag: 'div',
  11973. classes: [Styles.resolve('dropup')]
  11974. },
  11975. components: [],
  11976. containerBehaviours: derive$1([
  11977. Replacing.config({}),
  11978. Sliding.config({
  11979. closedClass: Styles.resolve('dropup-closed'),
  11980. openClass: Styles.resolve('dropup-open'),
  11981. shrinkingClass: Styles.resolve('dropup-shrinking'),
  11982. growingClass: Styles.resolve('dropup-growing'),
  11983. dimension: { property: 'height' },
  11984. onShrunk: function (component) {
  11985. refresh();
  11986. scrollIntoView();
  11987. Replacing.set(component, []);
  11988. },
  11989. onGrown: function (component) {
  11990. refresh();
  11991. scrollIntoView();
  11992. }
  11993. }),
  11994. Receivers.orientation(function (component, data) {
  11995. disappear(noop);
  11996. })
  11997. ])
  11998. }));
  11999. var appear = function (menu, update, component) {
  12000. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  12001. domGlobals.window.requestAnimationFrame(function () {
  12002. update(component);
  12003. Replacing.set(dropup, [menu()]);
  12004. Sliding.grow(dropup);
  12005. });
  12006. }
  12007. };
  12008. var disappear = function (onReadyToShrink) {
  12009. domGlobals.window.requestAnimationFrame(function () {
  12010. onReadyToShrink();
  12011. Sliding.shrink(dropup);
  12012. });
  12013. };
  12014. return {
  12015. appear: appear,
  12016. disappear: disappear,
  12017. component: constant(dropup),
  12018. element: dropup.element
  12019. };
  12020. };
  12021. var closest$3 = function (scope, selector, isRoot) {
  12022. return closest$2(scope, selector, isRoot).isSome();
  12023. };
  12024. var isDangerous = function (event) {
  12025. var keyEv = event.raw();
  12026. return keyEv.which === BACKSPACE()[0] && !contains([
  12027. 'input',
  12028. 'textarea'
  12029. ], name(event.target())) && !closest$3(event.target(), '[contenteditable="true"]');
  12030. };
  12031. var isFirefox = PlatformDetection$1.detect().browser.isFirefox();
  12032. var settingsSchema = objOfOnly([
  12033. strictFunction('triggerEvent'),
  12034. defaulted$1('stopBackspace', true)
  12035. ]);
  12036. var bindFocus = function (container, handler) {
  12037. if (isFirefox) {
  12038. return capture$1(container, 'focus', handler);
  12039. } else {
  12040. return bind$3(container, 'focusin', handler);
  12041. }
  12042. };
  12043. var bindBlur = function (container, handler) {
  12044. if (isFirefox) {
  12045. return capture$1(container, 'blur', handler);
  12046. } else {
  12047. return bind$3(container, 'focusout', handler);
  12048. }
  12049. };
  12050. var setup$2 = function (container, rawSettings) {
  12051. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  12052. var pointerEvents = PlatformDetection$1.detect().deviceType.isTouch() ? [
  12053. 'touchstart',
  12054. 'touchmove',
  12055. 'touchend',
  12056. 'gesturestart'
  12057. ] : [
  12058. 'mousedown',
  12059. 'mouseup',
  12060. 'mouseover',
  12061. 'mousemove',
  12062. 'mouseout',
  12063. 'click'
  12064. ];
  12065. var tapEvent = monitor(settings);
  12066. var simpleEvents = map$1(pointerEvents.concat([
  12067. 'selectstart',
  12068. 'input',
  12069. 'contextmenu',
  12070. 'change',
  12071. 'transitionend',
  12072. 'drag',
  12073. 'dragstart',
  12074. 'dragend',
  12075. 'dragenter',
  12076. 'dragleave',
  12077. 'dragover',
  12078. 'drop',
  12079. 'keyup'
  12080. ]), function (type) {
  12081. return bind$3(container, type, function (event) {
  12082. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  12083. if (tapStopped) {
  12084. event.kill();
  12085. }
  12086. });
  12087. var stopped = settings.triggerEvent(type, event);
  12088. if (stopped) {
  12089. event.kill();
  12090. }
  12091. });
  12092. });
  12093. var pasteTimeout = Cell(Option.none());
  12094. var onPaste = bind$3(container, 'paste', function (event) {
  12095. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  12096. if (tapStopped) {
  12097. event.kill();
  12098. }
  12099. });
  12100. var stopped = settings.triggerEvent('paste', event);
  12101. if (stopped) {
  12102. event.kill();
  12103. }
  12104. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  12105. settings.triggerEvent(postPaste(), event);
  12106. }, 0)));
  12107. });
  12108. var onKeydown = bind$3(container, 'keydown', function (event) {
  12109. var stopped = settings.triggerEvent('keydown', event);
  12110. if (stopped) {
  12111. event.kill();
  12112. } else if (settings.stopBackspace === true && isDangerous(event)) {
  12113. event.prevent();
  12114. }
  12115. });
  12116. var onFocusIn = bindFocus(container, function (event) {
  12117. var stopped = settings.triggerEvent('focusin', event);
  12118. if (stopped) {
  12119. event.kill();
  12120. }
  12121. });
  12122. var focusoutTimeout = Cell(Option.none());
  12123. var onFocusOut = bindBlur(container, function (event) {
  12124. var stopped = settings.triggerEvent('focusout', event);
  12125. if (stopped) {
  12126. event.kill();
  12127. }
  12128. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  12129. settings.triggerEvent(postBlur(), event);
  12130. }, 0)));
  12131. });
  12132. var unbind = function () {
  12133. each$1(simpleEvents, function (e) {
  12134. e.unbind();
  12135. });
  12136. onKeydown.unbind();
  12137. onFocusIn.unbind();
  12138. onFocusOut.unbind();
  12139. onPaste.unbind();
  12140. pasteTimeout.get().each(domGlobals.clearTimeout);
  12141. focusoutTimeout.get().each(domGlobals.clearTimeout);
  12142. };
  12143. return { unbind: unbind };
  12144. };
  12145. var derive$2 = function (rawEvent, rawTarget) {
  12146. var source = readOptFrom$1(rawEvent, 'target').map(function (getTarget) {
  12147. return getTarget();
  12148. }).getOr(rawTarget);
  12149. return Cell(source);
  12150. };
  12151. var fromSource = function (event, source) {
  12152. var stopper = Cell(false);
  12153. var cutter = Cell(false);
  12154. var stop = function () {
  12155. stopper.set(true);
  12156. };
  12157. var cut = function () {
  12158. cutter.set(true);
  12159. };
  12160. return {
  12161. stop: stop,
  12162. cut: cut,
  12163. isStopped: stopper.get,
  12164. isCut: cutter.get,
  12165. event: constant(event),
  12166. setSource: source.set,
  12167. getSource: source.get
  12168. };
  12169. };
  12170. var fromExternal = function (event) {
  12171. var stopper = Cell(false);
  12172. var stop = function () {
  12173. stopper.set(true);
  12174. };
  12175. return {
  12176. stop: stop,
  12177. cut: noop,
  12178. isStopped: stopper.get,
  12179. isCut: constant(false),
  12180. event: constant(event),
  12181. setSource: die('Cannot set source of a broadcasted event'),
  12182. getSource: die('Cannot get source of a broadcasted event')
  12183. };
  12184. };
  12185. var adt$6 = Adt.generate([
  12186. { stopped: [] },
  12187. { resume: ['element'] },
  12188. { complete: [] }
  12189. ]);
  12190. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  12191. var handler = lookup(eventType, target);
  12192. var simulatedEvent = fromSource(rawEvent, source);
  12193. return handler.fold(function () {
  12194. logger.logEventNoHandlers(eventType, target);
  12195. return adt$6.complete();
  12196. }, function (handlerInfo) {
  12197. var descHandler = handlerInfo.descHandler();
  12198. var eventHandler = getCurried(descHandler);
  12199. eventHandler(simulatedEvent);
  12200. if (simulatedEvent.isStopped()) {
  12201. logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose());
  12202. return adt$6.stopped();
  12203. } else if (simulatedEvent.isCut()) {
  12204. logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose());
  12205. return adt$6.complete();
  12206. } else {
  12207. return parent(handlerInfo.element()).fold(function () {
  12208. logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose());
  12209. return adt$6.complete();
  12210. }, function (parent) {
  12211. logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose());
  12212. return adt$6.resume(parent);
  12213. });
  12214. }
  12215. });
  12216. };
  12217. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12218. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  12219. return true;
  12220. }, function (parent) {
  12221. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12222. }, function () {
  12223. return false;
  12224. });
  12225. };
  12226. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12227. var source = derive$2(rawEvent, target);
  12228. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12229. };
  12230. var broadcast = function (listeners, rawEvent, logger) {
  12231. var simulatedEvent = fromExternal(rawEvent);
  12232. each$1(listeners, function (listener) {
  12233. var descHandler = listener.descHandler();
  12234. var handler = getCurried(descHandler);
  12235. handler(simulatedEvent);
  12236. });
  12237. return simulatedEvent.isStopped();
  12238. };
  12239. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12240. var rawTarget = rawEvent.target();
  12241. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  12242. };
  12243. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12244. var source = derive$2(rawEvent, rawTarget);
  12245. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12246. };
  12247. var eventHandler = Immutable('element', 'descHandler');
  12248. var broadcastHandler = function (id, handler) {
  12249. return {
  12250. id: constant(id),
  12251. descHandler: constant(handler)
  12252. };
  12253. };
  12254. function EventRegistry () {
  12255. var registry = {};
  12256. var registerId = function (extraArgs, id, events) {
  12257. each(events, function (v, k) {
  12258. var handlers = registry[k] !== undefined ? registry[k] : {};
  12259. handlers[id] = curryArgs(v, extraArgs);
  12260. registry[k] = handlers;
  12261. });
  12262. };
  12263. var findHandler = function (handlers, elem) {
  12264. return read$2(elem).fold(function () {
  12265. return Option.none();
  12266. }, function (id) {
  12267. var reader = readOpt$1(id);
  12268. return handlers.bind(reader).map(function (descHandler) {
  12269. return eventHandler(elem, descHandler);
  12270. });
  12271. });
  12272. };
  12273. var filterByType = function (type) {
  12274. return readOptFrom$1(registry, type).map(function (handlers) {
  12275. return mapToArray(handlers, function (f, id) {
  12276. return broadcastHandler(id, f);
  12277. });
  12278. }).getOr([]);
  12279. };
  12280. var find = function (isAboveRoot, type, target) {
  12281. var readType = readOpt$1(type);
  12282. var handlers = readType(registry);
  12283. return closest$1(target, function (elem) {
  12284. return findHandler(handlers, elem);
  12285. }, isAboveRoot);
  12286. };
  12287. var unregisterId = function (id) {
  12288. each(registry, function (handlersById, eventName) {
  12289. if (handlersById.hasOwnProperty(id)) {
  12290. delete handlersById[id];
  12291. }
  12292. });
  12293. };
  12294. return {
  12295. registerId: registerId,
  12296. unregisterId: unregisterId,
  12297. filterByType: filterByType,
  12298. find: find
  12299. };
  12300. }
  12301. function Registry () {
  12302. var events = EventRegistry();
  12303. var components = {};
  12304. var readOrTag = function (component) {
  12305. var elem = component.element();
  12306. return read$2(elem).fold(function () {
  12307. return write('uid-', component.element());
  12308. }, function (uid) {
  12309. return uid;
  12310. });
  12311. };
  12312. var failOnDuplicate = function (component, tagId) {
  12313. var conflict = components[tagId];
  12314. if (conflict === component) {
  12315. unregister(component);
  12316. } else {
  12317. 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');
  12318. }
  12319. };
  12320. var register = function (component) {
  12321. var tagId = readOrTag(component);
  12322. if (hasKey$1(components, tagId)) {
  12323. failOnDuplicate(component, tagId);
  12324. }
  12325. var extraArgs = [component];
  12326. events.registerId(extraArgs, tagId, component.events());
  12327. components[tagId] = component;
  12328. };
  12329. var unregister = function (component) {
  12330. read$2(component.element()).each(function (tagId) {
  12331. delete components[tagId];
  12332. events.unregisterId(tagId);
  12333. });
  12334. };
  12335. var filter = function (type) {
  12336. return events.filterByType(type);
  12337. };
  12338. var find = function (isAboveRoot, type, target) {
  12339. return events.find(isAboveRoot, type, target);
  12340. };
  12341. var getById = function (id) {
  12342. return readOpt$1(id)(components);
  12343. };
  12344. return {
  12345. find: find,
  12346. filter: filter,
  12347. register: register,
  12348. unregister: unregister,
  12349. getById: getById
  12350. };
  12351. }
  12352. var takeover = function (root) {
  12353. var isAboveRoot = function (el) {
  12354. return parent(root.element()).fold(function () {
  12355. return true;
  12356. }, function (parent) {
  12357. return eq(el, parent);
  12358. });
  12359. };
  12360. var registry = Registry();
  12361. var lookup = function (eventName, target) {
  12362. return registry.find(isAboveRoot, eventName, target);
  12363. };
  12364. var domEvents = setup$2(root.element(), {
  12365. triggerEvent: function (eventName, event) {
  12366. return monitorEvent(eventName, event.target(), function (logger) {
  12367. return triggerUntilStopped(lookup, eventName, event, logger);
  12368. });
  12369. }
  12370. });
  12371. var systemApi = {
  12372. debugInfo: constant('real'),
  12373. triggerEvent: function (eventName, target, data) {
  12374. monitorEvent(eventName, target, function (logger) {
  12375. triggerOnUntilStopped(lookup, eventName, data, target, logger);
  12376. });
  12377. },
  12378. triggerFocus: function (target, originator) {
  12379. read$2(target).fold(function () {
  12380. focus$1(target);
  12381. }, function (_alloyId) {
  12382. monitorEvent(focus(), target, function (logger) {
  12383. triggerHandler(lookup, focus(), {
  12384. originator: constant(originator),
  12385. kill: noop,
  12386. prevent: noop,
  12387. target: constant(target)
  12388. }, target, logger);
  12389. });
  12390. });
  12391. },
  12392. triggerEscape: function (comp, simulatedEvent) {
  12393. systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
  12394. },
  12395. getByUid: function (uid) {
  12396. return getByUid(uid);
  12397. },
  12398. getByDom: function (elem) {
  12399. return getByDom(elem);
  12400. },
  12401. build: build$1,
  12402. addToGui: function (c) {
  12403. add(c);
  12404. },
  12405. removeFromGui: function (c) {
  12406. remove$1(c);
  12407. },
  12408. addToWorld: function (c) {
  12409. addToWorld(c);
  12410. },
  12411. removeFromWorld: function (c) {
  12412. removeFromWorld(c);
  12413. },
  12414. broadcast: function (message) {
  12415. broadcast$1(message);
  12416. },
  12417. broadcastOn: function (channels, message) {
  12418. broadcastOn(channels, message);
  12419. },
  12420. broadcastEvent: function (eventName, event) {
  12421. broadcastEvent(eventName, event);
  12422. },
  12423. isConnected: constant(true)
  12424. };
  12425. var addToWorld = function (component) {
  12426. component.connect(systemApi);
  12427. if (!isText(component.element())) {
  12428. registry.register(component);
  12429. each$1(component.components(), addToWorld);
  12430. systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
  12431. }
  12432. };
  12433. var removeFromWorld = function (component) {
  12434. if (!isText(component.element())) {
  12435. each$1(component.components(), removeFromWorld);
  12436. registry.unregister(component);
  12437. }
  12438. component.disconnect();
  12439. };
  12440. var add = function (component) {
  12441. attach(root, component);
  12442. };
  12443. var remove$1 = function (component) {
  12444. detach(component);
  12445. };
  12446. var destroy = function () {
  12447. domEvents.unbind();
  12448. remove(root.element());
  12449. };
  12450. var broadcastData = function (data) {
  12451. var receivers = registry.filter(receive());
  12452. each$1(receivers, function (receiver) {
  12453. var descHandler = receiver.descHandler();
  12454. var handler = getCurried(descHandler);
  12455. handler(data);
  12456. });
  12457. };
  12458. var broadcast$1 = function (message) {
  12459. broadcastData({
  12460. universal: constant(true),
  12461. data: constant(message)
  12462. });
  12463. };
  12464. var broadcastOn = function (channels, message) {
  12465. broadcastData({
  12466. universal: constant(false),
  12467. channels: constant(channels),
  12468. data: constant(message)
  12469. });
  12470. };
  12471. var broadcastEvent = function (eventName, event) {
  12472. var listeners = registry.filter(eventName);
  12473. return broadcast(listeners, event);
  12474. };
  12475. var getByUid = function (uid) {
  12476. return registry.getById(uid).fold(function () {
  12477. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  12478. }, Result.value);
  12479. };
  12480. var getByDom = function (elem) {
  12481. var uid = read$2(elem).getOr('not found');
  12482. return getByUid(uid);
  12483. };
  12484. addToWorld(root);
  12485. return {
  12486. root: constant(root),
  12487. element: root.element,
  12488. destroy: destroy,
  12489. add: add,
  12490. remove: remove$1,
  12491. getByUid: getByUid,
  12492. getByDom: getByDom,
  12493. addToWorld: addToWorld,
  12494. removeFromWorld: removeFromWorld,
  12495. broadcast: broadcast$1,
  12496. broadcastOn: broadcastOn,
  12497. broadcastEvent: broadcastEvent
  12498. };
  12499. };
  12500. var READ_ONLY_MODE_CLASS = constant(Styles.resolve('readonly-mode'));
  12501. var EDIT_MODE_CLASS = constant(Styles.resolve('edit-mode'));
  12502. function OuterContainer (spec) {
  12503. var root = build$1(Container.sketch({
  12504. dom: { classes: [Styles.resolve('outer-container')].concat(spec.classes) },
  12505. containerBehaviours: derive$1([Swapping.config({
  12506. alpha: READ_ONLY_MODE_CLASS(),
  12507. omega: EDIT_MODE_CLASS()
  12508. })])
  12509. }));
  12510. return takeover(root);
  12511. }
  12512. function AndroidRealm (scrollIntoView) {
  12513. var alloy = OuterContainer({ classes: [Styles.resolve('android-container')] });
  12514. var toolbar = ScrollingToolbar();
  12515. var webapp = api$2();
  12516. var switchToEdit = CommonRealm.makeEditSwitch(webapp);
  12517. var socket = CommonRealm.makeSocket();
  12518. var dropup = build$2(noop, scrollIntoView);
  12519. alloy.add(toolbar.wrapper());
  12520. alloy.add(socket);
  12521. alloy.add(dropup.component());
  12522. var setToolbarGroups = function (rawGroups) {
  12523. var groups = toolbar.createGroups(rawGroups);
  12524. toolbar.setGroups(groups);
  12525. };
  12526. var setContextToolbar = function (rawGroups) {
  12527. var groups = toolbar.createGroups(rawGroups);
  12528. toolbar.setContextToolbar(groups);
  12529. };
  12530. var focusToolbar = function () {
  12531. toolbar.focus();
  12532. };
  12533. var restoreToolbar = function () {
  12534. toolbar.restoreToolbar();
  12535. };
  12536. var init = function (spec) {
  12537. webapp.set(AndroidWebapp.produce(spec));
  12538. };
  12539. var exit = function () {
  12540. webapp.run(function (w) {
  12541. w.exit();
  12542. Replacing.remove(socket, switchToEdit);
  12543. });
  12544. };
  12545. var updateMode = function (readOnly) {
  12546. CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
  12547. };
  12548. return {
  12549. system: constant(alloy),
  12550. element: alloy.element,
  12551. init: init,
  12552. exit: exit,
  12553. setToolbarGroups: setToolbarGroups,
  12554. setContextToolbar: setContextToolbar,
  12555. focusToolbar: focusToolbar,
  12556. restoreToolbar: restoreToolbar,
  12557. updateMode: updateMode,
  12558. socket: constant(socket),
  12559. dropup: constant(dropup)
  12560. };
  12561. }
  12562. var input$1 = function (parent, operation) {
  12563. var input = Element.fromTag('input');
  12564. setAll$1(input, {
  12565. opacity: '0',
  12566. position: 'absolute',
  12567. top: '-1000px',
  12568. left: '-1000px'
  12569. });
  12570. append(parent, input);
  12571. focus$1(input);
  12572. operation(input);
  12573. remove(input);
  12574. };
  12575. var CaptureBin = { input: input$1 };
  12576. var refreshInput = function (input) {
  12577. var start = input.dom().selectionStart;
  12578. var end = input.dom().selectionEnd;
  12579. var dir = input.dom().selectionDirection;
  12580. global$3.setTimeout(function () {
  12581. input.dom().setSelectionRange(start, end, dir);
  12582. focus$1(input);
  12583. }, 50);
  12584. };
  12585. var refresh$1 = function (winScope) {
  12586. var sel = winScope.getSelection();
  12587. if (sel.rangeCount > 0) {
  12588. var br = sel.getRangeAt(0);
  12589. var r = winScope.document.createRange();
  12590. r.setStart(br.startContainer, br.startOffset);
  12591. r.setEnd(br.endContainer, br.endOffset);
  12592. sel.removeAllRanges();
  12593. sel.addRange(r);
  12594. }
  12595. };
  12596. var CursorRefresh = {
  12597. refreshInput: refreshInput,
  12598. refresh: refresh$1
  12599. };
  12600. var resume$1 = function (cWin, frame) {
  12601. active().each(function (active) {
  12602. if (!eq(active, frame)) {
  12603. blur(active);
  12604. }
  12605. });
  12606. cWin.focus();
  12607. focus$1(Element.fromDom(cWin.document.body));
  12608. CursorRefresh.refresh(cWin);
  12609. };
  12610. var ResumeEditing$1 = { resume: resume$1 };
  12611. var stubborn = function (outerBody, cWin, page, frame) {
  12612. var toEditing = function () {
  12613. ResumeEditing$1.resume(cWin, frame);
  12614. };
  12615. var toReading = function () {
  12616. CaptureBin.input(outerBody, blur);
  12617. };
  12618. var captureInput = bind$3(page, 'keydown', function (evt) {
  12619. if (!contains([
  12620. 'input',
  12621. 'textarea'
  12622. ], name(evt.target()))) {
  12623. toEditing();
  12624. }
  12625. });
  12626. var onToolbarTouch = function () {
  12627. };
  12628. var destroy = function () {
  12629. captureInput.unbind();
  12630. };
  12631. return {
  12632. toReading: toReading,
  12633. toEditing: toEditing,
  12634. onToolbarTouch: onToolbarTouch,
  12635. destroy: destroy
  12636. };
  12637. };
  12638. var timid = function (outerBody, cWin, page, frame) {
  12639. var dismissKeyboard = function () {
  12640. blur(frame);
  12641. };
  12642. var onToolbarTouch = function () {
  12643. dismissKeyboard();
  12644. };
  12645. var toReading = function () {
  12646. dismissKeyboard();
  12647. };
  12648. var toEditing = function () {
  12649. ResumeEditing$1.resume(cWin, frame);
  12650. };
  12651. return {
  12652. toReading: toReading,
  12653. toEditing: toEditing,
  12654. onToolbarTouch: onToolbarTouch,
  12655. destroy: noop
  12656. };
  12657. };
  12658. var IosKeyboard = {
  12659. stubborn: stubborn,
  12660. timid: timid
  12661. };
  12662. var initEvents$1 = function (editorApi, iosApi, toolstrip, socket, dropup) {
  12663. var saveSelectionFirst = function () {
  12664. iosApi.run(function (api) {
  12665. api.highlightSelection();
  12666. });
  12667. };
  12668. var refreshIosSelection = function () {
  12669. iosApi.run(function (api) {
  12670. api.refreshSelection();
  12671. });
  12672. };
  12673. var scrollToY = function (yTop, height) {
  12674. var y = yTop - socket.dom().scrollTop;
  12675. iosApi.run(function (api) {
  12676. api.scrollIntoView(y, y + height);
  12677. });
  12678. };
  12679. var scrollToElement = function (target) {
  12680. scrollToY(iosApi, socket);
  12681. };
  12682. var scrollToCursor = function () {
  12683. editorApi.getCursorBox().each(function (box) {
  12684. scrollToY(box.top(), box.height());
  12685. });
  12686. };
  12687. var clearSelection = function () {
  12688. iosApi.run(function (api) {
  12689. api.clearSelection();
  12690. });
  12691. };
  12692. var clearAndRefresh = function () {
  12693. clearSelection();
  12694. refreshThrottle.throttle();
  12695. };
  12696. var refreshView = function () {
  12697. scrollToCursor();
  12698. iosApi.run(function (api) {
  12699. api.syncHeight();
  12700. });
  12701. };
  12702. var reposition = function () {
  12703. var toolbarHeight = get$5(toolstrip);
  12704. iosApi.run(function (api) {
  12705. api.setViewportOffset(toolbarHeight);
  12706. });
  12707. refreshIosSelection();
  12708. refreshView();
  12709. };
  12710. var toEditing = function () {
  12711. iosApi.run(function (api) {
  12712. api.toEditing();
  12713. });
  12714. };
  12715. var toReading = function () {
  12716. iosApi.run(function (api) {
  12717. api.toReading();
  12718. });
  12719. };
  12720. var onToolbarTouch = function (event) {
  12721. iosApi.run(function (api) {
  12722. api.onToolbarTouch(event);
  12723. });
  12724. };
  12725. var tapping = TappingEvent.monitor(editorApi);
  12726. var refreshThrottle = last$2(refreshView, 300);
  12727. var listeners = [
  12728. editorApi.onKeyup(clearAndRefresh),
  12729. editorApi.onNodeChanged(refreshIosSelection),
  12730. editorApi.onDomChanged(refreshThrottle.throttle),
  12731. editorApi.onDomChanged(refreshIosSelection),
  12732. editorApi.onScrollToCursor(function (tinyEvent) {
  12733. tinyEvent.preventDefault();
  12734. refreshThrottle.throttle();
  12735. }),
  12736. editorApi.onScrollToElement(function (event) {
  12737. scrollToElement(event.element());
  12738. }),
  12739. editorApi.onToEditing(toEditing),
  12740. editorApi.onToReading(toReading),
  12741. bind$3(editorApi.doc(), 'touchend', function (touchEvent) {
  12742. if (eq(editorApi.html(), touchEvent.target()) || eq(editorApi.body(), touchEvent.target())) ;
  12743. }),
  12744. bind$3(toolstrip, 'transitionend', function (transitionEvent) {
  12745. if (transitionEvent.raw().propertyName === 'height') {
  12746. reposition();
  12747. }
  12748. }),
  12749. capture$1(toolstrip, 'touchstart', function (touchEvent) {
  12750. saveSelectionFirst();
  12751. onToolbarTouch(touchEvent);
  12752. editorApi.onTouchToolstrip();
  12753. }),
  12754. bind$3(editorApi.body(), 'touchstart', function (evt) {
  12755. clearSelection();
  12756. editorApi.onTouchContent();
  12757. tapping.fireTouchstart(evt);
  12758. }),
  12759. tapping.onTouchmove(),
  12760. tapping.onTouchend(),
  12761. bind$3(editorApi.body(), 'click', function (event) {
  12762. event.kill();
  12763. }),
  12764. bind$3(toolstrip, 'touchmove', function () {
  12765. editorApi.onToolbarScrollStart();
  12766. })
  12767. ];
  12768. var destroy = function () {
  12769. each$1(listeners, function (l) {
  12770. l.unbind();
  12771. });
  12772. };
  12773. return { destroy: destroy };
  12774. };
  12775. var IosEvents = { initEvents: initEvents$1 };
  12776. function FakeSelection (win, frame) {
  12777. var doc = win.document;
  12778. var container = Element.fromTag('div');
  12779. add$2(container, Styles.resolve('unfocused-selections'));
  12780. append(Element.fromDom(doc.documentElement), container);
  12781. var onTouch = bind$3(container, 'touchstart', function (event) {
  12782. event.prevent();
  12783. ResumeEditing$1.resume(win, frame);
  12784. clear();
  12785. });
  12786. var make = function (rectangle) {
  12787. var span = Element.fromTag('span');
  12788. add$3(span, [
  12789. Styles.resolve('layer-editor'),
  12790. Styles.resolve('unfocused-selection')
  12791. ]);
  12792. setAll$1(span, {
  12793. left: rectangle.left() + 'px',
  12794. top: rectangle.top() + 'px',
  12795. width: rectangle.width() + 'px',
  12796. height: rectangle.height() + 'px'
  12797. });
  12798. return span;
  12799. };
  12800. var update = function () {
  12801. clear();
  12802. var rectangles = Rectangles.getRectangles(win);
  12803. var spans = map$1(rectangles, make);
  12804. append$1(container, spans);
  12805. };
  12806. var clear = function () {
  12807. empty(container);
  12808. };
  12809. var destroy = function () {
  12810. onTouch.unbind();
  12811. remove(container);
  12812. };
  12813. var isActive = function () {
  12814. return children(container).length > 0;
  12815. };
  12816. return {
  12817. update: update,
  12818. isActive: isActive,
  12819. destroy: destroy,
  12820. clear: clear
  12821. };
  12822. }
  12823. var nu$7 = function (baseFn) {
  12824. var data = Option.none();
  12825. var callbacks = [];
  12826. var map = function (f) {
  12827. return nu$7(function (nCallback) {
  12828. get(function (data) {
  12829. nCallback(f(data));
  12830. });
  12831. });
  12832. };
  12833. var get = function (nCallback) {
  12834. if (isReady())
  12835. call(nCallback);
  12836. else
  12837. callbacks.push(nCallback);
  12838. };
  12839. var set = function (x) {
  12840. data = Option.some(x);
  12841. run(callbacks);
  12842. callbacks = [];
  12843. };
  12844. var isReady = function () {
  12845. return data.isSome();
  12846. };
  12847. var run = function (cbs) {
  12848. each$1(cbs, call);
  12849. };
  12850. var call = function (cb) {
  12851. data.each(function (x) {
  12852. domGlobals.setTimeout(function () {
  12853. cb(x);
  12854. }, 0);
  12855. });
  12856. };
  12857. baseFn(set);
  12858. return {
  12859. get: get,
  12860. map: map,
  12861. isReady: isReady
  12862. };
  12863. };
  12864. var pure$1 = function (a) {
  12865. return nu$7(function (callback) {
  12866. callback(a);
  12867. });
  12868. };
  12869. var LazyValue = {
  12870. nu: nu$7,
  12871. pure: pure$1
  12872. };
  12873. var bounce = function (f) {
  12874. return function () {
  12875. var args = [];
  12876. for (var _i = 0; _i < arguments.length; _i++) {
  12877. args[_i] = arguments[_i];
  12878. }
  12879. var me = this;
  12880. domGlobals.setTimeout(function () {
  12881. f.apply(me, args);
  12882. }, 0);
  12883. };
  12884. };
  12885. var nu$8 = function (baseFn) {
  12886. var get = function (callback) {
  12887. baseFn(bounce(callback));
  12888. };
  12889. var map = function (fab) {
  12890. return nu$8(function (callback) {
  12891. get(function (a) {
  12892. var value = fab(a);
  12893. callback(value);
  12894. });
  12895. });
  12896. };
  12897. var bind = function (aFutureB) {
  12898. return nu$8(function (callback) {
  12899. get(function (a) {
  12900. aFutureB(a).get(callback);
  12901. });
  12902. });
  12903. };
  12904. var anonBind = function (futureB) {
  12905. return nu$8(function (callback) {
  12906. get(function (a) {
  12907. futureB.get(callback);
  12908. });
  12909. });
  12910. };
  12911. var toLazy = function () {
  12912. return LazyValue.nu(get);
  12913. };
  12914. var toCached = function () {
  12915. var cache = null;
  12916. return nu$8(function (callback) {
  12917. if (cache === null) {
  12918. cache = toLazy();
  12919. }
  12920. cache.get(callback);
  12921. });
  12922. };
  12923. return {
  12924. map: map,
  12925. bind: bind,
  12926. anonBind: anonBind,
  12927. toLazy: toLazy,
  12928. toCached: toCached,
  12929. get: get
  12930. };
  12931. };
  12932. var pure$2 = function (a) {
  12933. return nu$8(function (callback) {
  12934. callback(a);
  12935. });
  12936. };
  12937. var Future = {
  12938. nu: nu$8,
  12939. pure: pure$2
  12940. };
  12941. var adjust = function (value, destination, amount) {
  12942. if (Math.abs(value - destination) <= amount) {
  12943. return Option.none();
  12944. } else if (value < destination) {
  12945. return Option.some(value + amount);
  12946. } else {
  12947. return Option.some(value - amount);
  12948. }
  12949. };
  12950. var create$4 = function () {
  12951. var interval = null;
  12952. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  12953. var finished = false;
  12954. var finish = function (v) {
  12955. finished = true;
  12956. doFinish(v);
  12957. };
  12958. global$3.clearInterval(interval);
  12959. var abort = function (v) {
  12960. global$3.clearInterval(interval);
  12961. finish(v);
  12962. };
  12963. interval = global$3.setInterval(function () {
  12964. var value = getCurrent();
  12965. adjust(value, destination, amount).fold(function () {
  12966. global$3.clearInterval(interval);
  12967. finish(destination);
  12968. }, function (s) {
  12969. increment(s, abort);
  12970. if (!finished) {
  12971. var newValue = getCurrent();
  12972. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  12973. global$3.clearInterval(interval);
  12974. finish(destination);
  12975. }
  12976. }
  12977. });
  12978. }, rate);
  12979. };
  12980. return { animate: animate };
  12981. };
  12982. var SmoothAnimation = {
  12983. create: create$4,
  12984. adjust: adjust
  12985. };
  12986. var findDevice = function (deviceWidth, deviceHeight) {
  12987. var devices = [
  12988. {
  12989. width: 320,
  12990. height: 480,
  12991. keyboard: {
  12992. portrait: 300,
  12993. landscape: 240
  12994. }
  12995. },
  12996. {
  12997. width: 320,
  12998. height: 568,
  12999. keyboard: {
  13000. portrait: 300,
  13001. landscape: 240
  13002. }
  13003. },
  13004. {
  13005. width: 375,
  13006. height: 667,
  13007. keyboard: {
  13008. portrait: 305,
  13009. landscape: 240
  13010. }
  13011. },
  13012. {
  13013. width: 414,
  13014. height: 736,
  13015. keyboard: {
  13016. portrait: 320,
  13017. landscape: 240
  13018. }
  13019. },
  13020. {
  13021. width: 768,
  13022. height: 1024,
  13023. keyboard: {
  13024. portrait: 320,
  13025. landscape: 400
  13026. }
  13027. },
  13028. {
  13029. width: 1024,
  13030. height: 1366,
  13031. keyboard: {
  13032. portrait: 380,
  13033. landscape: 460
  13034. }
  13035. }
  13036. ];
  13037. return findMap(devices, function (device) {
  13038. return deviceWidth <= device.width && deviceHeight <= device.height ? Option.some(device.keyboard) : Option.none();
  13039. }).getOr({
  13040. portrait: deviceHeight / 5,
  13041. landscape: deviceWidth / 4
  13042. });
  13043. };
  13044. var Devices = { findDevice: findDevice };
  13045. var softKeyboardLimits = function (outerWindow) {
  13046. return Devices.findDevice(outerWindow.screen.width, outerWindow.screen.height);
  13047. };
  13048. var accountableKeyboardHeight = function (outerWindow) {
  13049. var portrait = Orientation.get(outerWindow).isPortrait();
  13050. var limits = softKeyboardLimits(outerWindow);
  13051. var keyboard = portrait ? limits.portrait : limits.landscape;
  13052. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  13053. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  13054. };
  13055. var getGreenzone = function (socket, dropup) {
  13056. var outerWindow = owner(socket).dom().defaultView;
  13057. var viewportHeight = get$5(socket) + get$5(dropup);
  13058. var acc = accountableKeyboardHeight(outerWindow);
  13059. return viewportHeight - acc;
  13060. };
  13061. var updatePadding = function (contentBody, socket, dropup) {
  13062. var greenzoneHeight = getGreenzone(socket, dropup);
  13063. var deltaHeight = get$5(socket) + get$5(dropup) - greenzoneHeight;
  13064. set$3(contentBody, 'padding-bottom', deltaHeight + 'px');
  13065. };
  13066. var DeviceZones = {
  13067. getGreenzone: getGreenzone,
  13068. updatePadding: updatePadding
  13069. };
  13070. var fixture = Adt.generate([
  13071. {
  13072. fixed: [
  13073. 'element',
  13074. 'property',
  13075. 'offsetY'
  13076. ]
  13077. },
  13078. {
  13079. scroller: [
  13080. 'element',
  13081. 'offsetY'
  13082. ]
  13083. }
  13084. ]);
  13085. var yFixedData = 'data-' + Styles.resolve('position-y-fixed');
  13086. var yFixedProperty = 'data-' + Styles.resolve('y-property');
  13087. var yScrollingData = 'data-' + Styles.resolve('scrolling');
  13088. var windowSizeData = 'data-' + Styles.resolve('last-window-height');
  13089. var getYFixedData = function (element) {
  13090. return DataAttributes.safeParse(element, yFixedData);
  13091. };
  13092. var getYFixedProperty = function (element) {
  13093. return get$1(element, yFixedProperty);
  13094. };
  13095. var getLastWindowSize = function (element) {
  13096. return DataAttributes.safeParse(element, windowSizeData);
  13097. };
  13098. var classifyFixed = function (element, offsetY) {
  13099. var prop = getYFixedProperty(element);
  13100. return fixture.fixed(element, prop, offsetY);
  13101. };
  13102. var classifyScrolling = function (element, offsetY) {
  13103. return fixture.scroller(element, offsetY);
  13104. };
  13105. var classify = function (element) {
  13106. var offsetY = getYFixedData(element);
  13107. var classifier = get$1(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  13108. return classifier(element, offsetY);
  13109. };
  13110. var findFixtures = function (container) {
  13111. var candidates = descendants(container, '[' + yFixedData + ']');
  13112. return map$1(candidates, classify);
  13113. };
  13114. var takeoverToolbar = function (toolbar) {
  13115. var oldToolbarStyle = get$1(toolbar, 'style');
  13116. setAll$1(toolbar, {
  13117. position: 'absolute',
  13118. top: '0px'
  13119. });
  13120. set(toolbar, yFixedData, '0px');
  13121. set(toolbar, yFixedProperty, 'top');
  13122. var restore = function () {
  13123. set(toolbar, 'style', oldToolbarStyle || '');
  13124. remove$1(toolbar, yFixedData);
  13125. remove$1(toolbar, yFixedProperty);
  13126. };
  13127. return { restore: restore };
  13128. };
  13129. var takeoverViewport = function (toolbarHeight, height, viewport) {
  13130. var oldViewportStyle = get$1(viewport, 'style');
  13131. Scrollable.register(viewport);
  13132. setAll$1(viewport, {
  13133. position: 'absolute',
  13134. height: height + 'px',
  13135. width: '100%',
  13136. top: toolbarHeight + 'px'
  13137. });
  13138. set(viewport, yFixedData, toolbarHeight + 'px');
  13139. set(viewport, yScrollingData, 'true');
  13140. set(viewport, yFixedProperty, 'top');
  13141. var restore = function () {
  13142. Scrollable.deregister(viewport);
  13143. set(viewport, 'style', oldViewportStyle || '');
  13144. remove$1(viewport, yFixedData);
  13145. remove$1(viewport, yScrollingData);
  13146. remove$1(viewport, yFixedProperty);
  13147. };
  13148. return { restore: restore };
  13149. };
  13150. var takeoverDropup = function (dropup, toolbarHeight, viewportHeight) {
  13151. var oldDropupStyle = get$1(dropup, 'style');
  13152. setAll$1(dropup, {
  13153. position: 'absolute',
  13154. bottom: '0px'
  13155. });
  13156. set(dropup, yFixedData, '0px');
  13157. set(dropup, yFixedProperty, 'bottom');
  13158. var restore = function () {
  13159. set(dropup, 'style', oldDropupStyle || '');
  13160. remove$1(dropup, yFixedData);
  13161. remove$1(dropup, yFixedProperty);
  13162. };
  13163. return { restore: restore };
  13164. };
  13165. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  13166. var outerWindow = owner(viewport).dom().defaultView;
  13167. var winH = outerWindow.innerHeight;
  13168. set(viewport, windowSizeData, winH + 'px');
  13169. return winH - toolbarHeight - dropupHeight;
  13170. };
  13171. var takeover$1 = function (viewport, contentBody, toolbar, dropup) {
  13172. var outerWindow = owner(viewport).dom().defaultView;
  13173. var toolbarSetup = takeoverToolbar(toolbar);
  13174. var toolbarHeight = get$5(toolbar);
  13175. var dropupHeight = get$5(dropup);
  13176. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  13177. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  13178. var dropupSetup = takeoverDropup(dropup, toolbarHeight, viewportHeight);
  13179. var isActive = true;
  13180. var restore = function () {
  13181. isActive = false;
  13182. toolbarSetup.restore();
  13183. viewportSetup.restore();
  13184. dropupSetup.restore();
  13185. };
  13186. var isExpanding = function () {
  13187. var currentWinHeight = outerWindow.innerHeight;
  13188. var lastWinHeight = getLastWindowSize(viewport);
  13189. return currentWinHeight > lastWinHeight;
  13190. };
  13191. var refresh = function () {
  13192. if (isActive) {
  13193. var newToolbarHeight = get$5(toolbar);
  13194. var dropupHeight_1 = get$5(dropup);
  13195. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  13196. set(viewport, yFixedData, newToolbarHeight + 'px');
  13197. set$3(viewport, 'height', newHeight + 'px');
  13198. DeviceZones.updatePadding(contentBody, viewport, dropup);
  13199. }
  13200. };
  13201. var setViewportOffset = function (newYOffset) {
  13202. var offsetPx = newYOffset + 'px';
  13203. set(viewport, yFixedData, offsetPx);
  13204. refresh();
  13205. };
  13206. DeviceZones.updatePadding(contentBody, viewport, dropup);
  13207. return {
  13208. setViewportOffset: setViewportOffset,
  13209. isExpanding: isExpanding,
  13210. isShrinking: not(isExpanding),
  13211. refresh: refresh,
  13212. restore: restore
  13213. };
  13214. };
  13215. var IosViewport = {
  13216. findFixtures: findFixtures,
  13217. takeover: takeover$1,
  13218. getYFixedData: getYFixedData
  13219. };
  13220. var animator = SmoothAnimation.create();
  13221. var ANIMATION_STEP = 15;
  13222. var NUM_TOP_ANIMATION_FRAMES = 10;
  13223. var ANIMATION_RATE = 10;
  13224. var lastScroll = 'data-' + Styles.resolve('last-scroll-top');
  13225. var getTop = function (element) {
  13226. var raw = getRaw(element, 'top').getOr('0');
  13227. return parseInt(raw, 10);
  13228. };
  13229. var getScrollTop = function (element) {
  13230. return parseInt(element.dom().scrollTop, 10);
  13231. };
  13232. var moveScrollAndTop = function (element, destination, finalTop) {
  13233. return Future.nu(function (callback) {
  13234. var getCurrent = curry(getScrollTop, element);
  13235. var update = function (newScroll) {
  13236. element.dom().scrollTop = newScroll;
  13237. set$3(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  13238. };
  13239. var finish = function () {
  13240. element.dom().scrollTop = destination;
  13241. set$3(element, 'top', finalTop + 'px');
  13242. callback(destination);
  13243. };
  13244. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  13245. });
  13246. };
  13247. var moveOnlyScroll = function (element, destination) {
  13248. return Future.nu(function (callback) {
  13249. var getCurrent = curry(getScrollTop, element);
  13250. set(element, lastScroll, getCurrent());
  13251. var update = function (newScroll, abort) {
  13252. var previous = DataAttributes.safeParse(element, lastScroll);
  13253. if (previous !== element.dom().scrollTop) {
  13254. abort(element.dom().scrollTop);
  13255. } else {
  13256. element.dom().scrollTop = newScroll;
  13257. set(element, lastScroll, newScroll);
  13258. }
  13259. };
  13260. var finish = function () {
  13261. element.dom().scrollTop = destination;
  13262. set(element, lastScroll, destination);
  13263. callback(destination);
  13264. };
  13265. var distance = Math.abs(destination - getCurrent());
  13266. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  13267. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  13268. });
  13269. };
  13270. var moveOnlyTop = function (element, destination) {
  13271. return Future.nu(function (callback) {
  13272. var getCurrent = curry(getTop, element);
  13273. var update = function (newTop) {
  13274. set$3(element, 'top', newTop + 'px');
  13275. };
  13276. var finish = function () {
  13277. update(destination);
  13278. callback(destination);
  13279. };
  13280. var distance = Math.abs(destination - getCurrent());
  13281. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  13282. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  13283. });
  13284. };
  13285. var updateTop = function (element, amount) {
  13286. var newTop = amount + IosViewport.getYFixedData(element) + 'px';
  13287. set$3(element, 'top', newTop);
  13288. };
  13289. var moveWindowScroll = function (toolbar, viewport, destY) {
  13290. var outerWindow = owner(toolbar).dom().defaultView;
  13291. return Future.nu(function (callback) {
  13292. updateTop(toolbar, destY);
  13293. updateTop(viewport, destY);
  13294. outerWindow.scrollTo(0, destY);
  13295. callback(destY);
  13296. });
  13297. };
  13298. var IosScrolling = {
  13299. moveScrollAndTop: moveScrollAndTop,
  13300. moveOnlyScroll: moveOnlyScroll,
  13301. moveOnlyTop: moveOnlyTop,
  13302. moveWindowScroll: moveWindowScroll
  13303. };
  13304. function BackgroundActivity (doAction) {
  13305. var action = Cell(LazyValue.pure({}));
  13306. var start = function (value) {
  13307. var future = LazyValue.nu(function (callback) {
  13308. return doAction(value).get(callback);
  13309. });
  13310. action.set(future);
  13311. };
  13312. var idle = function (g) {
  13313. action.get().get(function () {
  13314. g();
  13315. });
  13316. };
  13317. return {
  13318. start: start,
  13319. idle: idle
  13320. };
  13321. }
  13322. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  13323. var greenzone = DeviceZones.getGreenzone(socket, dropup);
  13324. var refreshCursor = curry(CursorRefresh.refresh, cWin);
  13325. if (top > greenzone || bottom > greenzone) {
  13326. IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop - greenzone + bottom).get(refreshCursor);
  13327. } else if (top < 0) {
  13328. IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop + top).get(refreshCursor);
  13329. }
  13330. };
  13331. var Greenzone = { scrollIntoView: scrollIntoView };
  13332. var par = function (asyncValues, nu) {
  13333. return nu(function (callback) {
  13334. var r = [];
  13335. var count = 0;
  13336. var cb = function (i) {
  13337. return function (value) {
  13338. r[i] = value;
  13339. count++;
  13340. if (count >= asyncValues.length) {
  13341. callback(r);
  13342. }
  13343. };
  13344. };
  13345. if (asyncValues.length === 0) {
  13346. callback([]);
  13347. } else {
  13348. each$1(asyncValues, function (asyncValue, i) {
  13349. asyncValue.get(cb(i));
  13350. });
  13351. }
  13352. });
  13353. };
  13354. var par$1 = function (futures) {
  13355. return par(futures, Future.nu);
  13356. };
  13357. var updateFixed = function (element, property, winY, offsetY) {
  13358. var destination = winY + offsetY;
  13359. set$3(element, property, destination + 'px');
  13360. return Future.pure(offsetY);
  13361. };
  13362. var updateScrollingFixed = function (element, winY, offsetY) {
  13363. var destTop = winY + offsetY;
  13364. var oldProp = getRaw(element, 'top').getOr(offsetY);
  13365. var delta = destTop - parseInt(oldProp, 10);
  13366. var destScroll = element.dom().scrollTop + delta;
  13367. return IosScrolling.moveScrollAndTop(element, destScroll, destTop);
  13368. };
  13369. var updateFixture = function (fixture, winY) {
  13370. return fixture.fold(function (element, property, offsetY) {
  13371. return updateFixed(element, property, winY, offsetY);
  13372. }, function (element, offsetY) {
  13373. return updateScrollingFixed(element, winY, offsetY);
  13374. });
  13375. };
  13376. var updatePositions = function (container, winY) {
  13377. var fixtures = IosViewport.findFixtures(container);
  13378. var updates = map$1(fixtures, function (fixture) {
  13379. return updateFixture(fixture, winY);
  13380. });
  13381. return par$1(updates);
  13382. };
  13383. var IosUpdates = { updatePositions: updatePositions };
  13384. var VIEW_MARGIN = 5;
  13385. var register$2 = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  13386. var scroller = BackgroundActivity(function (y) {
  13387. return IosScrolling.moveWindowScroll(toolstrip, socket, y);
  13388. });
  13389. var scrollBounds = function () {
  13390. var rects = Rectangles.getRectangles(cWin);
  13391. return Option.from(rects[0]).bind(function (rect) {
  13392. var viewTop = rect.top() - socket.dom().scrollTop;
  13393. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  13394. return outside ? Option.some({
  13395. top: constant(viewTop),
  13396. bottom: constant(viewTop + rect.height())
  13397. }) : Option.none();
  13398. });
  13399. };
  13400. var scrollThrottle = last$2(function () {
  13401. scroller.idle(function () {
  13402. IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(function () {
  13403. var extraScroll = scrollBounds();
  13404. extraScroll.each(function (extra) {
  13405. socket.dom().scrollTop = socket.dom().scrollTop + extra.top();
  13406. });
  13407. scroller.start(0);
  13408. structure.refresh();
  13409. });
  13410. });
  13411. }, 1000);
  13412. var onScroll = bind$3(Element.fromDom(outerWindow), 'scroll', function () {
  13413. if (outerWindow.pageYOffset < 0) {
  13414. return;
  13415. }
  13416. scrollThrottle.throttle();
  13417. });
  13418. IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(identity);
  13419. return { unbind: onScroll.unbind };
  13420. };
  13421. var setup$3 = function (bag) {
  13422. var cWin = bag.cWin();
  13423. var ceBody = bag.ceBody();
  13424. var socket = bag.socket();
  13425. var toolstrip = bag.toolstrip();
  13426. var toolbar = bag.toolbar();
  13427. var contentElement = bag.contentElement();
  13428. var keyboardType = bag.keyboardType();
  13429. var outerWindow = bag.outerWindow();
  13430. var dropup = bag.dropup();
  13431. var structure = IosViewport.takeover(socket, ceBody, toolstrip, dropup);
  13432. var keyboardModel = keyboardType(bag.outerBody(), cWin, body(), contentElement, toolstrip, toolbar);
  13433. var toEditing = function () {
  13434. keyboardModel.toEditing();
  13435. clearSelection();
  13436. };
  13437. var toReading = function () {
  13438. keyboardModel.toReading();
  13439. };
  13440. var onToolbarTouch = function (event) {
  13441. keyboardModel.onToolbarTouch(event);
  13442. };
  13443. var onOrientation = Orientation.onChange(outerWindow, {
  13444. onChange: noop,
  13445. onReady: structure.refresh
  13446. });
  13447. onOrientation.onAdjustment(function () {
  13448. structure.refresh();
  13449. });
  13450. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  13451. if (structure.isExpanding()) {
  13452. structure.refresh();
  13453. }
  13454. });
  13455. var onScroll = register$2(toolstrip, socket, bag.outerBody(), outerWindow, structure, cWin);
  13456. var unfocusedSelection = FakeSelection(cWin, contentElement);
  13457. var refreshSelection = function () {
  13458. if (unfocusedSelection.isActive()) {
  13459. unfocusedSelection.update();
  13460. }
  13461. };
  13462. var highlightSelection = function () {
  13463. unfocusedSelection.update();
  13464. };
  13465. var clearSelection = function () {
  13466. unfocusedSelection.clear();
  13467. };
  13468. var scrollIntoView = function (top, bottom) {
  13469. Greenzone.scrollIntoView(cWin, socket, dropup, top, bottom);
  13470. };
  13471. var syncHeight = function () {
  13472. set$3(contentElement, 'height', contentElement.dom().contentWindow.document.body.scrollHeight + 'px');
  13473. };
  13474. var setViewportOffset = function (newYOffset) {
  13475. structure.setViewportOffset(newYOffset);
  13476. IosScrolling.moveOnlyTop(socket, newYOffset).get(identity);
  13477. };
  13478. var destroy = function () {
  13479. structure.restore();
  13480. onOrientation.destroy();
  13481. onScroll.unbind();
  13482. onResize.unbind();
  13483. keyboardModel.destroy();
  13484. unfocusedSelection.destroy();
  13485. CaptureBin.input(body(), blur);
  13486. };
  13487. return {
  13488. toEditing: toEditing,
  13489. toReading: toReading,
  13490. onToolbarTouch: onToolbarTouch,
  13491. refreshSelection: refreshSelection,
  13492. clearSelection: clearSelection,
  13493. highlightSelection: highlightSelection,
  13494. scrollIntoView: scrollIntoView,
  13495. updateToolbarPadding: noop,
  13496. setViewportOffset: setViewportOffset,
  13497. syncHeight: syncHeight,
  13498. refreshStructure: structure.refresh,
  13499. destroy: destroy
  13500. };
  13501. };
  13502. var IosSetup = { setup: setup$3 };
  13503. var create$5 = function (platform, mask) {
  13504. var meta = MetaViewport.tag();
  13505. var priorState = value$3();
  13506. var scrollEvents = value$3();
  13507. var iosApi = api$2();
  13508. var iosEvents = api$2();
  13509. var enter = function () {
  13510. mask.hide();
  13511. var doc = Element.fromDom(domGlobals.document);
  13512. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  13513. priorState.set({
  13514. socketHeight: getRaw(platform.socket, 'height'),
  13515. iframeHeight: getRaw(editorApi.frame(), 'height'),
  13516. outerScroll: domGlobals.document.body.scrollTop
  13517. });
  13518. scrollEvents.set({ exclusives: Scrollables.exclusive(doc, '.' + Scrollable.scrollable()) });
  13519. add$2(platform.container, Styles.resolve('fullscreen-maximized'));
  13520. Thor.clobberStyles(platform.container, editorApi.body());
  13521. meta.maximize();
  13522. set$3(platform.socket, 'overflow', 'scroll');
  13523. set$3(platform.socket, '-webkit-overflow-scrolling', 'touch');
  13524. focus$1(editorApi.body());
  13525. var setupBag = MixedBag([
  13526. 'cWin',
  13527. 'ceBody',
  13528. 'socket',
  13529. 'toolstrip',
  13530. 'toolbar',
  13531. 'dropup',
  13532. 'contentElement',
  13533. 'cursor',
  13534. 'keyboardType',
  13535. 'isScrolling',
  13536. 'outerWindow',
  13537. 'outerBody'
  13538. ], []);
  13539. iosApi.set(IosSetup.setup(setupBag({
  13540. cWin: editorApi.win(),
  13541. ceBody: editorApi.body(),
  13542. socket: platform.socket,
  13543. toolstrip: platform.toolstrip,
  13544. toolbar: platform.toolbar,
  13545. dropup: platform.dropup.element(),
  13546. contentElement: editorApi.frame(),
  13547. cursor: noop,
  13548. outerBody: platform.body,
  13549. outerWindow: platform.win,
  13550. keyboardType: IosKeyboard.stubborn,
  13551. isScrolling: function () {
  13552. var scrollValue = scrollEvents;
  13553. return scrollValue.get().exists(function (s) {
  13554. return s.socket.isScrolling();
  13555. });
  13556. }
  13557. })));
  13558. iosApi.run(function (api) {
  13559. api.syncHeight();
  13560. });
  13561. iosEvents.set(IosEvents.initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  13562. });
  13563. };
  13564. var exit = function () {
  13565. meta.restore();
  13566. iosEvents.clear();
  13567. iosApi.clear();
  13568. mask.show();
  13569. priorState.on(function (s) {
  13570. s.socketHeight.each(function (h) {
  13571. set$3(platform.socket, 'height', h);
  13572. });
  13573. s.iframeHeight.each(function (h) {
  13574. set$3(platform.editor.getFrame(), 'height', h);
  13575. });
  13576. domGlobals.document.body.scrollTop = s.scrollTop;
  13577. });
  13578. priorState.clear();
  13579. scrollEvents.on(function (s) {
  13580. s.exclusives.unbind();
  13581. });
  13582. scrollEvents.clear();
  13583. remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
  13584. Thor.restoreStyles();
  13585. Scrollable.deregister(platform.toolbar);
  13586. remove$5(platform.socket, 'overflow');
  13587. remove$5(platform.socket, '-webkit-overflow-scrolling');
  13588. blur(platform.editor.getFrame());
  13589. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  13590. editorApi.clearSelection();
  13591. });
  13592. };
  13593. var refreshStructure = function () {
  13594. iosApi.run(function (api) {
  13595. api.refreshStructure();
  13596. });
  13597. };
  13598. return {
  13599. enter: enter,
  13600. refreshStructure: refreshStructure,
  13601. exit: exit
  13602. };
  13603. };
  13604. var IosMode = { create: create$5 };
  13605. var produce$1 = function (raw) {
  13606. var mobile = asRawOrDie('Getting IosWebapp schema', MobileSchema, raw);
  13607. set$3(mobile.toolstrip, 'width', '100%');
  13608. set$3(mobile.container, 'position', 'relative');
  13609. var onView = function () {
  13610. mobile.setReadOnly(mobile.readOnlyOnInit());
  13611. mode.enter();
  13612. };
  13613. var mask = build$1(TapToEditMask.sketch(onView, mobile.translate));
  13614. mobile.alloy.add(mask);
  13615. var maskApi = {
  13616. show: function () {
  13617. mobile.alloy.add(mask);
  13618. },
  13619. hide: function () {
  13620. mobile.alloy.remove(mask);
  13621. }
  13622. };
  13623. var mode = IosMode.create(mobile, maskApi);
  13624. return {
  13625. setReadOnly: mobile.setReadOnly,
  13626. refreshStructure: mode.refreshStructure,
  13627. enter: mode.enter,
  13628. exit: mode.exit,
  13629. destroy: noop
  13630. };
  13631. };
  13632. var IosWebapp = { produce: produce$1 };
  13633. function IosRealm (scrollIntoView) {
  13634. var alloy = OuterContainer({ classes: [Styles.resolve('ios-container')] });
  13635. var toolbar = ScrollingToolbar();
  13636. var webapp = api$2();
  13637. var switchToEdit = CommonRealm.makeEditSwitch(webapp);
  13638. var socket = CommonRealm.makeSocket();
  13639. var dropup = build$2(function () {
  13640. webapp.run(function (w) {
  13641. w.refreshStructure();
  13642. });
  13643. }, scrollIntoView);
  13644. alloy.add(toolbar.wrapper());
  13645. alloy.add(socket);
  13646. alloy.add(dropup.component());
  13647. var setToolbarGroups = function (rawGroups) {
  13648. var groups = toolbar.createGroups(rawGroups);
  13649. toolbar.setGroups(groups);
  13650. };
  13651. var setContextToolbar = function (rawGroups) {
  13652. var groups = toolbar.createGroups(rawGroups);
  13653. toolbar.setContextToolbar(groups);
  13654. };
  13655. var focusToolbar = function () {
  13656. toolbar.focus();
  13657. };
  13658. var restoreToolbar = function () {
  13659. toolbar.restoreToolbar();
  13660. };
  13661. var init = function (spec) {
  13662. webapp.set(IosWebapp.produce(spec));
  13663. };
  13664. var exit = function () {
  13665. webapp.run(function (w) {
  13666. Replacing.remove(socket, switchToEdit);
  13667. w.exit();
  13668. });
  13669. };
  13670. var updateMode = function (readOnly) {
  13671. CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
  13672. };
  13673. return {
  13674. system: constant(alloy),
  13675. element: alloy.element,
  13676. init: init,
  13677. exit: exit,
  13678. setToolbarGroups: setToolbarGroups,
  13679. setContextToolbar: setContextToolbar,
  13680. focusToolbar: focusToolbar,
  13681. restoreToolbar: restoreToolbar,
  13682. updateMode: updateMode,
  13683. socket: constant(socket),
  13684. dropup: constant(dropup)
  13685. };
  13686. }
  13687. var global$4 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  13688. var derive$3 = function (editor) {
  13689. var base = readOptFrom$1(editor.settings, 'skin_url').fold(function () {
  13690. return global$4.baseURL + '/skins/ui/oxide';
  13691. }, function (url) {
  13692. return url;
  13693. });
  13694. return {
  13695. content: base + '/content.mobile.min.css',
  13696. ui: base + '/skin.mobile.min.css'
  13697. };
  13698. };
  13699. var CssUrls = { derive: derive$3 };
  13700. var fontSizes = [
  13701. 'x-small',
  13702. 'small',
  13703. 'medium',
  13704. 'large',
  13705. 'x-large'
  13706. ];
  13707. var fireChange = function (realm, command, state) {
  13708. realm.system().broadcastOn([TinyChannels.formatChanged()], {
  13709. command: command,
  13710. state: state
  13711. });
  13712. };
  13713. var init$5 = function (realm, editor) {
  13714. var allFormats = keys(editor.formatter.get());
  13715. each$1(allFormats, function (command) {
  13716. editor.formatter.formatChanged(command, function (state) {
  13717. fireChange(realm, command, state);
  13718. });
  13719. });
  13720. each$1([
  13721. 'ul',
  13722. 'ol'
  13723. ], function (command) {
  13724. editor.selection.selectorChanged(command, function (state, data) {
  13725. fireChange(realm, command, state);
  13726. });
  13727. });
  13728. };
  13729. var FormatChangers = {
  13730. init: init$5,
  13731. fontSizes: constant(fontSizes)
  13732. };
  13733. var fireSkinLoaded = function (editor) {
  13734. var done = function () {
  13735. editor._skinLoaded = true;
  13736. editor.fire('SkinLoaded');
  13737. };
  13738. return function () {
  13739. if (editor.initialized) {
  13740. done();
  13741. } else {
  13742. editor.on('init', done);
  13743. }
  13744. };
  13745. };
  13746. var SkinLoaded = { fireSkinLoaded: fireSkinLoaded };
  13747. var READING = constant('toReading');
  13748. var EDITING = constant('toEditing');
  13749. var renderMobileTheme = function (editor) {
  13750. var renderUI = function () {
  13751. var targetNode = editor.getElement();
  13752. var cssUrls = CssUrls.derive(editor);
  13753. if (isSkinDisabled(editor) === false) {
  13754. editor.contentCSS.push(cssUrls.content);
  13755. global.DOM.styleSheetLoader.load(cssUrls.ui, SkinLoaded.fireSkinLoaded(editor));
  13756. } else {
  13757. SkinLoaded.fireSkinLoaded(editor)();
  13758. }
  13759. var doScrollIntoView = function () {
  13760. editor.fire('ScrollIntoView');
  13761. };
  13762. var realm = PlatformDetection$1.detect().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  13763. var original = Element.fromDom(targetNode);
  13764. attachSystemAfter(original, realm.system());
  13765. var findFocusIn = function (elem) {
  13766. return search(elem).bind(function (focused) {
  13767. return realm.system().getByDom(focused).toOption();
  13768. });
  13769. };
  13770. var outerWindow = targetNode.ownerDocument.defaultView;
  13771. var orientation = Orientation.onChange(outerWindow, {
  13772. onChange: function () {
  13773. var alloy = realm.system();
  13774. alloy.broadcastOn([TinyChannels.orientationChanged()], { width: Orientation.getActualWidth(outerWindow) });
  13775. },
  13776. onReady: noop
  13777. });
  13778. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  13779. if (ro === false) {
  13780. editor.selection.collapse();
  13781. }
  13782. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  13783. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  13784. editor.setMode(ro === true ? 'readonly' : 'design');
  13785. editor.fire(ro === true ? READING() : EDITING());
  13786. realm.updateMode(ro);
  13787. };
  13788. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  13789. var dynamic = dynamicGroup.get();
  13790. var toolbars = {
  13791. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  13792. main: dynamic.backToMask.concat(mainGroups.get())
  13793. };
  13794. return toolbars;
  13795. };
  13796. var bindHandler = function (label, handler) {
  13797. editor.on(label, handler);
  13798. return {
  13799. unbind: function () {
  13800. editor.off(label);
  13801. }
  13802. };
  13803. };
  13804. editor.on('init', function () {
  13805. realm.init({
  13806. editor: {
  13807. getFrame: function () {
  13808. return Element.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  13809. },
  13810. onDomChanged: function () {
  13811. return { unbind: noop };
  13812. },
  13813. onToReading: function (handler) {
  13814. return bindHandler(READING(), handler);
  13815. },
  13816. onToEditing: function (handler) {
  13817. return bindHandler(EDITING(), handler);
  13818. },
  13819. onScrollToCursor: function (handler) {
  13820. editor.on('ScrollIntoView', function (tinyEvent) {
  13821. handler(tinyEvent);
  13822. });
  13823. var unbind = function () {
  13824. editor.off('ScrollIntoView');
  13825. orientation.destroy();
  13826. };
  13827. return { unbind: unbind };
  13828. },
  13829. onTouchToolstrip: function () {
  13830. hideDropup();
  13831. },
  13832. onTouchContent: function () {
  13833. var toolbar = Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar')));
  13834. findFocusIn(toolbar).each(emitExecute);
  13835. realm.restoreToolbar();
  13836. hideDropup();
  13837. },
  13838. onTapContent: function (evt) {
  13839. var target = evt.target();
  13840. if (name(target) === 'img') {
  13841. editor.selection.select(target.dom());
  13842. evt.kill();
  13843. } else if (name(target) === 'a') {
  13844. var component = realm.system().getByDom(Element.fromDom(editor.editorContainer));
  13845. component.each(function (container) {
  13846. if (Swapping.isAlpha(container)) {
  13847. TinyCodeDupe.openLink(target.dom());
  13848. }
  13849. });
  13850. }
  13851. }
  13852. },
  13853. container: Element.fromDom(editor.editorContainer),
  13854. socket: Element.fromDom(editor.contentAreaContainer),
  13855. toolstrip: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolstrip'))),
  13856. toolbar: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar'))),
  13857. dropup: realm.dropup(),
  13858. alloy: realm.system(),
  13859. translate: noop,
  13860. setReadOnly: function (ro) {
  13861. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  13862. },
  13863. readOnlyOnInit: function () {
  13864. return readOnlyOnInit(editor);
  13865. }
  13866. });
  13867. var hideDropup = function () {
  13868. realm.dropup().disappear(function () {
  13869. realm.system().broadcastOn([TinyChannels.dropupDismissed()], {});
  13870. });
  13871. };
  13872. var backToMaskGroup = {
  13873. label: 'The first group',
  13874. scrollable: false,
  13875. items: [Buttons.forToolbar('back', function () {
  13876. editor.selection.collapse();
  13877. realm.exit();
  13878. }, {}, editor)]
  13879. };
  13880. var backToReadOnlyGroup = {
  13881. label: 'Back to read only',
  13882. scrollable: false,
  13883. items: [Buttons.forToolbar('readonly-back', function () {
  13884. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  13885. }, {}, editor)]
  13886. };
  13887. var readOnlyGroup = {
  13888. label: 'The read only mode group',
  13889. scrollable: true,
  13890. items: []
  13891. };
  13892. var features = Features.setup(realm, editor);
  13893. var items = Features.detect(editor.settings, features);
  13894. var actionGroup = {
  13895. label: 'the action group',
  13896. scrollable: true,
  13897. items: items
  13898. };
  13899. var extraGroup = {
  13900. label: 'The extra group',
  13901. scrollable: false,
  13902. items: []
  13903. };
  13904. var mainGroups = Cell([
  13905. actionGroup,
  13906. extraGroup
  13907. ]);
  13908. var readOnlyGroups = Cell([
  13909. readOnlyGroup,
  13910. extraGroup
  13911. ]);
  13912. var dynamicGroup = Cell({
  13913. backToMask: [backToMaskGroup],
  13914. backToReadOnly: [backToReadOnlyGroup]
  13915. });
  13916. FormatChangers.init(realm, editor);
  13917. });
  13918. editor.on('remove', function () {
  13919. realm.exit();
  13920. });
  13921. editor.on('detach', function () {
  13922. detachSystem(realm.system());
  13923. realm.system().destroy();
  13924. });
  13925. return {
  13926. iframeContainer: realm.socket().element().dom(),
  13927. editorContainer: realm.element().dom()
  13928. };
  13929. };
  13930. return {
  13931. getNotificationManagerImpl: function () {
  13932. return {
  13933. open: constant({
  13934. progressBar: { value: noop },
  13935. close: noop,
  13936. text: noop
  13937. }),
  13938. close: noop,
  13939. reposition: noop,
  13940. getArgs: constant({})
  13941. };
  13942. },
  13943. renderUI: renderUI
  13944. };
  13945. };
  13946. global$1.add('mobile', renderMobileTheme);
  13947. function Theme () {
  13948. }
  13949. return Theme;
  13950. }(window));
  13951. })();