theme.js 461 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002
  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.1.0 (2019-10-17)
  8. */
  9. (function (domGlobals) {
  10. 'use strict';
  11. var __assign = function () {
  12. __assign = Object.assign || function __assign(t) {
  13. for (var s, i = 1, n = arguments.length; i < n; i++) {
  14. s = arguments[i];
  15. for (var p in s)
  16. if (Object.prototype.hasOwnProperty.call(s, p))
  17. t[p] = s[p];
  18. }
  19. return t;
  20. };
  21. return __assign.apply(this, arguments);
  22. };
  23. function __rest(s, e) {
  24. var t = {};
  25. for (var p in s)
  26. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  27. t[p] = s[p];
  28. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  29. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  30. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  31. t[p[i]] = s[p[i]];
  32. }
  33. return t;
  34. }
  35. var noop = function () {
  36. };
  37. var compose = function (fa, fb) {
  38. return function () {
  39. var args = [];
  40. for (var _i = 0; _i < arguments.length; _i++) {
  41. args[_i] = arguments[_i];
  42. }
  43. return fa(fb.apply(null, args));
  44. };
  45. };
  46. var constant = function (value) {
  47. return function () {
  48. return value;
  49. };
  50. };
  51. var identity = function (x) {
  52. return x;
  53. };
  54. function curry(fn) {
  55. var initialArgs = [];
  56. for (var _i = 1; _i < arguments.length; _i++) {
  57. initialArgs[_i - 1] = arguments[_i];
  58. }
  59. return function () {
  60. var restArgs = [];
  61. for (var _i = 0; _i < arguments.length; _i++) {
  62. restArgs[_i] = arguments[_i];
  63. }
  64. var all = initialArgs.concat(restArgs);
  65. return fn.apply(null, all);
  66. };
  67. }
  68. var not = function (f) {
  69. return function () {
  70. var args = [];
  71. for (var _i = 0; _i < arguments.length; _i++) {
  72. args[_i] = arguments[_i];
  73. }
  74. return !f.apply(null, args);
  75. };
  76. };
  77. var die = function (msg) {
  78. return function () {
  79. throw new Error(msg);
  80. };
  81. };
  82. var apply = function (f) {
  83. return f();
  84. };
  85. var never = constant(false);
  86. var always = constant(true);
  87. var none = function () {
  88. return NONE;
  89. };
  90. var NONE = function () {
  91. var eq = function (o) {
  92. return o.isNone();
  93. };
  94. var call = function (thunk) {
  95. return thunk();
  96. };
  97. var id = function (n) {
  98. return n;
  99. };
  100. var me = {
  101. fold: function (n, s) {
  102. return n();
  103. },
  104. is: never,
  105. isSome: never,
  106. isNone: always,
  107. getOr: id,
  108. getOrThunk: call,
  109. getOrDie: function (msg) {
  110. throw new Error(msg || 'error: getOrDie called on none.');
  111. },
  112. getOrNull: constant(null),
  113. getOrUndefined: constant(undefined),
  114. or: id,
  115. orThunk: call,
  116. map: none,
  117. each: noop,
  118. bind: none,
  119. exists: never,
  120. forall: always,
  121. filter: none,
  122. equals: eq,
  123. equals_: eq,
  124. toArray: function () {
  125. return [];
  126. },
  127. toString: constant('none()')
  128. };
  129. if (Object.freeze) {
  130. Object.freeze(me);
  131. }
  132. return me;
  133. }();
  134. var some = function (a) {
  135. var constant_a = constant(a);
  136. var self = function () {
  137. return me;
  138. };
  139. var bind = function (f) {
  140. return f(a);
  141. };
  142. var me = {
  143. fold: function (n, s) {
  144. return s(a);
  145. },
  146. is: function (v) {
  147. return a === v;
  148. },
  149. isSome: always,
  150. isNone: never,
  151. getOr: constant_a,
  152. getOrThunk: constant_a,
  153. getOrDie: constant_a,
  154. getOrNull: constant_a,
  155. getOrUndefined: constant_a,
  156. or: self,
  157. orThunk: self,
  158. map: function (f) {
  159. return some(f(a));
  160. },
  161. each: function (f) {
  162. f(a);
  163. },
  164. bind: bind,
  165. exists: bind,
  166. forall: bind,
  167. filter: function (f) {
  168. return f(a) ? me : NONE;
  169. },
  170. toArray: function () {
  171. return [a];
  172. },
  173. toString: function () {
  174. return 'some(' + a + ')';
  175. },
  176. equals: function (o) {
  177. return o.is(a);
  178. },
  179. equals_: function (o, elementEq) {
  180. return o.fold(never, function (b) {
  181. return elementEq(a, b);
  182. });
  183. }
  184. };
  185. return me;
  186. };
  187. var from = function (value) {
  188. return value === null || value === undefined ? NONE : some(value);
  189. };
  190. var Option = {
  191. some: some,
  192. none: none,
  193. from: from
  194. };
  195. var keys = Object.keys;
  196. var hasOwnProperty = Object.hasOwnProperty;
  197. var each = function (obj, f) {
  198. var props = keys(obj);
  199. for (var k = 0, len = props.length; k < len; k++) {
  200. var i = props[k];
  201. var x = obj[i];
  202. f(x, i);
  203. }
  204. };
  205. var map = function (obj, f) {
  206. return tupleMap(obj, function (x, i) {
  207. return {
  208. k: i,
  209. v: f(x, i)
  210. };
  211. });
  212. };
  213. var tupleMap = function (obj, f) {
  214. var r = {};
  215. each(obj, function (x, i) {
  216. var tuple = f(x, i);
  217. r[tuple.k] = tuple.v;
  218. });
  219. return r;
  220. };
  221. var mapToArray = function (obj, f) {
  222. var r = [];
  223. each(obj, function (value, name) {
  224. r.push(f(value, name));
  225. });
  226. return r;
  227. };
  228. var find = function (obj, pred) {
  229. var props = keys(obj);
  230. for (var k = 0, len = props.length; k < len; k++) {
  231. var i = props[k];
  232. var x = obj[i];
  233. if (pred(x, i, obj)) {
  234. return Option.some(x);
  235. }
  236. }
  237. return Option.none();
  238. };
  239. var values = function (obj) {
  240. return mapToArray(obj, function (v) {
  241. return v;
  242. });
  243. };
  244. var has = function (obj, key) {
  245. return hasOwnProperty.call(obj, key);
  246. };
  247. var touchstart = constant('touchstart');
  248. var touchmove = constant('touchmove');
  249. var touchend = constant('touchend');
  250. var mousedown = constant('mousedown');
  251. var mousemove = constant('mousemove');
  252. var mouseup = constant('mouseup');
  253. var mouseover = constant('mouseover');
  254. var keydown = constant('keydown');
  255. var keyup = constant('keyup');
  256. var input = constant('input');
  257. var change = constant('change');
  258. var click = constant('click');
  259. var transitionend = constant('transitionend');
  260. var selectstart = constant('selectstart');
  261. var Cell = function (initial) {
  262. var value = initial;
  263. var get = function () {
  264. return value;
  265. };
  266. var set = function (v) {
  267. value = v;
  268. };
  269. var clone = function () {
  270. return Cell(get());
  271. };
  272. return {
  273. get: get,
  274. set: set,
  275. clone: clone
  276. };
  277. };
  278. var firstMatch = function (regexes, s) {
  279. for (var i = 0; i < regexes.length; i++) {
  280. var x = regexes[i];
  281. if (x.test(s)) {
  282. return x;
  283. }
  284. }
  285. return undefined;
  286. };
  287. var find$1 = function (regexes, agent) {
  288. var r = firstMatch(regexes, agent);
  289. if (!r) {
  290. return {
  291. major: 0,
  292. minor: 0
  293. };
  294. }
  295. var group = function (i) {
  296. return Number(agent.replace(r, '$' + i));
  297. };
  298. return nu(group(1), group(2));
  299. };
  300. var detect = function (versionRegexes, agent) {
  301. var cleanedAgent = String(agent).toLowerCase();
  302. if (versionRegexes.length === 0) {
  303. return unknown();
  304. }
  305. return find$1(versionRegexes, cleanedAgent);
  306. };
  307. var unknown = function () {
  308. return nu(0, 0);
  309. };
  310. var nu = function (major, minor) {
  311. return {
  312. major: major,
  313. minor: minor
  314. };
  315. };
  316. var Version = {
  317. nu: nu,
  318. detect: detect,
  319. unknown: unknown
  320. };
  321. var edge = 'Edge';
  322. var chrome = 'Chrome';
  323. var ie = 'IE';
  324. var opera = 'Opera';
  325. var firefox = 'Firefox';
  326. var safari = 'Safari';
  327. var isBrowser = function (name, current) {
  328. return function () {
  329. return current === name;
  330. };
  331. };
  332. var unknown$1 = function () {
  333. return nu$1({
  334. current: undefined,
  335. version: Version.unknown()
  336. });
  337. };
  338. var nu$1 = function (info) {
  339. var current = info.current;
  340. var version = info.version;
  341. return {
  342. current: current,
  343. version: version,
  344. isEdge: isBrowser(edge, current),
  345. isChrome: isBrowser(chrome, current),
  346. isIE: isBrowser(ie, current),
  347. isOpera: isBrowser(opera, current),
  348. isFirefox: isBrowser(firefox, current),
  349. isSafari: isBrowser(safari, current)
  350. };
  351. };
  352. var Browser = {
  353. unknown: unknown$1,
  354. nu: nu$1,
  355. edge: constant(edge),
  356. chrome: constant(chrome),
  357. ie: constant(ie),
  358. opera: constant(opera),
  359. firefox: constant(firefox),
  360. safari: constant(safari)
  361. };
  362. var windows = 'Windows';
  363. var ios = 'iOS';
  364. var android = 'Android';
  365. var linux = 'Linux';
  366. var osx = 'OSX';
  367. var solaris = 'Solaris';
  368. var freebsd = 'FreeBSD';
  369. var isOS = function (name, current) {
  370. return function () {
  371. return current === name;
  372. };
  373. };
  374. var unknown$2 = function () {
  375. return nu$2({
  376. current: undefined,
  377. version: Version.unknown()
  378. });
  379. };
  380. var nu$2 = function (info) {
  381. var current = info.current;
  382. var version = info.version;
  383. return {
  384. current: current,
  385. version: version,
  386. isWindows: isOS(windows, current),
  387. isiOS: isOS(ios, current),
  388. isAndroid: isOS(android, current),
  389. isOSX: isOS(osx, current),
  390. isLinux: isOS(linux, current),
  391. isSolaris: isOS(solaris, current),
  392. isFreeBSD: isOS(freebsd, current)
  393. };
  394. };
  395. var OperatingSystem = {
  396. unknown: unknown$2,
  397. nu: nu$2,
  398. windows: constant(windows),
  399. ios: constant(ios),
  400. android: constant(android),
  401. linux: constant(linux),
  402. osx: constant(osx),
  403. solaris: constant(solaris),
  404. freebsd: constant(freebsd)
  405. };
  406. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  407. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  408. var isiPhone = os.isiOS() && !isiPad;
  409. var isMobile = os.isiOS() || os.isAndroid();
  410. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  411. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  412. var isPhone = isiPhone || isMobile && !isTablet;
  413. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  414. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  415. return {
  416. isiPad: constant(isiPad),
  417. isiPhone: constant(isiPhone),
  418. isTablet: constant(isTablet),
  419. isPhone: constant(isPhone),
  420. isTouch: constant(isTouch),
  421. isAndroid: os.isAndroid,
  422. isiOS: os.isiOS,
  423. isWebView: constant(iOSwebview),
  424. isDesktop: constant(isDesktop)
  425. };
  426. };
  427. var typeOf = function (x) {
  428. if (x === null) {
  429. return 'null';
  430. }
  431. var t = typeof x;
  432. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  433. return 'array';
  434. }
  435. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  436. return 'string';
  437. }
  438. return t;
  439. };
  440. var isType = function (type) {
  441. return function (value) {
  442. return typeOf(value) === type;
  443. };
  444. };
  445. var isString = isType('string');
  446. var isObject = isType('object');
  447. var isArray = isType('array');
  448. var isBoolean = isType('boolean');
  449. var isFunction = isType('function');
  450. var isNumber = isType('number');
  451. var nativeSlice = Array.prototype.slice;
  452. var nativeIndexOf = Array.prototype.indexOf;
  453. var nativePush = Array.prototype.push;
  454. var rawIndexOf = function (ts, t) {
  455. return nativeIndexOf.call(ts, t);
  456. };
  457. var contains = function (xs, x) {
  458. return rawIndexOf(xs, x) > -1;
  459. };
  460. var exists = function (xs, pred) {
  461. for (var i = 0, len = xs.length; i < len; i++) {
  462. var x = xs[i];
  463. if (pred(x, i)) {
  464. return true;
  465. }
  466. }
  467. return false;
  468. };
  469. var map$1 = function (xs, f) {
  470. var len = xs.length;
  471. var r = new Array(len);
  472. for (var i = 0; i < len; i++) {
  473. var x = xs[i];
  474. r[i] = f(x, i);
  475. }
  476. return r;
  477. };
  478. var each$1 = function (xs, f) {
  479. for (var i = 0, len = xs.length; i < len; i++) {
  480. var x = xs[i];
  481. f(x, i);
  482. }
  483. };
  484. var eachr = function (xs, f) {
  485. for (var i = xs.length - 1; i >= 0; i--) {
  486. var x = xs[i];
  487. f(x, i);
  488. }
  489. };
  490. var filter = function (xs, pred) {
  491. var r = [];
  492. for (var i = 0, len = xs.length; i < len; i++) {
  493. var x = xs[i];
  494. if (pred(x, i)) {
  495. r.push(x);
  496. }
  497. }
  498. return r;
  499. };
  500. var foldr = function (xs, f, acc) {
  501. eachr(xs, function (x) {
  502. acc = f(acc, x);
  503. });
  504. return acc;
  505. };
  506. var foldl = function (xs, f, acc) {
  507. each$1(xs, function (x) {
  508. acc = f(acc, x);
  509. });
  510. return acc;
  511. };
  512. var find$2 = function (xs, pred) {
  513. for (var i = 0, len = xs.length; i < len; i++) {
  514. var x = xs[i];
  515. if (pred(x, i)) {
  516. return Option.some(x);
  517. }
  518. }
  519. return Option.none();
  520. };
  521. var findIndex = function (xs, pred) {
  522. for (var i = 0, len = xs.length; i < len; i++) {
  523. var x = xs[i];
  524. if (pred(x, i)) {
  525. return Option.some(i);
  526. }
  527. }
  528. return Option.none();
  529. };
  530. var flatten = function (xs) {
  531. var r = [];
  532. for (var i = 0, len = xs.length; i < len; ++i) {
  533. if (!isArray(xs[i])) {
  534. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  535. }
  536. nativePush.apply(r, xs[i]);
  537. }
  538. return r;
  539. };
  540. var bind = function (xs, f) {
  541. var output = map$1(xs, f);
  542. return flatten(output);
  543. };
  544. var forall = function (xs, pred) {
  545. for (var i = 0, len = xs.length; i < len; ++i) {
  546. var x = xs[i];
  547. if (pred(x, i) !== true) {
  548. return false;
  549. }
  550. }
  551. return true;
  552. };
  553. var reverse = function (xs) {
  554. var r = nativeSlice.call(xs, 0);
  555. r.reverse();
  556. return r;
  557. };
  558. var difference = function (a1, a2) {
  559. return filter(a1, function (x) {
  560. return !contains(a2, x);
  561. });
  562. };
  563. var pure = function (x) {
  564. return [x];
  565. };
  566. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  567. return nativeSlice.call(x);
  568. };
  569. var detect$1 = function (candidates, userAgent) {
  570. var agent = String(userAgent).toLowerCase();
  571. return find$2(candidates, function (candidate) {
  572. return candidate.search(agent);
  573. });
  574. };
  575. var detectBrowser = function (browsers, userAgent) {
  576. return detect$1(browsers, userAgent).map(function (browser) {
  577. var version = Version.detect(browser.versionRegexes, userAgent);
  578. return {
  579. current: browser.name,
  580. version: version
  581. };
  582. });
  583. };
  584. var detectOs = function (oses, userAgent) {
  585. return detect$1(oses, userAgent).map(function (os) {
  586. var version = Version.detect(os.versionRegexes, userAgent);
  587. return {
  588. current: os.name,
  589. version: version
  590. };
  591. });
  592. };
  593. var UaString = {
  594. detectBrowser: detectBrowser,
  595. detectOs: detectOs
  596. };
  597. var checkRange = function (str, substr, start) {
  598. if (substr === '') {
  599. return true;
  600. }
  601. if (str.length < substr.length) {
  602. return false;
  603. }
  604. var x = str.substr(start, start + substr.length);
  605. return x === substr;
  606. };
  607. var supplant = function (str, obj) {
  608. var isStringOrNumber = function (a) {
  609. var t = typeof a;
  610. return t === 'string' || t === 'number';
  611. };
  612. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  613. var value = obj[key];
  614. return isStringOrNumber(value) ? value.toString() : fullMatch;
  615. });
  616. };
  617. var contains$1 = function (str, substr) {
  618. return str.indexOf(substr) !== -1;
  619. };
  620. var endsWith = function (str, suffix) {
  621. return checkRange(str, suffix, str.length - suffix.length);
  622. };
  623. var trim = function (str) {
  624. return str.replace(/^\s+|\s+$/g, '');
  625. };
  626. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  627. var checkContains = function (target) {
  628. return function (uastring) {
  629. return contains$1(uastring, target);
  630. };
  631. };
  632. var browsers = [
  633. {
  634. name: 'Edge',
  635. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  636. search: function (uastring) {
  637. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  638. }
  639. },
  640. {
  641. name: 'Chrome',
  642. versionRegexes: [
  643. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  644. normalVersionRegex
  645. ],
  646. search: function (uastring) {
  647. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  648. }
  649. },
  650. {
  651. name: 'IE',
  652. versionRegexes: [
  653. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  654. /.*?rv:([0-9]+)\.([0-9]+).*/
  655. ],
  656. search: function (uastring) {
  657. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  658. }
  659. },
  660. {
  661. name: 'Opera',
  662. versionRegexes: [
  663. normalVersionRegex,
  664. /.*?opera\/([0-9]+)\.([0-9]+).*/
  665. ],
  666. search: checkContains('opera')
  667. },
  668. {
  669. name: 'Firefox',
  670. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  671. search: checkContains('firefox')
  672. },
  673. {
  674. name: 'Safari',
  675. versionRegexes: [
  676. normalVersionRegex,
  677. /.*?cpu os ([0-9]+)_([0-9]+).*/
  678. ],
  679. search: function (uastring) {
  680. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  681. }
  682. }
  683. ];
  684. var oses = [
  685. {
  686. name: 'Windows',
  687. search: checkContains('win'),
  688. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  689. },
  690. {
  691. name: 'iOS',
  692. search: function (uastring) {
  693. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  694. },
  695. versionRegexes: [
  696. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  697. /.*cpu os ([0-9]+)_([0-9]+).*/,
  698. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  699. ]
  700. },
  701. {
  702. name: 'Android',
  703. search: checkContains('android'),
  704. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  705. },
  706. {
  707. name: 'OSX',
  708. search: checkContains('os x'),
  709. versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
  710. },
  711. {
  712. name: 'Linux',
  713. search: checkContains('linux'),
  714. versionRegexes: []
  715. },
  716. {
  717. name: 'Solaris',
  718. search: checkContains('sunos'),
  719. versionRegexes: []
  720. },
  721. {
  722. name: 'FreeBSD',
  723. search: checkContains('freebsd'),
  724. versionRegexes: []
  725. }
  726. ];
  727. var PlatformInfo = {
  728. browsers: constant(browsers),
  729. oses: constant(oses)
  730. };
  731. var detect$2 = function (userAgent, mediaMatch) {
  732. var browsers = PlatformInfo.browsers();
  733. var oses = PlatformInfo.oses();
  734. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  735. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  736. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  737. return {
  738. browser: browser,
  739. os: os,
  740. deviceType: deviceType
  741. };
  742. };
  743. var PlatformDetection = { detect: detect$2 };
  744. var mediaMatch = function (query) {
  745. return domGlobals.window.matchMedia(query).matches;
  746. };
  747. var platform = Cell(PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch));
  748. var detect$3 = function () {
  749. return platform.get();
  750. };
  751. var alloy = { tap: constant('alloy.tap') };
  752. var focus = constant('alloy.focus');
  753. var postBlur = constant('alloy.blur.post');
  754. var postPaste = constant('alloy.paste.post');
  755. var receive = constant('alloy.receive');
  756. var execute = constant('alloy.execute');
  757. var focusItem = constant('alloy.focus.item');
  758. var tap = alloy.tap;
  759. var tapOrClick = detect$3().deviceType.isTouch() ? alloy.tap : click;
  760. var longpress = constant('alloy.longpress');
  761. var systemInit = constant('alloy.system.init');
  762. var attachedToDom = constant('alloy.system.attached');
  763. var detachedFromDom = constant('alloy.system.detached');
  764. var focusShifted = constant('alloy.focusmanager.shifted');
  765. var highlight = constant('alloy.highlight');
  766. var dehighlight = constant('alloy.dehighlight');
  767. var emit = function (component, event) {
  768. dispatchWith(component, component.element(), event, {});
  769. };
  770. var emitWith = function (component, event, properties) {
  771. dispatchWith(component, component.element(), event, properties);
  772. };
  773. var emitExecute = function (component) {
  774. emit(component, execute());
  775. };
  776. var dispatch = function (component, target, event) {
  777. dispatchWith(component, target, event, {});
  778. };
  779. var dispatchWith = function (component, target, event, properties) {
  780. var data = __assign({ target: target }, properties);
  781. component.getSystem().triggerEvent(event, target, map(data, constant));
  782. };
  783. var dispatchEvent = function (component, target, event, simulatedEvent) {
  784. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  785. };
  786. var dispatchFocus = function (component, target) {
  787. component.getSystem().triggerFocus(target, component.element());
  788. };
  789. var cached = function (f) {
  790. var called = false;
  791. var r;
  792. return function () {
  793. var args = [];
  794. for (var _i = 0; _i < arguments.length; _i++) {
  795. args[_i] = arguments[_i];
  796. }
  797. if (!called) {
  798. called = true;
  799. r = f.apply(null, args);
  800. }
  801. return r;
  802. };
  803. };
  804. var fromHtml = function (html, scope) {
  805. var doc = scope || domGlobals.document;
  806. var div = doc.createElement('div');
  807. div.innerHTML = html;
  808. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  809. domGlobals.console.error('HTML does not have a single root node', html);
  810. throw new Error('HTML must have a single root node');
  811. }
  812. return fromDom(div.childNodes[0]);
  813. };
  814. var fromTag = function (tag, scope) {
  815. var doc = scope || domGlobals.document;
  816. var node = doc.createElement(tag);
  817. return fromDom(node);
  818. };
  819. var fromText = function (text, scope) {
  820. var doc = scope || domGlobals.document;
  821. var node = doc.createTextNode(text);
  822. return fromDom(node);
  823. };
  824. var fromDom = function (node) {
  825. if (node === null || node === undefined) {
  826. throw new Error('Node cannot be null or undefined');
  827. }
  828. return { dom: constant(node) };
  829. };
  830. var fromPoint = function (docElm, x, y) {
  831. var doc = docElm.dom();
  832. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  833. };
  834. var Element = {
  835. fromHtml: fromHtml,
  836. fromTag: fromTag,
  837. fromText: fromText,
  838. fromDom: fromDom,
  839. fromPoint: fromPoint
  840. };
  841. var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE;
  842. var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE;
  843. var COMMENT = domGlobals.Node.COMMENT_NODE;
  844. var DOCUMENT = domGlobals.Node.DOCUMENT_NODE;
  845. var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE;
  846. var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE;
  847. var ELEMENT = domGlobals.Node.ELEMENT_NODE;
  848. var TEXT = domGlobals.Node.TEXT_NODE;
  849. var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE;
  850. var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE;
  851. var ENTITY = domGlobals.Node.ENTITY_NODE;
  852. var NOTATION = domGlobals.Node.NOTATION_NODE;
  853. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  854. var name = function (element) {
  855. var r = element.dom().nodeName;
  856. return r.toLowerCase();
  857. };
  858. var type = function (element) {
  859. return element.dom().nodeType;
  860. };
  861. var isType$1 = function (t) {
  862. return function (element) {
  863. return type(element) === t;
  864. };
  865. };
  866. var isElement = isType$1(ELEMENT);
  867. var isText = isType$1(TEXT);
  868. var inBody = function (element) {
  869. var dom = isText(element) ? element.dom().parentNode : element.dom();
  870. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  871. };
  872. var body = cached(function () {
  873. return getBody(Element.fromDom(domGlobals.document));
  874. });
  875. var getBody = function (doc) {
  876. var b = doc.dom().body;
  877. if (b === null || b === undefined) {
  878. throw new Error('Body is not available yet');
  879. }
  880. return Element.fromDom(b);
  881. };
  882. var Immutable = function () {
  883. var fields = [];
  884. for (var _i = 0; _i < arguments.length; _i++) {
  885. fields[_i] = arguments[_i];
  886. }
  887. return function () {
  888. var values = [];
  889. for (var _i = 0; _i < arguments.length; _i++) {
  890. values[_i] = arguments[_i];
  891. }
  892. if (fields.length !== values.length) {
  893. throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
  894. }
  895. var struct = {};
  896. each$1(fields, function (name, i) {
  897. struct[name] = constant(values[i]);
  898. });
  899. return struct;
  900. };
  901. };
  902. var sort = function (arr) {
  903. return arr.slice(0).sort();
  904. };
  905. var reqMessage = function (required, keys) {
  906. throw new Error('All required keys (' + sort(required).join(', ') + ') were not specified. Specified keys were: ' + sort(keys).join(', ') + '.');
  907. };
  908. var unsuppMessage = function (unsupported) {
  909. throw new Error('Unsupported keys for object: ' + sort(unsupported).join(', '));
  910. };
  911. var validateStrArr = function (label, array) {
  912. if (!isArray(array)) {
  913. throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
  914. }
  915. each$1(array, function (a) {
  916. if (!isString(a)) {
  917. throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
  918. }
  919. });
  920. };
  921. var checkDupes = function (everything) {
  922. var sorted = sort(everything);
  923. var dupe = find$2(sorted, function (s, i) {
  924. return i < sorted.length - 1 && s === sorted[i + 1];
  925. });
  926. dupe.each(function (d) {
  927. throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
  928. });
  929. };
  930. var MixedBag = function (required, optional) {
  931. var everything = required.concat(optional);
  932. if (everything.length === 0) {
  933. throw new Error('You must specify at least one required or optional field.');
  934. }
  935. validateStrArr('required', required);
  936. validateStrArr('optional', optional);
  937. checkDupes(everything);
  938. return function (obj) {
  939. var keys$1 = keys(obj);
  940. var allReqd = forall(required, function (req) {
  941. return contains(keys$1, req);
  942. });
  943. if (!allReqd) {
  944. reqMessage(required, keys$1);
  945. }
  946. var unsupported = filter(keys$1, function (key) {
  947. return !contains(everything, key);
  948. });
  949. if (unsupported.length > 0) {
  950. unsuppMessage(unsupported);
  951. }
  952. var r = {};
  953. each$1(required, function (req) {
  954. r[req] = constant(obj[req]);
  955. });
  956. each$1(optional, function (opt) {
  957. r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
  958. });
  959. return r;
  960. };
  961. };
  962. var compareDocumentPosition = function (a, b, match) {
  963. return (a.compareDocumentPosition(b) & match) !== 0;
  964. };
  965. var documentPositionPreceding = function (a, b) {
  966. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_PRECEDING);
  967. };
  968. var documentPositionContainedBy = function (a, b) {
  969. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY);
  970. };
  971. var Node = {
  972. documentPositionPreceding: documentPositionPreceding,
  973. documentPositionContainedBy: documentPositionContainedBy
  974. };
  975. var ELEMENT$1 = ELEMENT;
  976. var DOCUMENT$1 = DOCUMENT;
  977. var is = function (element, selector) {
  978. var dom = element.dom();
  979. if (dom.nodeType !== ELEMENT$1) {
  980. return false;
  981. } else {
  982. var elem = dom;
  983. if (elem.matches !== undefined) {
  984. return elem.matches(selector);
  985. } else if (elem.msMatchesSelector !== undefined) {
  986. return elem.msMatchesSelector(selector);
  987. } else if (elem.webkitMatchesSelector !== undefined) {
  988. return elem.webkitMatchesSelector(selector);
  989. } else if (elem.mozMatchesSelector !== undefined) {
  990. return elem.mozMatchesSelector(selector);
  991. } else {
  992. throw new Error('Browser lacks native selectors');
  993. }
  994. }
  995. };
  996. var bypassSelector = function (dom) {
  997. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  998. };
  999. var all = function (selector, scope) {
  1000. var base = scope === undefined ? domGlobals.document : scope.dom();
  1001. return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), Element.fromDom);
  1002. };
  1003. var one = function (selector, scope) {
  1004. var base = scope === undefined ? domGlobals.document : scope.dom();
  1005. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1006. };
  1007. var eq = function (e1, e2) {
  1008. return e1.dom() === e2.dom();
  1009. };
  1010. var regularContains = function (e1, e2) {
  1011. var d1 = e1.dom();
  1012. var d2 = e2.dom();
  1013. return d1 === d2 ? false : d1.contains(d2);
  1014. };
  1015. var ieContains = function (e1, e2) {
  1016. return Node.documentPositionContainedBy(e1.dom(), e2.dom());
  1017. };
  1018. var browser = detect$3().browser;
  1019. var contains$2 = browser.isIE() ? ieContains : regularContains;
  1020. var owner = function (element) {
  1021. return Element.fromDom(element.dom().ownerDocument);
  1022. };
  1023. var defaultView = function (element) {
  1024. return Element.fromDom(element.dom().ownerDocument.defaultView);
  1025. };
  1026. var parent = function (element) {
  1027. return Option.from(element.dom().parentNode).map(Element.fromDom);
  1028. };
  1029. var parents = function (element, isRoot) {
  1030. var stop = isFunction(isRoot) ? isRoot : never;
  1031. var dom = element.dom();
  1032. var ret = [];
  1033. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1034. var rawParent = dom.parentNode;
  1035. var p = Element.fromDom(rawParent);
  1036. ret.push(p);
  1037. if (stop(p) === true) {
  1038. break;
  1039. } else {
  1040. dom = rawParent;
  1041. }
  1042. }
  1043. return ret;
  1044. };
  1045. var siblings = function (element) {
  1046. var filterSelf = function (elements) {
  1047. return filter(elements, function (x) {
  1048. return !eq(element, x);
  1049. });
  1050. };
  1051. return parent(element).map(children).map(filterSelf).getOr([]);
  1052. };
  1053. var nextSibling = function (element) {
  1054. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  1055. };
  1056. var children = function (element) {
  1057. return map$1(element.dom().childNodes, Element.fromDom);
  1058. };
  1059. var child = function (element, index) {
  1060. var cs = element.dom().childNodes;
  1061. return Option.from(cs[index]).map(Element.fromDom);
  1062. };
  1063. var firstChild = function (element) {
  1064. return child(element, 0);
  1065. };
  1066. var spot = Immutable('element', 'offset');
  1067. var before = function (marker, element) {
  1068. var parent$1 = parent(marker);
  1069. parent$1.each(function (v) {
  1070. v.dom().insertBefore(element.dom(), marker.dom());
  1071. });
  1072. };
  1073. var after = function (marker, element) {
  1074. var sibling = nextSibling(marker);
  1075. sibling.fold(function () {
  1076. var parent$1 = parent(marker);
  1077. parent$1.each(function (v) {
  1078. append(v, element);
  1079. });
  1080. }, function (v) {
  1081. before(v, element);
  1082. });
  1083. };
  1084. var prepend = function (parent, element) {
  1085. var firstChild$1 = firstChild(parent);
  1086. firstChild$1.fold(function () {
  1087. append(parent, element);
  1088. }, function (v) {
  1089. parent.dom().insertBefore(element.dom(), v.dom());
  1090. });
  1091. };
  1092. var append = function (parent, element) {
  1093. parent.dom().appendChild(element.dom());
  1094. };
  1095. var appendAt = function (parent, element, index) {
  1096. child(parent, index).fold(function () {
  1097. append(parent, element);
  1098. }, function (v) {
  1099. before(v, element);
  1100. });
  1101. };
  1102. var append$1 = function (parent, elements) {
  1103. each$1(elements, function (x) {
  1104. append(parent, x);
  1105. });
  1106. };
  1107. var empty = function (element) {
  1108. element.dom().textContent = '';
  1109. each$1(children(element), function (rogue) {
  1110. remove(rogue);
  1111. });
  1112. };
  1113. var remove = function (element) {
  1114. var dom = element.dom();
  1115. if (dom.parentNode !== null) {
  1116. dom.parentNode.removeChild(dom);
  1117. }
  1118. };
  1119. var fireDetaching = function (component) {
  1120. emit(component, detachedFromDom());
  1121. var children = component.components();
  1122. each$1(children, fireDetaching);
  1123. };
  1124. var fireAttaching = function (component) {
  1125. var children = component.components();
  1126. each$1(children, fireAttaching);
  1127. emit(component, attachedToDom());
  1128. };
  1129. var attach = function (parent, child) {
  1130. append(parent.element(), child.element());
  1131. };
  1132. var detachChildren = function (component) {
  1133. each$1(component.components(), function (childComp) {
  1134. return remove(childComp.element());
  1135. });
  1136. empty(component.element());
  1137. component.syncComponents();
  1138. };
  1139. var replaceChildren = function (component, newChildren) {
  1140. var subs = component.components();
  1141. detachChildren(component);
  1142. var deleted = difference(subs, newChildren);
  1143. each$1(deleted, function (comp) {
  1144. fireDetaching(comp);
  1145. component.getSystem().removeFromWorld(comp);
  1146. });
  1147. each$1(newChildren, function (childComp) {
  1148. if (!childComp.getSystem().isConnected()) {
  1149. component.getSystem().addToWorld(childComp);
  1150. attach(component, childComp);
  1151. if (inBody(component.element())) {
  1152. fireAttaching(childComp);
  1153. }
  1154. } else {
  1155. attach(component, childComp);
  1156. }
  1157. component.syncComponents();
  1158. });
  1159. };
  1160. var attach$1 = function (parent, child) {
  1161. attachWith(parent, child, append);
  1162. };
  1163. var attachWith = function (parent, child, insertion) {
  1164. parent.getSystem().addToWorld(child);
  1165. insertion(parent.element(), child.element());
  1166. if (inBody(parent.element())) {
  1167. fireAttaching(child);
  1168. }
  1169. parent.syncComponents();
  1170. };
  1171. var doDetach = function (component) {
  1172. fireDetaching(component);
  1173. remove(component.element());
  1174. component.getSystem().removeFromWorld(component);
  1175. };
  1176. var detach = function (component) {
  1177. var parent$1 = parent(component.element()).bind(function (p) {
  1178. return component.getSystem().getByDom(p).toOption();
  1179. });
  1180. doDetach(component);
  1181. parent$1.each(function (p) {
  1182. p.syncComponents();
  1183. });
  1184. };
  1185. var attachSystemAfter = function (element, guiSystem) {
  1186. attachSystemWith(element, guiSystem, after);
  1187. };
  1188. var attachSystemWith = function (element, guiSystem, inserter) {
  1189. inserter(element, guiSystem.element());
  1190. var children$1 = children(guiSystem.element());
  1191. each$1(children$1, function (child) {
  1192. guiSystem.getByDom(child).each(fireAttaching);
  1193. });
  1194. };
  1195. var detachSystem = function (guiSystem) {
  1196. var children$1 = children(guiSystem.element());
  1197. each$1(children$1, function (child) {
  1198. guiSystem.getByDom(child).each(fireDetaching);
  1199. });
  1200. remove(guiSystem.element());
  1201. };
  1202. var value = function (o) {
  1203. var is = function (v) {
  1204. return o === v;
  1205. };
  1206. var or = function (opt) {
  1207. return value(o);
  1208. };
  1209. var orThunk = function (f) {
  1210. return value(o);
  1211. };
  1212. var map = function (f) {
  1213. return value(f(o));
  1214. };
  1215. var mapError = function (f) {
  1216. return value(o);
  1217. };
  1218. var each = function (f) {
  1219. f(o);
  1220. };
  1221. var bind = function (f) {
  1222. return f(o);
  1223. };
  1224. var fold = function (_, onValue) {
  1225. return onValue(o);
  1226. };
  1227. var exists = function (f) {
  1228. return f(o);
  1229. };
  1230. var forall = function (f) {
  1231. return f(o);
  1232. };
  1233. var toOption = function () {
  1234. return Option.some(o);
  1235. };
  1236. return {
  1237. is: is,
  1238. isValue: always,
  1239. isError: never,
  1240. getOr: constant(o),
  1241. getOrThunk: constant(o),
  1242. getOrDie: constant(o),
  1243. or: or,
  1244. orThunk: orThunk,
  1245. fold: fold,
  1246. map: map,
  1247. mapError: mapError,
  1248. each: each,
  1249. bind: bind,
  1250. exists: exists,
  1251. forall: forall,
  1252. toOption: toOption
  1253. };
  1254. };
  1255. var error = function (message) {
  1256. var getOrThunk = function (f) {
  1257. return f();
  1258. };
  1259. var getOrDie = function () {
  1260. return die(String(message))();
  1261. };
  1262. var or = function (opt) {
  1263. return opt;
  1264. };
  1265. var orThunk = function (f) {
  1266. return f();
  1267. };
  1268. var map = function (f) {
  1269. return error(message);
  1270. };
  1271. var mapError = function (f) {
  1272. return error(f(message));
  1273. };
  1274. var bind = function (f) {
  1275. return error(message);
  1276. };
  1277. var fold = function (onError, _) {
  1278. return onError(message);
  1279. };
  1280. return {
  1281. is: never,
  1282. isValue: never,
  1283. isError: always,
  1284. getOr: identity,
  1285. getOrThunk: getOrThunk,
  1286. getOrDie: getOrDie,
  1287. or: or,
  1288. orThunk: orThunk,
  1289. fold: fold,
  1290. map: map,
  1291. mapError: mapError,
  1292. each: noop,
  1293. bind: bind,
  1294. exists: never,
  1295. forall: always,
  1296. toOption: Option.none
  1297. };
  1298. };
  1299. var fromOption = function (opt, err) {
  1300. return opt.fold(function () {
  1301. return error(err);
  1302. }, value);
  1303. };
  1304. var Result = {
  1305. value: value,
  1306. error: error,
  1307. fromOption: fromOption
  1308. };
  1309. var generate = function (cases) {
  1310. if (!isArray(cases)) {
  1311. throw new Error('cases must be an array');
  1312. }
  1313. if (cases.length === 0) {
  1314. throw new Error('there must be at least one case');
  1315. }
  1316. var constructors = [];
  1317. var adt = {};
  1318. each$1(cases, function (acase, count) {
  1319. var keys$1 = keys(acase);
  1320. if (keys$1.length !== 1) {
  1321. throw new Error('one and only one name per case');
  1322. }
  1323. var key = keys$1[0];
  1324. var value = acase[key];
  1325. if (adt[key] !== undefined) {
  1326. throw new Error('duplicate key detected:' + key);
  1327. } else if (key === 'cata') {
  1328. throw new Error('cannot have a case named cata (sorry)');
  1329. } else if (!isArray(value)) {
  1330. throw new Error('case arguments must be an array');
  1331. }
  1332. constructors.push(key);
  1333. adt[key] = function () {
  1334. var argLength = arguments.length;
  1335. if (argLength !== value.length) {
  1336. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1337. }
  1338. var args = new Array(argLength);
  1339. for (var i = 0; i < args.length; i++) {
  1340. args[i] = arguments[i];
  1341. }
  1342. var match = function (branches) {
  1343. var branchKeys = keys(branches);
  1344. if (constructors.length !== branchKeys.length) {
  1345. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1346. }
  1347. var allReqd = forall(constructors, function (reqKey) {
  1348. return contains(branchKeys, reqKey);
  1349. });
  1350. if (!allReqd) {
  1351. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1352. }
  1353. return branches[key].apply(null, args);
  1354. };
  1355. return {
  1356. fold: function () {
  1357. if (arguments.length !== cases.length) {
  1358. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  1359. }
  1360. var target = arguments[count];
  1361. return target.apply(null, args);
  1362. },
  1363. match: match,
  1364. log: function (label) {
  1365. domGlobals.console.log(label, {
  1366. constructors: constructors,
  1367. constructor: key,
  1368. params: args
  1369. });
  1370. }
  1371. };
  1372. };
  1373. });
  1374. return adt;
  1375. };
  1376. var Adt = { generate: generate };
  1377. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  1378. var shallow = function (old, nu) {
  1379. return nu;
  1380. };
  1381. var deep = function (old, nu) {
  1382. var bothObjects = isObject(old) && isObject(nu);
  1383. return bothObjects ? deepMerge(old, nu) : nu;
  1384. };
  1385. var baseMerge = function (merger) {
  1386. return function () {
  1387. var objects = new Array(arguments.length);
  1388. for (var i = 0; i < objects.length; i++) {
  1389. objects[i] = arguments[i];
  1390. }
  1391. if (objects.length === 0) {
  1392. throw new Error('Can\'t merge zero objects');
  1393. }
  1394. var ret = {};
  1395. for (var j = 0; j < objects.length; j++) {
  1396. var curObject = objects[j];
  1397. for (var key in curObject) {
  1398. if (hasOwnProperty$1.call(curObject, key)) {
  1399. ret[key] = merger(ret[key], curObject[key]);
  1400. }
  1401. }
  1402. }
  1403. return ret;
  1404. };
  1405. };
  1406. var deepMerge = baseMerge(deep);
  1407. var merge = baseMerge(shallow);
  1408. var adt = Adt.generate([
  1409. { strict: [] },
  1410. { defaultedThunk: ['fallbackThunk'] },
  1411. { asOption: [] },
  1412. { asDefaultedOptionThunk: ['fallbackThunk'] },
  1413. { mergeWithThunk: ['baseThunk'] }
  1414. ]);
  1415. var defaulted = function (fallback) {
  1416. return adt.defaultedThunk(constant(fallback));
  1417. };
  1418. var mergeWith = function (base) {
  1419. return adt.mergeWithThunk(constant(base));
  1420. };
  1421. var strict = adt.strict;
  1422. var asOption = adt.asOption;
  1423. var defaultedThunk = adt.defaultedThunk;
  1424. var mergeWithThunk = adt.mergeWithThunk;
  1425. var exclude = function (obj, fields) {
  1426. var r = {};
  1427. each(obj, function (v, k) {
  1428. if (!contains(fields, k)) {
  1429. r[k] = v;
  1430. }
  1431. });
  1432. return r;
  1433. };
  1434. var readOpt = function (key) {
  1435. return function (obj) {
  1436. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  1437. };
  1438. };
  1439. var readOr = function (key, fallback) {
  1440. return function (obj) {
  1441. return has(obj, key) ? obj[key] : fallback;
  1442. };
  1443. };
  1444. var readOptFrom = function (obj, key) {
  1445. return readOpt(key)(obj);
  1446. };
  1447. var hasKey = function (obj, key) {
  1448. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  1449. };
  1450. var wrap = function (key, value) {
  1451. var r = {};
  1452. r[key] = value;
  1453. return r;
  1454. };
  1455. var wrapAll = function (keyvalues) {
  1456. var r = {};
  1457. each$1(keyvalues, function (kv) {
  1458. r[kv.key] = kv.value;
  1459. });
  1460. return r;
  1461. };
  1462. var comparison = Adt.generate([
  1463. {
  1464. bothErrors: [
  1465. 'error1',
  1466. 'error2'
  1467. ]
  1468. },
  1469. {
  1470. firstError: [
  1471. 'error1',
  1472. 'value2'
  1473. ]
  1474. },
  1475. {
  1476. secondError: [
  1477. 'value1',
  1478. 'error2'
  1479. ]
  1480. },
  1481. {
  1482. bothValues: [
  1483. 'value1',
  1484. 'value2'
  1485. ]
  1486. }
  1487. ]);
  1488. var partition = function (results) {
  1489. var errors = [];
  1490. var values = [];
  1491. each$1(results, function (result) {
  1492. result.fold(function (err) {
  1493. errors.push(err);
  1494. }, function (value) {
  1495. values.push(value);
  1496. });
  1497. });
  1498. return {
  1499. errors: errors,
  1500. values: values
  1501. };
  1502. };
  1503. var exclude$1 = function (obj, fields) {
  1504. return exclude(obj, fields);
  1505. };
  1506. var readOpt$1 = function (key) {
  1507. return readOpt(key);
  1508. };
  1509. var readOr$1 = function (key, fallback) {
  1510. return readOr(key, fallback);
  1511. };
  1512. var readOptFrom$1 = function (obj, key) {
  1513. return readOptFrom(obj, key);
  1514. };
  1515. var wrap$1 = function (key, value) {
  1516. return wrap(key, value);
  1517. };
  1518. var wrapAll$1 = function (keyvalues) {
  1519. return wrapAll(keyvalues);
  1520. };
  1521. var mergeValues = function (values, base) {
  1522. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  1523. };
  1524. var mergeErrors = function (errors) {
  1525. return Result.error(flatten(errors));
  1526. };
  1527. var consolidate = function (objs, base) {
  1528. var partitions = partition(objs);
  1529. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  1530. };
  1531. var hasKey$1 = function (obj, key) {
  1532. return hasKey(obj, key);
  1533. };
  1534. var SimpleResultType;
  1535. (function (SimpleResultType) {
  1536. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1537. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1538. }(SimpleResultType || (SimpleResultType = {})));
  1539. var fold = function (res, onError, onValue) {
  1540. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1541. };
  1542. var partition$1 = function (results) {
  1543. var values = [];
  1544. var errors = [];
  1545. each$1(results, function (obj) {
  1546. fold(obj, function (err) {
  1547. return errors.push(err);
  1548. }, function (val) {
  1549. return values.push(val);
  1550. });
  1551. });
  1552. return {
  1553. values: values,
  1554. errors: errors
  1555. };
  1556. };
  1557. var mapError = function (res, f) {
  1558. if (res.stype === SimpleResultType.Error) {
  1559. return {
  1560. stype: SimpleResultType.Error,
  1561. serror: f(res.serror)
  1562. };
  1563. } else {
  1564. return res;
  1565. }
  1566. };
  1567. var map$2 = function (res, f) {
  1568. if (res.stype === SimpleResultType.Value) {
  1569. return {
  1570. stype: SimpleResultType.Value,
  1571. svalue: f(res.svalue)
  1572. };
  1573. } else {
  1574. return res;
  1575. }
  1576. };
  1577. var bind$1 = function (res, f) {
  1578. if (res.stype === SimpleResultType.Value) {
  1579. return f(res.svalue);
  1580. } else {
  1581. return res;
  1582. }
  1583. };
  1584. var bindError = function (res, f) {
  1585. if (res.stype === SimpleResultType.Error) {
  1586. return f(res.serror);
  1587. } else {
  1588. return res;
  1589. }
  1590. };
  1591. var svalue = function (v) {
  1592. return {
  1593. stype: SimpleResultType.Value,
  1594. svalue: v
  1595. };
  1596. };
  1597. var serror = function (e) {
  1598. return {
  1599. stype: SimpleResultType.Error,
  1600. serror: e
  1601. };
  1602. };
  1603. var toResult = function (res) {
  1604. return fold(res, Result.error, Result.value);
  1605. };
  1606. var fromResult = function (res) {
  1607. return res.fold(serror, svalue);
  1608. };
  1609. var SimpleResult = {
  1610. fromResult: fromResult,
  1611. toResult: toResult,
  1612. svalue: svalue,
  1613. partition: partition$1,
  1614. serror: serror,
  1615. bind: bind$1,
  1616. bindError: bindError,
  1617. map: map$2,
  1618. mapError: mapError,
  1619. fold: fold
  1620. };
  1621. var mergeValues$1 = function (values, base) {
  1622. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  1623. };
  1624. var mergeErrors$1 = function (errors) {
  1625. return compose(SimpleResult.serror, flatten)(errors);
  1626. };
  1627. var consolidateObj = function (objects, base) {
  1628. var partition = SimpleResult.partition(objects);
  1629. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1630. };
  1631. var consolidateArr = function (objects) {
  1632. var partitions = SimpleResult.partition(objects);
  1633. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1634. };
  1635. var ResultCombine = {
  1636. consolidateObj: consolidateObj,
  1637. consolidateArr: consolidateArr
  1638. };
  1639. var typeAdt = Adt.generate([
  1640. {
  1641. setOf: [
  1642. 'validator',
  1643. 'valueType'
  1644. ]
  1645. },
  1646. { arrOf: ['valueType'] },
  1647. { objOf: ['fields'] },
  1648. { itemOf: ['validator'] },
  1649. {
  1650. choiceOf: [
  1651. 'key',
  1652. 'branches'
  1653. ]
  1654. },
  1655. { thunk: ['description'] },
  1656. {
  1657. func: [
  1658. 'args',
  1659. 'outputSchema'
  1660. ]
  1661. }
  1662. ]);
  1663. var fieldAdt = Adt.generate([
  1664. {
  1665. field: [
  1666. 'name',
  1667. 'presence',
  1668. 'type'
  1669. ]
  1670. },
  1671. { state: ['name'] }
  1672. ]);
  1673. var formatObj = function (input) {
  1674. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1675. };
  1676. var formatErrors = function (errors) {
  1677. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1678. path: [],
  1679. getErrorInfo: function () {
  1680. return '... (only showing first ten failures)';
  1681. }
  1682. }]) : errors;
  1683. return map$1(es, function (e) {
  1684. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1685. });
  1686. };
  1687. var nu$3 = function (path, getErrorInfo) {
  1688. return SimpleResult.serror([{
  1689. path: path,
  1690. getErrorInfo: getErrorInfo
  1691. }]);
  1692. };
  1693. var missingStrict = function (path, key, obj) {
  1694. return nu$3(path, function () {
  1695. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  1696. });
  1697. };
  1698. var missingKey = function (path, key) {
  1699. return nu$3(path, function () {
  1700. return 'Choice schema did not contain choice key: "' + key + '"';
  1701. });
  1702. };
  1703. var missingBranch = function (path, branches, branch) {
  1704. return nu$3(path, function () {
  1705. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1706. });
  1707. };
  1708. var unsupportedFields = function (path, unsupported) {
  1709. return nu$3(path, function () {
  1710. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1711. });
  1712. };
  1713. var custom = function (path, err) {
  1714. return nu$3(path, function () {
  1715. return err;
  1716. });
  1717. };
  1718. var adt$1 = Adt.generate([
  1719. {
  1720. field: [
  1721. 'key',
  1722. 'okey',
  1723. 'presence',
  1724. 'prop'
  1725. ]
  1726. },
  1727. {
  1728. state: [
  1729. 'okey',
  1730. 'instantiator'
  1731. ]
  1732. }
  1733. ]);
  1734. var strictAccess = function (path, obj, key) {
  1735. return readOptFrom(obj, key).fold(function () {
  1736. return missingStrict(path, key, obj);
  1737. }, SimpleResult.svalue);
  1738. };
  1739. var fallbackAccess = function (obj, key, fallbackThunk) {
  1740. var v = readOptFrom(obj, key).fold(function () {
  1741. return fallbackThunk(obj);
  1742. }, identity);
  1743. return SimpleResult.svalue(v);
  1744. };
  1745. var optionAccess = function (obj, key) {
  1746. return SimpleResult.svalue(readOptFrom(obj, key));
  1747. };
  1748. var optionDefaultedAccess = function (obj, key, fallback) {
  1749. var opt = readOptFrom(obj, key).map(function (val) {
  1750. return val === true ? fallback(obj) : val;
  1751. });
  1752. return SimpleResult.svalue(opt);
  1753. };
  1754. var cExtractOne = function (path, obj, field, strength) {
  1755. return field.fold(function (key, okey, presence, prop) {
  1756. var bundle = function (av) {
  1757. var result = prop.extract(path.concat([key]), strength, av);
  1758. return SimpleResult.map(result, function (res) {
  1759. return wrap(okey, strength(res));
  1760. });
  1761. };
  1762. var bundleAsOption = function (optValue) {
  1763. return optValue.fold(function () {
  1764. var outcome = wrap(okey, strength(Option.none()));
  1765. return SimpleResult.svalue(outcome);
  1766. }, function (ov) {
  1767. var result = prop.extract(path.concat([key]), strength, ov);
  1768. return SimpleResult.map(result, function (res) {
  1769. return wrap(okey, strength(Option.some(res)));
  1770. });
  1771. });
  1772. };
  1773. return function () {
  1774. return presence.fold(function () {
  1775. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1776. }, function (fallbackThunk) {
  1777. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1778. }, function () {
  1779. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1780. }, function (fallbackThunk) {
  1781. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1782. }, function (baseThunk) {
  1783. var base = baseThunk(obj);
  1784. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1785. return deepMerge(base, v);
  1786. });
  1787. return SimpleResult.bind(result, bundle);
  1788. });
  1789. }();
  1790. }, function (okey, instantiator) {
  1791. var state = instantiator(obj);
  1792. return SimpleResult.svalue(wrap(okey, strength(state)));
  1793. });
  1794. };
  1795. var cExtract = function (path, obj, fields, strength) {
  1796. var results = map$1(fields, function (field) {
  1797. return cExtractOne(path, obj, field, strength);
  1798. });
  1799. return ResultCombine.consolidateObj(results, {});
  1800. };
  1801. var value$1 = function (validator) {
  1802. var extract = function (path, strength, val) {
  1803. return SimpleResult.bindError(validator(val, strength), function (err) {
  1804. return custom(path, err);
  1805. });
  1806. };
  1807. var toString = function () {
  1808. return 'val';
  1809. };
  1810. var toDsl = function () {
  1811. return typeAdt.itemOf(validator);
  1812. };
  1813. return {
  1814. extract: extract,
  1815. toString: toString,
  1816. toDsl: toDsl
  1817. };
  1818. };
  1819. var getSetKeys = function (obj) {
  1820. var keys$1 = keys(obj);
  1821. return filter(keys$1, function (k) {
  1822. return hasKey$1(obj, k);
  1823. });
  1824. };
  1825. var objOfOnly = function (fields) {
  1826. var delegate = objOf(fields);
  1827. var fieldNames = foldr(fields, function (acc, f) {
  1828. return f.fold(function (key) {
  1829. return deepMerge(acc, wrap$1(key, true));
  1830. }, constant(acc));
  1831. }, {});
  1832. var extract = function (path, strength, o) {
  1833. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1834. var extra = filter(keys, function (k) {
  1835. return !hasKey$1(fieldNames, k);
  1836. });
  1837. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1838. };
  1839. return {
  1840. extract: extract,
  1841. toString: delegate.toString,
  1842. toDsl: delegate.toDsl
  1843. };
  1844. };
  1845. var objOf = function (fields) {
  1846. var extract = function (path, strength, o) {
  1847. return cExtract(path, o, fields, strength);
  1848. };
  1849. var toString = function () {
  1850. var fieldStrings = map$1(fields, function (field) {
  1851. return field.fold(function (key, okey, presence, prop) {
  1852. return key + ' -> ' + prop.toString();
  1853. }, function (okey, instantiator) {
  1854. return 'state(' + okey + ')';
  1855. });
  1856. });
  1857. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1858. };
  1859. var toDsl = function () {
  1860. return typeAdt.objOf(map$1(fields, function (f) {
  1861. return f.fold(function (key, okey, presence, prop) {
  1862. return fieldAdt.field(key, presence, prop);
  1863. }, function (okey, instantiator) {
  1864. return fieldAdt.state(okey);
  1865. });
  1866. }));
  1867. };
  1868. return {
  1869. extract: extract,
  1870. toString: toString,
  1871. toDsl: toDsl
  1872. };
  1873. };
  1874. var arrOf = function (prop) {
  1875. var extract = function (path, strength, array) {
  1876. var results = map$1(array, function (a, i) {
  1877. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1878. });
  1879. return ResultCombine.consolidateArr(results);
  1880. };
  1881. var toString = function () {
  1882. return 'array(' + prop.toString() + ')';
  1883. };
  1884. var toDsl = function () {
  1885. return typeAdt.arrOf(prop);
  1886. };
  1887. return {
  1888. extract: extract,
  1889. toString: toString,
  1890. toDsl: toDsl
  1891. };
  1892. };
  1893. var setOf = function (validator, prop) {
  1894. var validateKeys = function (path, keys) {
  1895. return arrOf(value$1(validator)).extract(path, identity, keys);
  1896. };
  1897. var extract = function (path, strength, o) {
  1898. var keys$1 = keys(o);
  1899. var validatedKeys = validateKeys(path, keys$1);
  1900. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1901. var schema = map$1(validKeys, function (vk) {
  1902. return adt$1.field(vk, vk, strict(), prop);
  1903. });
  1904. return objOf(schema).extract(path, strength, o);
  1905. });
  1906. };
  1907. var toString = function () {
  1908. return 'setOf(' + prop.toString() + ')';
  1909. };
  1910. var toDsl = function () {
  1911. return typeAdt.setOf(validator, prop);
  1912. };
  1913. return {
  1914. extract: extract,
  1915. toString: toString,
  1916. toDsl: toDsl
  1917. };
  1918. };
  1919. var anyValue = constant(value$1(SimpleResult.svalue));
  1920. var state = adt$1.state;
  1921. var field = adt$1.field;
  1922. var chooseFrom = function (path, strength, input, branches, ch) {
  1923. var fields = readOptFrom$1(branches, ch);
  1924. return fields.fold(function () {
  1925. return missingBranch(path, branches, ch);
  1926. }, function (vp) {
  1927. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1928. });
  1929. };
  1930. var choose = function (key, branches) {
  1931. var extract = function (path, strength, input) {
  1932. var choice = readOptFrom$1(input, key);
  1933. return choice.fold(function () {
  1934. return missingKey(path, key);
  1935. }, function (chosen) {
  1936. return chooseFrom(path, strength, input, branches, chosen);
  1937. });
  1938. };
  1939. var toString = function () {
  1940. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1941. };
  1942. var toDsl = function () {
  1943. return typeAdt.choiceOf(key, branches);
  1944. };
  1945. return {
  1946. extract: extract,
  1947. toString: toString,
  1948. toDsl: toDsl
  1949. };
  1950. };
  1951. var _anyValue = value$1(SimpleResult.svalue);
  1952. var valueOf = function (validator) {
  1953. return value$1(function (v) {
  1954. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1955. });
  1956. };
  1957. var setOf$1 = function (validator, prop) {
  1958. return setOf(function (v) {
  1959. return SimpleResult.fromResult(validator(v));
  1960. }, prop);
  1961. };
  1962. var extract = function (label, prop, strength, obj) {
  1963. var res = prop.extract([label], strength, obj);
  1964. return SimpleResult.mapError(res, function (errs) {
  1965. return {
  1966. input: obj,
  1967. errors: errs
  1968. };
  1969. });
  1970. };
  1971. var asRaw = function (label, prop, obj) {
  1972. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1973. };
  1974. var getOrDie = function (extraction) {
  1975. return extraction.fold(function (errInfo) {
  1976. throw new Error(formatError(errInfo));
  1977. }, identity);
  1978. };
  1979. var asRawOrDie = function (label, prop, obj) {
  1980. return getOrDie(asRaw(label, prop, obj));
  1981. };
  1982. var formatError = function (errInfo) {
  1983. return 'Errors: \n' + formatErrors(errInfo.errors) + '\n\nInput object: ' + formatObj(errInfo.input);
  1984. };
  1985. var choose$1 = function (key, branches) {
  1986. return choose(key, map(branches, objOf));
  1987. };
  1988. var anyValue$1 = constant(_anyValue);
  1989. var typedValue = function (validator, expectedType) {
  1990. return value$1(function (a) {
  1991. var actualType = typeof a;
  1992. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1993. });
  1994. };
  1995. var functionProcessor = typedValue(isFunction, 'function');
  1996. var strict$1 = function (key) {
  1997. return field(key, key, strict(), anyValue());
  1998. };
  1999. var strictOf = function (key, schema) {
  2000. return field(key, key, strict(), schema);
  2001. };
  2002. var strictFunction = function (key) {
  2003. return strictOf(key, functionProcessor);
  2004. };
  2005. var forbid = function (key, message) {
  2006. return field(key, key, asOption(), value$1(function (v) {
  2007. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  2008. }));
  2009. };
  2010. var strictObjOf = function (key, objSchema) {
  2011. return field(key, key, strict(), objOf(objSchema));
  2012. };
  2013. var option = function (key) {
  2014. return field(key, key, asOption(), anyValue());
  2015. };
  2016. var optionOf = function (key, schema) {
  2017. return field(key, key, asOption(), schema);
  2018. };
  2019. var optionObjOf = function (key, objSchema) {
  2020. return optionOf(key, objOf(objSchema));
  2021. };
  2022. var optionObjOfOnly = function (key, objSchema) {
  2023. return optionOf(key, objOfOnly(objSchema));
  2024. };
  2025. var defaulted$1 = function (key, fallback) {
  2026. return field(key, key, defaulted(fallback), anyValue());
  2027. };
  2028. var defaultedOf = function (key, fallback, schema) {
  2029. return field(key, key, defaulted(fallback), schema);
  2030. };
  2031. var defaultedObjOf = function (key, fallback, objSchema) {
  2032. return defaultedOf(key, fallback, objOf(objSchema));
  2033. };
  2034. var state$1 = function (okey, instantiator) {
  2035. return state(okey, instantiator);
  2036. };
  2037. var isSource = function (component, simulatedEvent) {
  2038. return eq(component.element(), simulatedEvent.event().target());
  2039. };
  2040. var nu$4 = function (parts) {
  2041. if (!hasKey$1(parts, 'can') && !hasKey$1(parts, 'abort') && !hasKey$1(parts, 'run')) {
  2042. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2043. }
  2044. return asRawOrDie('Extracting event.handler', objOfOnly([
  2045. defaulted$1('can', constant(true)),
  2046. defaulted$1('abort', constant(false)),
  2047. defaulted$1('run', noop)
  2048. ]), parts);
  2049. };
  2050. var all$1 = function (handlers, f) {
  2051. return function () {
  2052. var args = [];
  2053. for (var _i = 0; _i < arguments.length; _i++) {
  2054. args[_i] = arguments[_i];
  2055. }
  2056. return foldl(handlers, function (acc, handler) {
  2057. return acc && f(handler).apply(undefined, args);
  2058. }, true);
  2059. };
  2060. };
  2061. var any = function (handlers, f) {
  2062. return function () {
  2063. var args = [];
  2064. for (var _i = 0; _i < arguments.length; _i++) {
  2065. args[_i] = arguments[_i];
  2066. }
  2067. return foldl(handlers, function (acc, handler) {
  2068. return acc || f(handler).apply(undefined, args);
  2069. }, false);
  2070. };
  2071. };
  2072. var read = function (handler) {
  2073. return isFunction(handler) ? {
  2074. can: constant(true),
  2075. abort: constant(false),
  2076. run: handler
  2077. } : handler;
  2078. };
  2079. var fuse = function (handlers) {
  2080. var can = all$1(handlers, function (handler) {
  2081. return handler.can;
  2082. });
  2083. var abort = any(handlers, function (handler) {
  2084. return handler.abort;
  2085. });
  2086. var run = function () {
  2087. var args = [];
  2088. for (var _i = 0; _i < arguments.length; _i++) {
  2089. args[_i] = arguments[_i];
  2090. }
  2091. each$1(handlers, function (handler) {
  2092. handler.run.apply(undefined, args);
  2093. });
  2094. };
  2095. return nu$4({
  2096. can: can,
  2097. abort: abort,
  2098. run: run
  2099. });
  2100. };
  2101. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2102. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  2103. }
  2104. var ancestor = function (scope, predicate, isRoot) {
  2105. var element = scope.dom();
  2106. var stop = isFunction(isRoot) ? isRoot : constant(false);
  2107. while (element.parentNode) {
  2108. element = element.parentNode;
  2109. var el = Element.fromDom(element);
  2110. if (predicate(el)) {
  2111. return Option.some(el);
  2112. } else if (stop(el)) {
  2113. break;
  2114. }
  2115. }
  2116. return Option.none();
  2117. };
  2118. var closest = function (scope, predicate, isRoot) {
  2119. var is = function (s, test) {
  2120. return test(s);
  2121. };
  2122. return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  2123. };
  2124. var descendant = function (scope, predicate) {
  2125. var descend = function (node) {
  2126. for (var i = 0; i < node.childNodes.length; i++) {
  2127. var child_1 = Element.fromDom(node.childNodes[i]);
  2128. if (predicate(child_1)) {
  2129. return Option.some(child_1);
  2130. }
  2131. var res = descend(node.childNodes[i]);
  2132. if (res.isSome()) {
  2133. return res;
  2134. }
  2135. }
  2136. return Option.none();
  2137. };
  2138. return descend(scope.dom());
  2139. };
  2140. var closest$1 = function (target, transform, isRoot) {
  2141. var delegate = closest(target, function (elem) {
  2142. return transform(elem).isSome();
  2143. }, isRoot);
  2144. return delegate.bind(transform);
  2145. };
  2146. var derive = function (configs) {
  2147. return wrapAll$1(configs);
  2148. };
  2149. var abort = function (name, predicate) {
  2150. return {
  2151. key: name,
  2152. value: nu$4({ abort: predicate })
  2153. };
  2154. };
  2155. var can = function (name, predicate) {
  2156. return {
  2157. key: name,
  2158. value: nu$4({ can: predicate })
  2159. };
  2160. };
  2161. var run = function (name, handler) {
  2162. return {
  2163. key: name,
  2164. value: nu$4({ run: handler })
  2165. };
  2166. };
  2167. var runActionExtra = function (name, action, extra) {
  2168. return {
  2169. key: name,
  2170. value: nu$4({
  2171. run: function (component) {
  2172. action.apply(undefined, [component].concat(extra));
  2173. }
  2174. })
  2175. };
  2176. };
  2177. var runOnName = function (name) {
  2178. return function (handler) {
  2179. return run(name, handler);
  2180. };
  2181. };
  2182. var runOnSourceName = function (name) {
  2183. return function (handler) {
  2184. return {
  2185. key: name,
  2186. value: nu$4({
  2187. run: function (component, simulatedEvent) {
  2188. if (isSource(component, simulatedEvent)) {
  2189. handler(component, simulatedEvent);
  2190. }
  2191. }
  2192. })
  2193. };
  2194. };
  2195. };
  2196. var redirectToUid = function (name, uid) {
  2197. return run(name, function (component, simulatedEvent) {
  2198. component.getSystem().getByUid(uid).each(function (redirectee) {
  2199. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2200. });
  2201. });
  2202. };
  2203. var redirectToPart = function (name, detail, partName) {
  2204. var uid = detail.partUids[partName];
  2205. return redirectToUid(name, uid);
  2206. };
  2207. var cutter = function (name) {
  2208. return run(name, function (component, simulatedEvent) {
  2209. simulatedEvent.cut();
  2210. });
  2211. };
  2212. var stopper = function (name) {
  2213. return run(name, function (component, simulatedEvent) {
  2214. simulatedEvent.stop();
  2215. });
  2216. };
  2217. var runOnSource = function (name, f) {
  2218. return runOnSourceName(name)(f);
  2219. };
  2220. var runOnAttached = runOnSourceName(attachedToDom());
  2221. var runOnDetached = runOnSourceName(detachedFromDom());
  2222. var runOnInit = runOnSourceName(systemInit());
  2223. var runOnExecute = runOnName(execute());
  2224. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2225. var delegate = apiFunction.toString();
  2226. var endIndex = delegate.indexOf(')') + 1;
  2227. var openBracketIndex = delegate.indexOf('(');
  2228. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2229. f.toFunctionAnnotation = function () {
  2230. return {
  2231. name: apiName,
  2232. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2233. };
  2234. };
  2235. return f;
  2236. };
  2237. var cleanParameters = function (parameters) {
  2238. return map$1(parameters, function (p) {
  2239. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2240. });
  2241. };
  2242. var markAsExtraApi = function (f, extraName) {
  2243. var delegate = f.toString();
  2244. var endIndex = delegate.indexOf(')') + 1;
  2245. var openBracketIndex = delegate.indexOf('(');
  2246. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2247. f.toFunctionAnnotation = function () {
  2248. return {
  2249. name: extraName,
  2250. parameters: cleanParameters(parameters)
  2251. };
  2252. };
  2253. return f;
  2254. };
  2255. var markAsSketchApi = function (f, apiFunction) {
  2256. var delegate = apiFunction.toString();
  2257. var endIndex = delegate.indexOf(')') + 1;
  2258. var openBracketIndex = delegate.indexOf('(');
  2259. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2260. f.toFunctionAnnotation = function () {
  2261. return {
  2262. name: 'OVERRIDE',
  2263. parameters: cleanParameters(parameters.slice(1))
  2264. };
  2265. };
  2266. return f;
  2267. };
  2268. var nu$5 = function (s) {
  2269. return {
  2270. classes: s.classes !== undefined ? s.classes : [],
  2271. attributes: s.attributes !== undefined ? s.attributes : {},
  2272. styles: s.styles !== undefined ? s.styles : {}
  2273. };
  2274. };
  2275. var merge$1 = function (defnA, mod) {
  2276. return __assign(__assign({}, defnA), {
  2277. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2278. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2279. classes: defnA.classes.concat(mod.classes)
  2280. });
  2281. };
  2282. var executeEvent = function (bConfig, bState, executor) {
  2283. return runOnExecute(function (component) {
  2284. executor(component, bConfig, bState);
  2285. });
  2286. };
  2287. var loadEvent = function (bConfig, bState, f) {
  2288. return runOnInit(function (component, simulatedEvent) {
  2289. f(component, bConfig, bState);
  2290. });
  2291. };
  2292. var create = function (schema, name, active, apis, extra, state) {
  2293. var configSchema = objOfOnly(schema);
  2294. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2295. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2296. };
  2297. var createModes = function (modes, name, active, apis, extra, state) {
  2298. var configSchema = modes;
  2299. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2300. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2301. };
  2302. var wrapApi = function (bName, apiFunction, apiName) {
  2303. var f = function (component) {
  2304. var rest = [];
  2305. for (var _i = 1; _i < arguments.length; _i++) {
  2306. rest[_i - 1] = arguments[_i];
  2307. }
  2308. var args = [component].concat(rest);
  2309. return component.config({ name: constant(bName) }).fold(function () {
  2310. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2311. }, function (info) {
  2312. var rest = Array.prototype.slice.call(args, 1);
  2313. return apiFunction.apply(undefined, [
  2314. component,
  2315. info.config,
  2316. info.state
  2317. ].concat(rest));
  2318. });
  2319. };
  2320. return markAsBehaviourApi(f, apiName, apiFunction);
  2321. };
  2322. var revokeBehaviour = function (name) {
  2323. return {
  2324. key: name,
  2325. value: undefined
  2326. };
  2327. };
  2328. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2329. var getConfig = function (info) {
  2330. return hasKey$1(info, name) ? info[name]() : Option.none();
  2331. };
  2332. var wrappedApis = map(apis, function (apiF, apiName) {
  2333. return wrapApi(name, apiF, apiName);
  2334. });
  2335. var wrappedExtra = map(extra, function (extraF, extraName) {
  2336. return markAsExtraApi(extraF, extraName);
  2337. });
  2338. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2339. revoke: curry(revokeBehaviour, name),
  2340. config: function (spec) {
  2341. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  2342. return {
  2343. key: name,
  2344. value: {
  2345. config: prepared,
  2346. me: me,
  2347. configAsRaw: cached(function () {
  2348. return asRawOrDie(name + '-config', configSchema, spec);
  2349. }),
  2350. initialConfig: spec,
  2351. state: state
  2352. }
  2353. };
  2354. },
  2355. schema: function () {
  2356. return schemaSchema;
  2357. },
  2358. exhibit: function (info, base) {
  2359. return getConfig(info).bind(function (behaviourInfo) {
  2360. return readOptFrom$1(active, 'exhibit').map(function (exhibitor) {
  2361. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2362. });
  2363. }).getOr(nu$5({}));
  2364. },
  2365. name: function () {
  2366. return name;
  2367. },
  2368. handlers: function (info) {
  2369. return getConfig(info).map(function (behaviourInfo) {
  2370. var getEvents = readOr$1('events', function (a, b) {
  2371. return {};
  2372. })(active);
  2373. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2374. }).getOr({});
  2375. }
  2376. });
  2377. return me;
  2378. };
  2379. var NoState = {
  2380. init: function () {
  2381. return nu$6({
  2382. readState: function () {
  2383. return 'No State required';
  2384. }
  2385. });
  2386. }
  2387. };
  2388. var nu$6 = function (spec) {
  2389. return spec;
  2390. };
  2391. var derive$1 = function (capabilities) {
  2392. return wrapAll$1(capabilities);
  2393. };
  2394. var simpleSchema = objOfOnly([
  2395. strict$1('fields'),
  2396. strict$1('name'),
  2397. defaulted$1('active', {}),
  2398. defaulted$1('apis', {}),
  2399. defaulted$1('state', NoState),
  2400. defaulted$1('extra', {})
  2401. ]);
  2402. var create$1 = function (data) {
  2403. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  2404. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2405. };
  2406. var modeSchema = objOfOnly([
  2407. strict$1('branchKey'),
  2408. strict$1('branches'),
  2409. strict$1('name'),
  2410. defaulted$1('active', {}),
  2411. defaulted$1('apis', {}),
  2412. defaulted$1('state', NoState),
  2413. defaulted$1('extra', {})
  2414. ]);
  2415. var createModes$1 = function (data) {
  2416. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  2417. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2418. };
  2419. var revoke = constant(undefined);
  2420. var rawSet = function (dom, key, value) {
  2421. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2422. dom.setAttribute(key, value + '');
  2423. } else {
  2424. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2425. throw new Error('Attribute value was not simple');
  2426. }
  2427. };
  2428. var set = function (element, key, value) {
  2429. rawSet(element.dom(), key, value);
  2430. };
  2431. var setAll = function (element, attrs) {
  2432. var dom = element.dom();
  2433. each(attrs, function (v, k) {
  2434. rawSet(dom, k, v);
  2435. });
  2436. };
  2437. var get = function (element, key) {
  2438. var v = element.dom().getAttribute(key);
  2439. return v === null ? undefined : v;
  2440. };
  2441. var has$1 = function (element, key) {
  2442. var dom = element.dom();
  2443. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2444. };
  2445. var remove$1 = function (element, key) {
  2446. element.dom().removeAttribute(key);
  2447. };
  2448. var read$1 = function (element, attr) {
  2449. var value = get(element, attr);
  2450. return value === undefined || value === '' ? [] : value.split(' ');
  2451. };
  2452. var add = function (element, attr, id) {
  2453. var old = read$1(element, attr);
  2454. var nu = old.concat([id]);
  2455. set(element, attr, nu.join(' '));
  2456. return true;
  2457. };
  2458. var remove$2 = function (element, attr, id) {
  2459. var nu = filter(read$1(element, attr), function (v) {
  2460. return v !== id;
  2461. });
  2462. if (nu.length > 0) {
  2463. set(element, attr, nu.join(' '));
  2464. } else {
  2465. remove$1(element, attr);
  2466. }
  2467. return false;
  2468. };
  2469. var supports = function (element) {
  2470. return element.dom().classList !== undefined;
  2471. };
  2472. var get$1 = function (element) {
  2473. return read$1(element, 'class');
  2474. };
  2475. var add$1 = function (element, clazz) {
  2476. return add(element, 'class', clazz);
  2477. };
  2478. var remove$3 = function (element, clazz) {
  2479. return remove$2(element, 'class', clazz);
  2480. };
  2481. var add$2 = function (element, clazz) {
  2482. if (supports(element)) {
  2483. element.dom().classList.add(clazz);
  2484. } else {
  2485. add$1(element, clazz);
  2486. }
  2487. };
  2488. var cleanClass = function (element) {
  2489. var classList = supports(element) ? element.dom().classList : get$1(element);
  2490. if (classList.length === 0) {
  2491. remove$1(element, 'class');
  2492. }
  2493. };
  2494. var remove$4 = function (element, clazz) {
  2495. if (supports(element)) {
  2496. var classList = element.dom().classList;
  2497. classList.remove(clazz);
  2498. } else {
  2499. remove$3(element, clazz);
  2500. }
  2501. cleanClass(element);
  2502. };
  2503. var has$2 = function (element, clazz) {
  2504. return supports(element) && element.dom().classList.contains(clazz);
  2505. };
  2506. var swap = function (element, addCls, removeCls) {
  2507. remove$4(element, removeCls);
  2508. add$2(element, addCls);
  2509. };
  2510. var toAlpha = function (component, swapConfig, swapState) {
  2511. swap(component.element(), swapConfig.alpha, swapConfig.omega);
  2512. };
  2513. var toOmega = function (component, swapConfig, swapState) {
  2514. swap(component.element(), swapConfig.omega, swapConfig.alpha);
  2515. };
  2516. var clear = function (component, swapConfig, swapState) {
  2517. remove$4(component.element(), swapConfig.alpha);
  2518. remove$4(component.element(), swapConfig.omega);
  2519. };
  2520. var isAlpha = function (component, swapConfig, swapState) {
  2521. return has$2(component.element(), swapConfig.alpha);
  2522. };
  2523. var isOmega = function (component, swapConfig, swapState) {
  2524. return has$2(component.element(), swapConfig.omega);
  2525. };
  2526. var SwapApis = /*#__PURE__*/Object.freeze({
  2527. toAlpha: toAlpha,
  2528. toOmega: toOmega,
  2529. isAlpha: isAlpha,
  2530. isOmega: isOmega,
  2531. clear: clear
  2532. });
  2533. var SwapSchema = [
  2534. strict$1('alpha'),
  2535. strict$1('omega')
  2536. ];
  2537. var Swapping = create$1({
  2538. fields: SwapSchema,
  2539. name: 'swapping',
  2540. apis: SwapApis
  2541. });
  2542. var focus$1 = function (element) {
  2543. element.dom().focus();
  2544. };
  2545. var blur = function (element) {
  2546. element.dom().blur();
  2547. };
  2548. var hasFocus = function (element) {
  2549. var doc = owner(element).dom();
  2550. return element.dom() === doc.activeElement;
  2551. };
  2552. var active = function (_doc) {
  2553. var doc = _doc !== undefined ? _doc.dom() : domGlobals.document;
  2554. return Option.from(doc.activeElement).map(Element.fromDom);
  2555. };
  2556. var search = function (element) {
  2557. return active(owner(element)).filter(function (e) {
  2558. return element.dom().contains(e.dom());
  2559. });
  2560. };
  2561. var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2562. var global$2 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2563. var openLink = function (target) {
  2564. var link = domGlobals.document.createElement('a');
  2565. link.target = '_blank';
  2566. link.href = target.href;
  2567. link.rel = 'noreferrer noopener';
  2568. var nuEvt = domGlobals.document.createEvent('MouseEvents');
  2569. nuEvt.initMouseEvent('click', true, true, domGlobals.window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2570. domGlobals.document.body.appendChild(link);
  2571. link.dispatchEvent(nuEvt);
  2572. domGlobals.document.body.removeChild(link);
  2573. };
  2574. var TinyCodeDupe = { openLink: openLink };
  2575. var isSkinDisabled = function (editor) {
  2576. return editor.settings.skin === false;
  2577. };
  2578. var readOnlyOnInit = function (editor) {
  2579. return false;
  2580. };
  2581. var formatChanged = 'formatChanged';
  2582. var orientationChanged = 'orientationChanged';
  2583. var dropupDismissed = 'dropupDismissed';
  2584. var TinyChannels = {
  2585. formatChanged: constant(formatChanged),
  2586. orientationChanged: constant(orientationChanged),
  2587. dropupDismissed: constant(dropupDismissed)
  2588. };
  2589. var fromHtml$1 = function (html, scope) {
  2590. var doc = scope || domGlobals.document;
  2591. var div = doc.createElement('div');
  2592. div.innerHTML = html;
  2593. return children(Element.fromDom(div));
  2594. };
  2595. var get$2 = function (element) {
  2596. return element.dom().innerHTML;
  2597. };
  2598. var set$1 = function (element, content) {
  2599. var owner$1 = owner(element);
  2600. var docDom = owner$1.dom();
  2601. var fragment = Element.fromDom(docDom.createDocumentFragment());
  2602. var contentElements = fromHtml$1(content, docDom);
  2603. append$1(fragment, contentElements);
  2604. empty(element);
  2605. append(element, fragment);
  2606. };
  2607. var getOuter = function (element) {
  2608. var container = Element.fromTag('div');
  2609. var clone = Element.fromDom(element.dom().cloneNode(true));
  2610. append(container, clone);
  2611. return get$2(container);
  2612. };
  2613. var clone = function (original, isDeep) {
  2614. return Element.fromDom(original.dom().cloneNode(isDeep));
  2615. };
  2616. var shallow$1 = function (original) {
  2617. return clone(original, false);
  2618. };
  2619. var getHtml = function (element) {
  2620. var clone = shallow$1(element);
  2621. return getOuter(clone);
  2622. };
  2623. var element = function (elem) {
  2624. return getHtml(elem);
  2625. };
  2626. var chooseChannels = function (channels, message) {
  2627. return message.universal() ? channels : filter(channels, function (ch) {
  2628. return contains(message.channels(), ch);
  2629. });
  2630. };
  2631. var events = function (receiveConfig) {
  2632. return derive([run(receive(), function (component, message) {
  2633. var channelMap = receiveConfig.channels;
  2634. var channels = keys(channelMap);
  2635. var targetChannels = chooseChannels(channels, message);
  2636. each$1(targetChannels, function (ch) {
  2637. var channelInfo = channelMap[ch];
  2638. var channelSchema = channelInfo.schema;
  2639. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, message.data());
  2640. channelInfo.onReceive(component, data);
  2641. });
  2642. })]);
  2643. };
  2644. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2645. events: events
  2646. });
  2647. var cat = function (arr) {
  2648. var r = [];
  2649. var push = function (x) {
  2650. r.push(x);
  2651. };
  2652. for (var i = 0; i < arr.length; i++) {
  2653. arr[i].each(push);
  2654. }
  2655. return r;
  2656. };
  2657. var sequence = function (arr) {
  2658. var r = [];
  2659. for (var i = 0; i < arr.length; i++) {
  2660. var x = arr[i];
  2661. if (x.isSome()) {
  2662. r.push(x.getOrDie());
  2663. } else {
  2664. return Option.none();
  2665. }
  2666. }
  2667. return Option.some(r);
  2668. };
  2669. var findMap = function (arr, f) {
  2670. for (var i = 0; i < arr.length; i++) {
  2671. var r = f(arr[i], i);
  2672. if (r.isSome()) {
  2673. return r;
  2674. }
  2675. }
  2676. return Option.none();
  2677. };
  2678. var someIf = function (b, a) {
  2679. return b ? Option.some(a) : Option.none();
  2680. };
  2681. var unknown$3 = 'unknown';
  2682. var EventConfiguration;
  2683. (function (EventConfiguration) {
  2684. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2685. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2686. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2687. }(EventConfiguration || (EventConfiguration = {})));
  2688. var eventConfig = Cell({});
  2689. var makeEventLogger = function (eventName, initialTarget) {
  2690. var sequence = [];
  2691. var startTime = new Date().getTime();
  2692. return {
  2693. logEventCut: function (name, target, purpose) {
  2694. sequence.push({
  2695. outcome: 'cut',
  2696. target: target,
  2697. purpose: purpose
  2698. });
  2699. },
  2700. logEventStopped: function (name, target, purpose) {
  2701. sequence.push({
  2702. outcome: 'stopped',
  2703. target: target,
  2704. purpose: purpose
  2705. });
  2706. },
  2707. logNoParent: function (name, target, purpose) {
  2708. sequence.push({
  2709. outcome: 'no-parent',
  2710. target: target,
  2711. purpose: purpose
  2712. });
  2713. },
  2714. logEventNoHandlers: function (name, target) {
  2715. sequence.push({
  2716. outcome: 'no-handlers-left',
  2717. target: target
  2718. });
  2719. },
  2720. logEventResponse: function (name, target, purpose) {
  2721. sequence.push({
  2722. outcome: 'response',
  2723. purpose: purpose,
  2724. target: target
  2725. });
  2726. },
  2727. write: function () {
  2728. var finishTime = new Date().getTime();
  2729. if (contains([
  2730. 'mousemove',
  2731. 'mouseover',
  2732. 'mouseout',
  2733. systemInit()
  2734. ], eventName)) {
  2735. return;
  2736. }
  2737. domGlobals.console.log(eventName, {
  2738. event: eventName,
  2739. time: finishTime - startTime,
  2740. target: initialTarget.dom(),
  2741. sequence: map$1(sequence, function (s) {
  2742. if (!contains([
  2743. 'cut',
  2744. 'stopped',
  2745. 'response'
  2746. ], s.outcome)) {
  2747. return s.outcome;
  2748. } else {
  2749. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2750. }
  2751. })
  2752. });
  2753. }
  2754. };
  2755. };
  2756. var processEvent = function (eventName, initialTarget, f) {
  2757. var status = readOptFrom$1(eventConfig.get(), eventName).orThunk(function () {
  2758. var patterns = keys(eventConfig.get());
  2759. return findMap(patterns, function (p) {
  2760. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  2761. });
  2762. }).getOr(EventConfiguration.NORMAL);
  2763. switch (status) {
  2764. case EventConfiguration.NORMAL:
  2765. return f(noLogger());
  2766. case EventConfiguration.LOGGING: {
  2767. var logger = makeEventLogger(eventName, initialTarget);
  2768. var output = f(logger);
  2769. logger.write();
  2770. return output;
  2771. }
  2772. case EventConfiguration.STOP:
  2773. return true;
  2774. }
  2775. };
  2776. var path = [
  2777. 'alloy/data/Fields',
  2778. 'alloy/debugging/Debugging'
  2779. ];
  2780. var getTrace = function () {
  2781. var err = new Error();
  2782. if (err.stack !== undefined) {
  2783. var lines = err.stack.split('\n');
  2784. return find$2(lines, function (line) {
  2785. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2786. return line.indexOf(p) > -1;
  2787. });
  2788. }).getOr(unknown$3);
  2789. } else {
  2790. return unknown$3;
  2791. }
  2792. };
  2793. var ignoreEvent = {
  2794. logEventCut: noop,
  2795. logEventStopped: noop,
  2796. logNoParent: noop,
  2797. logEventNoHandlers: noop,
  2798. logEventResponse: noop,
  2799. write: noop
  2800. };
  2801. var monitorEvent = function (eventName, initialTarget, f) {
  2802. return processEvent(eventName, initialTarget, f);
  2803. };
  2804. var noLogger = constant(ignoreEvent);
  2805. var menuFields = constant([
  2806. strict$1('menu'),
  2807. strict$1('selectedMenu')
  2808. ]);
  2809. var itemFields = constant([
  2810. strict$1('item'),
  2811. strict$1('selectedItem')
  2812. ]);
  2813. var schema = constant(objOf(itemFields().concat(menuFields())));
  2814. var itemSchema = constant(objOf(itemFields()));
  2815. var _initSize = strictObjOf('initSize', [
  2816. strict$1('numColumns'),
  2817. strict$1('numRows')
  2818. ]);
  2819. var itemMarkers = function () {
  2820. return strictOf('markers', itemSchema());
  2821. };
  2822. var tieredMenuMarkers = function () {
  2823. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2824. };
  2825. var markers = function (required) {
  2826. return strictObjOf('markers', map$1(required, strict$1));
  2827. };
  2828. var onPresenceHandler = function (label, fieldName, presence) {
  2829. var trace = getTrace();
  2830. return field(fieldName, fieldName, presence, valueOf(function (f) {
  2831. return Result.value(function () {
  2832. var args = [];
  2833. for (var _i = 0; _i < arguments.length; _i++) {
  2834. args[_i] = arguments[_i];
  2835. }
  2836. return f.apply(undefined, args);
  2837. });
  2838. }));
  2839. };
  2840. var onHandler = function (fieldName) {
  2841. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  2842. };
  2843. var onKeyboardHandler = function (fieldName) {
  2844. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  2845. };
  2846. var onStrictHandler = function (fieldName) {
  2847. return onPresenceHandler('onHandler', fieldName, strict());
  2848. };
  2849. var onStrictKeyboardHandler = function (fieldName) {
  2850. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  2851. };
  2852. var output = function (name, value) {
  2853. return state$1(name, constant(value));
  2854. };
  2855. var snapshot = function (name) {
  2856. return state$1(name, identity);
  2857. };
  2858. var initSize = constant(_initSize);
  2859. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  2860. onStrictHandler('onReceive'),
  2861. defaulted$1('schema', anyValue$1())
  2862. ])))];
  2863. var Receiving = create$1({
  2864. fields: ReceivingSchema,
  2865. name: 'receiving',
  2866. active: ActiveReceiving
  2867. });
  2868. var updateAriaState = function (component, toggleConfig, toggleState) {
  2869. var ariaInfo = toggleConfig.aria;
  2870. ariaInfo.update(component, ariaInfo, toggleState.get());
  2871. };
  2872. var updateClass = function (component, toggleConfig, toggleState) {
  2873. toggleConfig.toggleClass.each(function (toggleClass) {
  2874. if (toggleState.get()) {
  2875. add$2(component.element(), toggleClass);
  2876. } else {
  2877. remove$4(component.element(), toggleClass);
  2878. }
  2879. });
  2880. };
  2881. var toggle = function (component, toggleConfig, toggleState) {
  2882. set$2(component, toggleConfig, toggleState, !toggleState.get());
  2883. };
  2884. var on = function (component, toggleConfig, toggleState) {
  2885. toggleState.set(true);
  2886. updateClass(component, toggleConfig, toggleState);
  2887. updateAriaState(component, toggleConfig, toggleState);
  2888. };
  2889. var off = function (component, toggleConfig, toggleState) {
  2890. toggleState.set(false);
  2891. updateClass(component, toggleConfig, toggleState);
  2892. updateAriaState(component, toggleConfig, toggleState);
  2893. };
  2894. var set$2 = function (component, toggleConfig, toggleState, state) {
  2895. var action = state ? on : off;
  2896. action(component, toggleConfig, toggleState);
  2897. };
  2898. var isOn = function (component, toggleConfig, toggleState) {
  2899. return toggleState.get();
  2900. };
  2901. var onLoad = function (component, toggleConfig, toggleState) {
  2902. set$2(component, toggleConfig, toggleState, toggleConfig.selected);
  2903. };
  2904. var ToggleApis = /*#__PURE__*/Object.freeze({
  2905. onLoad: onLoad,
  2906. toggle: toggle,
  2907. isOn: isOn,
  2908. on: on,
  2909. off: off,
  2910. set: set$2
  2911. });
  2912. var exhibit = function (base, toggleConfig, toggleState) {
  2913. return nu$5({});
  2914. };
  2915. var events$1 = function (toggleConfig, toggleState) {
  2916. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2917. var load = loadEvent(toggleConfig, toggleState, onLoad);
  2918. return derive(flatten([
  2919. toggleConfig.toggleOnExecute ? [execute] : [],
  2920. [load]
  2921. ]));
  2922. };
  2923. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2924. exhibit: exhibit,
  2925. events: events$1
  2926. });
  2927. var SetupBehaviourCellState = function (initialState) {
  2928. var init = function () {
  2929. var cell = Cell(initialState);
  2930. var get = function () {
  2931. return cell.get();
  2932. };
  2933. var set = function (newState) {
  2934. return cell.set(newState);
  2935. };
  2936. var clear = function () {
  2937. return cell.set(initialState);
  2938. };
  2939. var readState = function () {
  2940. return cell.get();
  2941. };
  2942. return {
  2943. get: get,
  2944. set: set,
  2945. clear: clear,
  2946. readState: readState
  2947. };
  2948. };
  2949. return { init: init };
  2950. };
  2951. var updatePressed = function (component, ariaInfo, status) {
  2952. set(component.element(), 'aria-pressed', status);
  2953. if (ariaInfo.syncWithExpanded) {
  2954. updateExpanded(component, ariaInfo, status);
  2955. }
  2956. };
  2957. var updateSelected = function (component, ariaInfo, status) {
  2958. set(component.element(), 'aria-selected', status);
  2959. };
  2960. var updateChecked = function (component, ariaInfo, status) {
  2961. set(component.element(), 'aria-checked', status);
  2962. };
  2963. var updateExpanded = function (component, ariaInfo, status) {
  2964. set(component.element(), 'aria-expanded', status);
  2965. };
  2966. var ToggleSchema = [
  2967. defaulted$1('selected', false),
  2968. option('toggleClass'),
  2969. defaulted$1('toggleOnExecute', true),
  2970. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  2971. pressed: [
  2972. defaulted$1('syncWithExpanded', false),
  2973. output('update', updatePressed)
  2974. ],
  2975. checked: [output('update', updateChecked)],
  2976. expanded: [output('update', updateExpanded)],
  2977. selected: [output('update', updateSelected)],
  2978. none: [output('update', noop)]
  2979. }))
  2980. ];
  2981. var Toggling = create$1({
  2982. fields: ToggleSchema,
  2983. name: 'toggling',
  2984. active: ActiveToggle,
  2985. apis: ToggleApis,
  2986. state: SetupBehaviourCellState(false)
  2987. });
  2988. var format = function (command, update) {
  2989. return Receiving.config({
  2990. channels: wrap$1(TinyChannels.formatChanged(), {
  2991. onReceive: function (button, data) {
  2992. if (data.command === command) {
  2993. update(button, data.state);
  2994. }
  2995. }
  2996. })
  2997. });
  2998. };
  2999. var orientation = function (onReceive) {
  3000. return Receiving.config({ channels: wrap$1(TinyChannels.orientationChanged(), { onReceive: onReceive }) });
  3001. };
  3002. var receive$1 = function (channel, onReceive) {
  3003. return {
  3004. key: channel,
  3005. value: { onReceive: onReceive }
  3006. };
  3007. };
  3008. var Receivers = {
  3009. format: format,
  3010. orientation: orientation,
  3011. receive: receive$1
  3012. };
  3013. var prefix = 'tinymce-mobile';
  3014. var resolve = function (p) {
  3015. return prefix + '-' + p;
  3016. };
  3017. var Styles = {
  3018. resolve: resolve,
  3019. prefix: constant(prefix)
  3020. };
  3021. var events$2 = function (optAction) {
  3022. var executeHandler = function (action) {
  3023. return run(execute(), function (component, simulatedEvent) {
  3024. action(component);
  3025. simulatedEvent.stop();
  3026. });
  3027. };
  3028. var onClick = function (component, simulatedEvent) {
  3029. simulatedEvent.stop();
  3030. emitExecute(component);
  3031. };
  3032. var onMousedown = function (component, simulatedEvent) {
  3033. simulatedEvent.cut();
  3034. };
  3035. var pointerEvents = detect$3().deviceType.isTouch() ? [run(tap(), onClick)] : [
  3036. run(click(), onClick),
  3037. run(mousedown(), onMousedown)
  3038. ];
  3039. return derive(flatten([
  3040. optAction.map(executeHandler).toArray(),
  3041. pointerEvents
  3042. ]));
  3043. };
  3044. var focus$2 = function (component, focusConfig) {
  3045. if (!focusConfig.ignore) {
  3046. focus$1(component.element());
  3047. focusConfig.onFocus(component);
  3048. }
  3049. };
  3050. var blur$1 = function (component, focusConfig) {
  3051. if (!focusConfig.ignore) {
  3052. blur(component.element());
  3053. }
  3054. };
  3055. var isFocused = function (component) {
  3056. return hasFocus(component.element());
  3057. };
  3058. var FocusApis = /*#__PURE__*/Object.freeze({
  3059. focus: focus$2,
  3060. blur: blur$1,
  3061. isFocused: isFocused
  3062. });
  3063. var exhibit$1 = function (base, focusConfig) {
  3064. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3065. return nu$5(mod);
  3066. };
  3067. var events$3 = function (focusConfig) {
  3068. return derive([run(focus(), function (component, simulatedEvent) {
  3069. focus$2(component, focusConfig);
  3070. simulatedEvent.stop();
  3071. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3072. simulatedEvent.event().prevent();
  3073. })] : []));
  3074. };
  3075. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3076. exhibit: exhibit$1,
  3077. events: events$3
  3078. });
  3079. var FocusSchema = [
  3080. onHandler('onFocus'),
  3081. defaulted$1('stopMousedown', false),
  3082. defaulted$1('ignore', false)
  3083. ];
  3084. var Focusing = create$1({
  3085. fields: FocusSchema,
  3086. name: 'focusing',
  3087. active: ActiveFocus,
  3088. apis: FocusApis
  3089. });
  3090. var isSupported = function (dom) {
  3091. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  3092. };
  3093. var internalSet = function (dom, property, value) {
  3094. if (!isString(value)) {
  3095. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3096. throw new Error('CSS value must be a string: ' + value);
  3097. }
  3098. if (isSupported(dom)) {
  3099. dom.style.setProperty(property, value);
  3100. }
  3101. };
  3102. var internalRemove = function (dom, property) {
  3103. if (isSupported(dom)) {
  3104. dom.style.removeProperty(property);
  3105. }
  3106. };
  3107. var set$3 = function (element, property, value) {
  3108. var dom = element.dom();
  3109. internalSet(dom, property, value);
  3110. };
  3111. var setAll$1 = function (element, css) {
  3112. var dom = element.dom();
  3113. each(css, function (v, k) {
  3114. internalSet(dom, k, v);
  3115. });
  3116. };
  3117. var get$3 = function (element, property) {
  3118. var dom = element.dom();
  3119. var styles = domGlobals.window.getComputedStyle(dom);
  3120. var r = styles.getPropertyValue(property);
  3121. var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3122. return v === null ? undefined : v;
  3123. };
  3124. var getUnsafeProperty = function (dom, property) {
  3125. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  3126. };
  3127. var getRaw = function (element, property) {
  3128. var dom = element.dom();
  3129. var raw = getUnsafeProperty(dom, property);
  3130. return Option.from(raw).filter(function (r) {
  3131. return r.length > 0;
  3132. });
  3133. };
  3134. var remove$5 = function (element, property) {
  3135. var dom = element.dom();
  3136. internalRemove(dom, property);
  3137. if (has$1(element, 'style') && trim(get(element, 'style')) === '') {
  3138. remove$1(element, 'style');
  3139. }
  3140. };
  3141. var reflow = function (e) {
  3142. return e.dom().offsetWidth;
  3143. };
  3144. function Dimension (name, getOffset) {
  3145. var set = function (element, h) {
  3146. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3147. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3148. }
  3149. var dom = element.dom();
  3150. if (isSupported(dom)) {
  3151. dom.style[name] = h + 'px';
  3152. }
  3153. };
  3154. var get = function (element) {
  3155. var r = getOffset(element);
  3156. if (r <= 0 || r === null) {
  3157. var css = get$3(element, name);
  3158. return parseFloat(css) || 0;
  3159. }
  3160. return r;
  3161. };
  3162. var getOuter = get;
  3163. var aggregate = function (element, properties) {
  3164. return foldl(properties, function (acc, property) {
  3165. var val = get$3(element, property);
  3166. var value = val === undefined ? 0 : parseInt(val, 10);
  3167. return isNaN(value) ? acc : acc + value;
  3168. }, 0);
  3169. };
  3170. var max = function (element, value, properties) {
  3171. var cumulativeInclusions = aggregate(element, properties);
  3172. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3173. return absoluteMax;
  3174. };
  3175. return {
  3176. set: set,
  3177. get: get,
  3178. getOuter: getOuter,
  3179. aggregate: aggregate,
  3180. max: max
  3181. };
  3182. }
  3183. var api = Dimension('height', function (element) {
  3184. var dom = element.dom();
  3185. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3186. });
  3187. var get$4 = function (element) {
  3188. return api.get(element);
  3189. };
  3190. var ancestors = function (scope, predicate, isRoot) {
  3191. return filter(parents(scope, isRoot), predicate);
  3192. };
  3193. var siblings$1 = function (scope, predicate) {
  3194. return filter(siblings(scope), predicate);
  3195. };
  3196. var all$2 = function (selector) {
  3197. return all(selector);
  3198. };
  3199. var ancestors$1 = function (scope, selector, isRoot) {
  3200. return ancestors(scope, function (e) {
  3201. return is(e, selector);
  3202. }, isRoot);
  3203. };
  3204. var siblings$2 = function (scope, selector) {
  3205. return siblings$1(scope, function (e) {
  3206. return is(e, selector);
  3207. });
  3208. };
  3209. var descendants = function (scope, selector) {
  3210. return all(selector, scope);
  3211. };
  3212. var first = function (selector) {
  3213. return one(selector);
  3214. };
  3215. var ancestor$1 = function (scope, selector, isRoot) {
  3216. return ancestor(scope, function (e) {
  3217. return is(e, selector);
  3218. }, isRoot);
  3219. };
  3220. var descendant$1 = function (scope, selector) {
  3221. return one(selector, scope);
  3222. };
  3223. var closest$2 = function (scope, selector, isRoot) {
  3224. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  3225. };
  3226. var BACKSPACE = function () {
  3227. return [8];
  3228. };
  3229. var TAB = function () {
  3230. return [9];
  3231. };
  3232. var ENTER = function () {
  3233. return [13];
  3234. };
  3235. var ESCAPE = function () {
  3236. return [27];
  3237. };
  3238. var SPACE = function () {
  3239. return [32];
  3240. };
  3241. var LEFT = function () {
  3242. return [37];
  3243. };
  3244. var UP = function () {
  3245. return [38];
  3246. };
  3247. var RIGHT = function () {
  3248. return [39];
  3249. };
  3250. var DOWN = function () {
  3251. return [40];
  3252. };
  3253. var cyclePrev = function (values, index, predicate) {
  3254. var before = reverse(values.slice(0, index));
  3255. var after = reverse(values.slice(index + 1));
  3256. return find$2(before.concat(after), predicate);
  3257. };
  3258. var tryPrev = function (values, index, predicate) {
  3259. var before = reverse(values.slice(0, index));
  3260. return find$2(before, predicate);
  3261. };
  3262. var cycleNext = function (values, index, predicate) {
  3263. var before = values.slice(0, index);
  3264. var after = values.slice(index + 1);
  3265. return find$2(after.concat(before), predicate);
  3266. };
  3267. var tryNext = function (values, index, predicate) {
  3268. var after = values.slice(index + 1);
  3269. return find$2(after, predicate);
  3270. };
  3271. var inSet = function (keys) {
  3272. return function (event) {
  3273. var raw = event.raw();
  3274. return contains(keys, raw.which);
  3275. };
  3276. };
  3277. var and = function (preds) {
  3278. return function (event) {
  3279. return forall(preds, function (pred) {
  3280. return pred(event);
  3281. });
  3282. };
  3283. };
  3284. var isShift = function (event) {
  3285. var raw = event.raw();
  3286. return raw.shiftKey === true;
  3287. };
  3288. var isControl = function (event) {
  3289. var raw = event.raw();
  3290. return raw.ctrlKey === true;
  3291. };
  3292. var isNotShift = not(isShift);
  3293. var rule = function (matches, action) {
  3294. return {
  3295. matches: matches,
  3296. classification: action
  3297. };
  3298. };
  3299. var choose$2 = function (transitions, event) {
  3300. var transition = find$2(transitions, function (t) {
  3301. return t.matches(event);
  3302. });
  3303. return transition.map(function (t) {
  3304. return t.classification;
  3305. });
  3306. };
  3307. var cycleBy = function (value, delta, min, max) {
  3308. var r = value + delta;
  3309. if (r > max) {
  3310. return min;
  3311. } else {
  3312. return r < min ? max : r;
  3313. }
  3314. };
  3315. var cap = function (value, min, max) {
  3316. if (value <= min) {
  3317. return min;
  3318. } else {
  3319. return value >= max ? max : value;
  3320. }
  3321. };
  3322. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3323. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  3324. each$1(highlighted, function (h) {
  3325. if (!exists(skip, function (skipComp) {
  3326. return skipComp.element() === h;
  3327. })) {
  3328. remove$4(h, hConfig.highlightClass);
  3329. component.getSystem().getByDom(h).each(function (target) {
  3330. hConfig.onDehighlight(component, target);
  3331. emit(target, dehighlight());
  3332. });
  3333. }
  3334. });
  3335. };
  3336. var dehighlightAll = function (component, hConfig, hState) {
  3337. return dehighlightAllExcept(component, hConfig, hState, []);
  3338. };
  3339. var dehighlight$1 = function (component, hConfig, hState, target) {
  3340. if (isHighlighted(component, hConfig, hState, target)) {
  3341. remove$4(target.element(), hConfig.highlightClass);
  3342. hConfig.onDehighlight(component, target);
  3343. emit(target, dehighlight());
  3344. }
  3345. };
  3346. var highlight$1 = function (component, hConfig, hState, target) {
  3347. dehighlightAllExcept(component, hConfig, hState, [target]);
  3348. if (!isHighlighted(component, hConfig, hState, target)) {
  3349. add$2(target.element(), hConfig.highlightClass);
  3350. hConfig.onHighlight(component, target);
  3351. emit(target, highlight());
  3352. }
  3353. };
  3354. var highlightFirst = function (component, hConfig, hState) {
  3355. getFirst(component, hConfig).each(function (firstComp) {
  3356. highlight$1(component, hConfig, hState, firstComp);
  3357. });
  3358. };
  3359. var highlightLast = function (component, hConfig, hState) {
  3360. getLast(component, hConfig).each(function (lastComp) {
  3361. highlight$1(component, hConfig, hState, lastComp);
  3362. });
  3363. };
  3364. var highlightAt = function (component, hConfig, hState, index) {
  3365. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3366. throw new Error(err);
  3367. }, function (firstComp) {
  3368. highlight$1(component, hConfig, hState, firstComp);
  3369. });
  3370. };
  3371. var highlightBy = function (component, hConfig, hState, predicate) {
  3372. var candidates = getCandidates(component, hConfig);
  3373. var targetComp = find$2(candidates, predicate);
  3374. targetComp.each(function (c) {
  3375. highlight$1(component, hConfig, hState, c);
  3376. });
  3377. };
  3378. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3379. return has$2(queryTarget.element(), hConfig.highlightClass);
  3380. };
  3381. var getHighlighted = function (component, hConfig, hState) {
  3382. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  3383. return component.getSystem().getByDom(e).toOption();
  3384. });
  3385. };
  3386. var getByIndex = function (component, hConfig, hState, index) {
  3387. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3388. return Option.from(items[index]).fold(function () {
  3389. return Result.error('No element found with index ' + index);
  3390. }, component.getSystem().getByDom);
  3391. };
  3392. var getFirst = function (component, hConfig, hState) {
  3393. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  3394. return component.getSystem().getByDom(e).toOption();
  3395. });
  3396. };
  3397. var getLast = function (component, hConfig, hState) {
  3398. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3399. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  3400. return last.bind(function (c) {
  3401. return component.getSystem().getByDom(c).toOption();
  3402. });
  3403. };
  3404. var getDelta = function (component, hConfig, hState, delta) {
  3405. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3406. var current = findIndex(items, function (item) {
  3407. return has$2(item, hConfig.highlightClass);
  3408. });
  3409. return current.bind(function (selected) {
  3410. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3411. return component.getSystem().getByDom(items[dest]).toOption();
  3412. });
  3413. };
  3414. var getPrevious = function (component, hConfig, hState) {
  3415. return getDelta(component, hConfig, hState, -1);
  3416. };
  3417. var getNext = function (component, hConfig, hState) {
  3418. return getDelta(component, hConfig, hState, +1);
  3419. };
  3420. var getCandidates = function (component, hConfig, hState) {
  3421. var items = descendants(component.element(), '.' + hConfig.itemClass);
  3422. return cat(map$1(items, function (i) {
  3423. return component.getSystem().getByDom(i).toOption();
  3424. }));
  3425. };
  3426. var HighlightApis = /*#__PURE__*/Object.freeze({
  3427. dehighlightAll: dehighlightAll,
  3428. dehighlight: dehighlight$1,
  3429. highlight: highlight$1,
  3430. highlightFirst: highlightFirst,
  3431. highlightLast: highlightLast,
  3432. highlightAt: highlightAt,
  3433. highlightBy: highlightBy,
  3434. isHighlighted: isHighlighted,
  3435. getHighlighted: getHighlighted,
  3436. getFirst: getFirst,
  3437. getLast: getLast,
  3438. getPrevious: getPrevious,
  3439. getNext: getNext,
  3440. getCandidates: getCandidates
  3441. });
  3442. var HighlightSchema = [
  3443. strict$1('highlightClass'),
  3444. strict$1('itemClass'),
  3445. onHandler('onHighlight'),
  3446. onHandler('onDehighlight')
  3447. ];
  3448. var Highlighting = create$1({
  3449. fields: HighlightSchema,
  3450. name: 'highlighting',
  3451. apis: HighlightApis
  3452. });
  3453. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3454. var noChange = prevFocus.exists(function (p) {
  3455. return newFocus.exists(function (n) {
  3456. return eq(n, p);
  3457. });
  3458. });
  3459. if (!noChange) {
  3460. emitWith(component, focusShifted(), {
  3461. prevFocus: prevFocus,
  3462. newFocus: newFocus
  3463. });
  3464. }
  3465. };
  3466. var dom = function () {
  3467. var get = function (component) {
  3468. return search(component.element());
  3469. };
  3470. var set = function (component, focusee) {
  3471. var prevFocus = get(component);
  3472. component.getSystem().triggerFocus(focusee, component.element());
  3473. var newFocus = get(component);
  3474. reportFocusShifting(component, prevFocus, newFocus);
  3475. };
  3476. return {
  3477. get: get,
  3478. set: set
  3479. };
  3480. };
  3481. var highlights = function () {
  3482. var get = function (component) {
  3483. return Highlighting.getHighlighted(component).map(function (item) {
  3484. return item.element();
  3485. });
  3486. };
  3487. var set = function (component, element) {
  3488. var prevFocus = get(component);
  3489. component.getSystem().getByDom(element).fold(noop, function (item) {
  3490. Highlighting.highlight(component, item);
  3491. });
  3492. var newFocus = get(component);
  3493. reportFocusShifting(component, prevFocus, newFocus);
  3494. };
  3495. return {
  3496. get: get,
  3497. set: set
  3498. };
  3499. };
  3500. var FocusInsideModes;
  3501. (function (FocusInsideModes) {
  3502. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3503. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3504. FocusInsideModes['OnApiMode'] = 'onApi';
  3505. }(FocusInsideModes || (FocusInsideModes = {})));
  3506. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3507. var schema = function () {
  3508. return infoSchema.concat([
  3509. defaulted$1('focusManager', dom()),
  3510. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3511. return contains([
  3512. 'onFocus',
  3513. 'onEnterOrSpace',
  3514. 'onApi'
  3515. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3516. })),
  3517. output('handler', me),
  3518. output('state', stateInit),
  3519. output('sendFocusIn', optFocusIn)
  3520. ]);
  3521. };
  3522. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3523. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3524. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  3525. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3526. });
  3527. };
  3528. var toEvents = function (keyingConfig, keyingState) {
  3529. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3530. return run(focus(), function (component, simulatedEvent) {
  3531. focusIn(component, keyingConfig, keyingState);
  3532. simulatedEvent.stop();
  3533. });
  3534. });
  3535. var tryGoInsideComponent = function (component, simulatedEvent) {
  3536. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  3537. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3538. optFocusIn(keyingConfig).each(function (focusIn) {
  3539. focusIn(component, keyingConfig, keyingState);
  3540. simulatedEvent.stop();
  3541. });
  3542. }
  3543. };
  3544. return derive(onFocusHandler.toArray().concat([
  3545. run(keydown(), function (component, simulatedEvent) {
  3546. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3547. tryGoInsideComponent(component, simulatedEvent);
  3548. }, function (_) {
  3549. simulatedEvent.stop();
  3550. });
  3551. }),
  3552. run(keyup(), function (component, simulatedEvent) {
  3553. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3554. simulatedEvent.stop();
  3555. });
  3556. })
  3557. ]));
  3558. };
  3559. var me = {
  3560. schema: schema,
  3561. processKey: processKey,
  3562. toEvents: toEvents
  3563. };
  3564. return me;
  3565. };
  3566. var create$2 = function (cyclicField) {
  3567. var schema = [
  3568. option('onEscape'),
  3569. option('onEnter'),
  3570. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3571. defaulted$1('firstTabstop', 0),
  3572. defaulted$1('useTabstopAt', constant(true)),
  3573. option('visibilitySelector')
  3574. ].concat([cyclicField]);
  3575. var isVisible = function (tabbingConfig, element) {
  3576. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3577. return closest$2(element, sel);
  3578. }).getOr(element);
  3579. return get$4(target) > 0;
  3580. };
  3581. var findInitial = function (component, tabbingConfig) {
  3582. var tabstops = descendants(component.element(), tabbingConfig.selector);
  3583. var visibles = filter(tabstops, function (elem) {
  3584. return isVisible(tabbingConfig, elem);
  3585. });
  3586. return Option.from(visibles[tabbingConfig.firstTabstop]);
  3587. };
  3588. var findCurrent = function (component, tabbingConfig) {
  3589. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3590. return closest$2(elem, tabbingConfig.selector);
  3591. });
  3592. };
  3593. var isTabstop = function (tabbingConfig, element) {
  3594. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3595. };
  3596. var focusIn = function (component, tabbingConfig) {
  3597. findInitial(component, tabbingConfig).each(function (target) {
  3598. tabbingConfig.focusManager.set(component, target);
  3599. });
  3600. };
  3601. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3602. return cycle(tabstops, stopIndex, function (elem) {
  3603. return isTabstop(tabbingConfig, elem);
  3604. }).fold(function () {
  3605. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  3606. }, function (target) {
  3607. tabbingConfig.focusManager.set(component, target);
  3608. return Option.some(true);
  3609. });
  3610. };
  3611. var go = function (component, simulatedEvent, tabbingConfig, cycle) {
  3612. var tabstops = descendants(component.element(), tabbingConfig.selector);
  3613. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3614. var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
  3615. return optStopIndex.bind(function (stopIndex) {
  3616. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3617. });
  3618. });
  3619. };
  3620. var goBackwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  3621. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3622. return go(component, simulatedEvent, tabbingConfig, navigate);
  3623. };
  3624. var goForwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  3625. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3626. return go(component, simulatedEvent, tabbingConfig, navigate);
  3627. };
  3628. var execute = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  3629. return tabbingConfig.onEnter.bind(function (f) {
  3630. return f(component, simulatedEvent);
  3631. });
  3632. };
  3633. var exit = function (component, simulatedEvent, tabbingConfig, tabbingState) {
  3634. return tabbingConfig.onEscape.bind(function (f) {
  3635. return f(component, simulatedEvent);
  3636. });
  3637. };
  3638. var getKeydownRules = constant([
  3639. rule(and([
  3640. isShift,
  3641. inSet(TAB())
  3642. ]), goBackwards),
  3643. rule(inSet(TAB()), goForwards),
  3644. rule(inSet(ESCAPE()), exit),
  3645. rule(and([
  3646. isNotShift,
  3647. inSet(ENTER())
  3648. ]), execute)
  3649. ]);
  3650. var getKeyupRules = constant([]);
  3651. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3652. return Option.some(focusIn);
  3653. });
  3654. };
  3655. var AcyclicType = create$2(state$1('cyclic', constant(false)));
  3656. var CyclicType = create$2(state$1('cyclic', constant(true)));
  3657. var inside = function (target) {
  3658. return name(target) === 'input' && get(target, 'type') !== 'radio' || name(target) === 'textarea';
  3659. };
  3660. var doDefaultExecute = function (component, simulatedEvent, focused) {
  3661. dispatch(component, focused, execute());
  3662. return Option.some(true);
  3663. };
  3664. var defaultExecute = function (component, simulatedEvent, focused) {
  3665. return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  3666. };
  3667. var stopEventForFirefox = function (component, simulatedEvent) {
  3668. return Option.some(true);
  3669. };
  3670. var schema$1 = [
  3671. defaulted$1('execute', defaultExecute),
  3672. defaulted$1('useSpace', false),
  3673. defaulted$1('useEnter', true),
  3674. defaulted$1('useControlEnter', false),
  3675. defaulted$1('useDown', false)
  3676. ];
  3677. var execute$1 = function (component, simulatedEvent, executeConfig) {
  3678. return executeConfig.execute(component, simulatedEvent, component.element());
  3679. };
  3680. var getKeydownRules = function (component, simulatedEvent, executeConfig, executeState) {
  3681. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  3682. var enterExec = executeConfig.useEnter ? ENTER() : [];
  3683. var downExec = executeConfig.useDown ? DOWN() : [];
  3684. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3685. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  3686. isControl,
  3687. inSet(ENTER())
  3688. ]), execute$1)] : []);
  3689. };
  3690. var getKeyupRules = function (component, simulatedEvent, executeConfig, executeState) {
  3691. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  3692. };
  3693. var ExecutionType = typical(schema$1, NoState.init, getKeydownRules, getKeyupRules, function () {
  3694. return Option.none();
  3695. });
  3696. var flatgrid = function (spec) {
  3697. var dimensions = Cell(Option.none());
  3698. var setGridSize = function (numRows, numColumns) {
  3699. dimensions.set(Option.some({
  3700. numRows: constant(numRows),
  3701. numColumns: constant(numColumns)
  3702. }));
  3703. };
  3704. var getNumRows = function () {
  3705. return dimensions.get().map(function (d) {
  3706. return d.numRows();
  3707. });
  3708. };
  3709. var getNumColumns = function () {
  3710. return dimensions.get().map(function (d) {
  3711. return d.numColumns();
  3712. });
  3713. };
  3714. return nu$6({
  3715. readState: function () {
  3716. return dimensions.get().map(function (d) {
  3717. return {
  3718. numRows: d.numRows(),
  3719. numColumns: d.numColumns()
  3720. };
  3721. }).getOr({
  3722. numRows: '?',
  3723. numColumns: '?'
  3724. });
  3725. },
  3726. setGridSize: setGridSize,
  3727. getNumRows: getNumRows,
  3728. getNumColumns: getNumColumns
  3729. });
  3730. };
  3731. var init = function (spec) {
  3732. return spec.state(spec);
  3733. };
  3734. var KeyingState = /*#__PURE__*/Object.freeze({
  3735. flatgrid: flatgrid,
  3736. init: init
  3737. });
  3738. var onDirection = function (isLtr, isRtl) {
  3739. return function (element) {
  3740. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3741. };
  3742. };
  3743. var getDirection = function (element) {
  3744. return get$3(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3745. };
  3746. var useH = function (movement) {
  3747. return function (component, simulatedEvent, config, state) {
  3748. var move = movement(component.element());
  3749. return use(move, component, simulatedEvent, config, state);
  3750. };
  3751. };
  3752. var west = function (moveLeft, moveRight) {
  3753. var movement = onDirection(moveLeft, moveRight);
  3754. return useH(movement);
  3755. };
  3756. var east = function (moveLeft, moveRight) {
  3757. var movement = onDirection(moveRight, moveLeft);
  3758. return useH(movement);
  3759. };
  3760. var useV = function (move) {
  3761. return function (component, simulatedEvent, config, state) {
  3762. return use(move, component, simulatedEvent, config, state);
  3763. };
  3764. };
  3765. var use = function (move, component, simulatedEvent, config, state) {
  3766. var outcome = config.focusManager.get(component).bind(function (focused) {
  3767. return move(component.element(), focused, config, state);
  3768. });
  3769. return outcome.map(function (newFocus) {
  3770. config.focusManager.set(component, newFocus);
  3771. return true;
  3772. });
  3773. };
  3774. var north = useV;
  3775. var south = useV;
  3776. var move = useV;
  3777. var isHidden = function (dom) {
  3778. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3779. };
  3780. var isVisible = function (element) {
  3781. var dom = element.dom();
  3782. return !isHidden(dom);
  3783. };
  3784. var indexInfo = MixedBag([
  3785. 'index',
  3786. 'candidates'
  3787. ], []);
  3788. var locate = function (candidates, predicate) {
  3789. return findIndex(candidates, predicate).map(function (index) {
  3790. return indexInfo({
  3791. index: index,
  3792. candidates: candidates
  3793. });
  3794. });
  3795. };
  3796. var locateVisible = function (container, current, selector) {
  3797. var predicate = curry(eq, current);
  3798. var candidates = descendants(container, selector);
  3799. var visible = filter(candidates, isVisible);
  3800. return locate(visible, predicate);
  3801. };
  3802. var findIndex$1 = function (elements, target) {
  3803. return findIndex(elements, function (elem) {
  3804. return eq(target, elem);
  3805. });
  3806. };
  3807. var withGrid = function (values, index, numCols, f) {
  3808. var oldRow = Math.floor(index / numCols);
  3809. var oldColumn = index % numCols;
  3810. return f(oldRow, oldColumn).bind(function (address) {
  3811. var newIndex = address.row() * numCols + address.column();
  3812. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  3813. });
  3814. };
  3815. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  3816. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3817. var onLastRow = oldRow === numRows - 1;
  3818. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3819. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3820. return Option.some({
  3821. row: constant(oldRow),
  3822. column: constant(newColumn)
  3823. });
  3824. });
  3825. };
  3826. var cycleVertical = function (values, index, numRows, numCols, delta) {
  3827. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3828. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3829. var onLastRow = newRow === numRows - 1;
  3830. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3831. var newCol = cap(oldColumn, 0, colsInRow - 1);
  3832. return Option.some({
  3833. row: constant(newRow),
  3834. column: constant(newCol)
  3835. });
  3836. });
  3837. };
  3838. var cycleRight = function (values, index, numRows, numCols) {
  3839. return cycleHorizontal(values, index, numRows, numCols, +1);
  3840. };
  3841. var cycleLeft = function (values, index, numRows, numCols) {
  3842. return cycleHorizontal(values, index, numRows, numCols, -1);
  3843. };
  3844. var cycleUp = function (values, index, numRows, numCols) {
  3845. return cycleVertical(values, index, numRows, numCols, -1);
  3846. };
  3847. var cycleDown = function (values, index, numRows, numCols) {
  3848. return cycleVertical(values, index, numRows, numCols, +1);
  3849. };
  3850. var schema$2 = [
  3851. strict$1('selector'),
  3852. defaulted$1('execute', defaultExecute),
  3853. onKeyboardHandler('onEscape'),
  3854. defaulted$1('captureTab', false),
  3855. initSize()
  3856. ];
  3857. var focusIn = function (component, gridConfig, gridState) {
  3858. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  3859. gridConfig.focusManager.set(component, first);
  3860. });
  3861. };
  3862. var findCurrent = function (component, gridConfig) {
  3863. return gridConfig.focusManager.get(component).bind(function (elem) {
  3864. return closest$2(elem, gridConfig.selector);
  3865. });
  3866. };
  3867. var execute$2 = function (component, simulatedEvent, gridConfig, gridState) {
  3868. return findCurrent(component, gridConfig).bind(function (focused) {
  3869. return gridConfig.execute(component, simulatedEvent, focused);
  3870. });
  3871. };
  3872. var doMove = function (cycle) {
  3873. return function (element, focused, gridConfig, gridState) {
  3874. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3875. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3876. });
  3877. };
  3878. };
  3879. var handleTab = function (component, simulatedEvent, gridConfig, gridState) {
  3880. return gridConfig.captureTab ? Option.some(true) : Option.none();
  3881. };
  3882. var doEscape = function (component, simulatedEvent, gridConfig, gridState) {
  3883. return gridConfig.onEscape(component, simulatedEvent);
  3884. };
  3885. var moveLeft = doMove(cycleLeft);
  3886. var moveRight = doMove(cycleRight);
  3887. var moveNorth = doMove(cycleUp);
  3888. var moveSouth = doMove(cycleDown);
  3889. var getKeydownRules$1 = constant([
  3890. rule(inSet(LEFT()), west(moveLeft, moveRight)),
  3891. rule(inSet(RIGHT()), east(moveLeft, moveRight)),
  3892. rule(inSet(UP()), north(moveNorth)),
  3893. rule(inSet(DOWN()), south(moveSouth)),
  3894. rule(and([
  3895. isShift,
  3896. inSet(TAB())
  3897. ]), handleTab),
  3898. rule(and([
  3899. isNotShift,
  3900. inSet(TAB())
  3901. ]), handleTab),
  3902. rule(inSet(ESCAPE()), doEscape),
  3903. rule(inSet(SPACE().concat(ENTER())), execute$2)
  3904. ]);
  3905. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3906. var FlatgridType = typical(schema$2, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  3907. return Option.some(focusIn);
  3908. });
  3909. var horizontal = function (container, selector, current, delta) {
  3910. var isDisabledButton = function (candidate) {
  3911. return name(candidate) === 'button' && get(candidate, 'disabled') === 'disabled';
  3912. };
  3913. var tryCycle = function (initial, index, candidates) {
  3914. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  3915. if (newIndex === initial) {
  3916. return Option.none();
  3917. } else {
  3918. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  3919. }
  3920. };
  3921. return locateVisible(container, current, selector).bind(function (identified) {
  3922. var index = identified.index();
  3923. var candidates = identified.candidates();
  3924. return tryCycle(index, index, candidates);
  3925. });
  3926. };
  3927. var schema$3 = [
  3928. strict$1('selector'),
  3929. defaulted$1('getInitial', Option.none),
  3930. defaulted$1('execute', defaultExecute),
  3931. onKeyboardHandler('onEscape'),
  3932. defaulted$1('executeOnMove', false),
  3933. defaulted$1('allowVertical', true)
  3934. ];
  3935. var findCurrent$1 = function (component, flowConfig) {
  3936. return flowConfig.focusManager.get(component).bind(function (elem) {
  3937. return closest$2(elem, flowConfig.selector);
  3938. });
  3939. };
  3940. var execute$3 = function (component, simulatedEvent, flowConfig) {
  3941. return findCurrent$1(component, flowConfig).bind(function (focused) {
  3942. return flowConfig.execute(component, simulatedEvent, focused);
  3943. });
  3944. };
  3945. var focusIn$1 = function (component, flowConfig) {
  3946. flowConfig.getInitial(component).orThunk(function () {
  3947. return descendant$1(component.element(), flowConfig.selector);
  3948. }).each(function (first) {
  3949. flowConfig.focusManager.set(component, first);
  3950. });
  3951. };
  3952. var moveLeft$1 = function (element, focused, info) {
  3953. return horizontal(element, info.selector, focused, -1);
  3954. };
  3955. var moveRight$1 = function (element, focused, info) {
  3956. return horizontal(element, info.selector, focused, +1);
  3957. };
  3958. var doMove$1 = function (movement) {
  3959. return function (component, simulatedEvent, flowConfig) {
  3960. return movement(component, simulatedEvent, flowConfig).bind(function () {
  3961. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  3962. });
  3963. };
  3964. };
  3965. var doEscape$1 = function (component, simulatedEvent, flowConfig, _flowState) {
  3966. return flowConfig.onEscape(component, simulatedEvent);
  3967. };
  3968. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  3969. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  3970. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  3971. return [
  3972. rule(inSet(westMovers), doMove$1(west(moveLeft$1, moveRight$1))),
  3973. rule(inSet(eastMovers), doMove$1(east(moveLeft$1, moveRight$1))),
  3974. rule(inSet(ENTER()), execute$3),
  3975. rule(inSet(SPACE()), execute$3),
  3976. rule(inSet(ESCAPE()), doEscape$1)
  3977. ];
  3978. };
  3979. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  3980. var FlowType = typical(schema$3, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  3981. return Option.some(focusIn$1);
  3982. });
  3983. var outcome = MixedBag([
  3984. 'rowIndex',
  3985. 'columnIndex',
  3986. 'cell'
  3987. ], []);
  3988. var toCell = function (matrix, rowIndex, columnIndex) {
  3989. return Option.from(matrix[rowIndex]).bind(function (row) {
  3990. return Option.from(row[columnIndex]).map(function (cell) {
  3991. return outcome({
  3992. rowIndex: rowIndex,
  3993. columnIndex: columnIndex,
  3994. cell: cell
  3995. });
  3996. });
  3997. });
  3998. };
  3999. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  4000. var row = matrix[rowIndex];
  4001. var colsInRow = row.length;
  4002. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  4003. return toCell(matrix, rowIndex, newColIndex);
  4004. };
  4005. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  4006. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  4007. var colsInNextRow = matrix[nextRowIndex].length;
  4008. var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
  4009. return toCell(matrix, nextRowIndex, nextColIndex);
  4010. };
  4011. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4012. var row = matrix[rowIndex];
  4013. var colsInRow = row.length;
  4014. var newColIndex = cap(startCol + deltaCol, 0, colsInRow - 1);
  4015. return toCell(matrix, rowIndex, newColIndex);
  4016. };
  4017. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  4018. var nextRowIndex = cap(startRow + deltaRow, 0, matrix.length - 1);
  4019. var colsInNextRow = matrix[nextRowIndex].length;
  4020. var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
  4021. return toCell(matrix, nextRowIndex, nextColIndex);
  4022. };
  4023. var cycleRight$1 = function (matrix, startRow, startCol) {
  4024. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  4025. };
  4026. var cycleLeft$1 = function (matrix, startRow, startCol) {
  4027. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  4028. };
  4029. var cycleUp$1 = function (matrix, startRow, startCol) {
  4030. return cycleVertical$1(matrix, startCol, startRow, -1);
  4031. };
  4032. var cycleDown$1 = function (matrix, startRow, startCol) {
  4033. return cycleVertical$1(matrix, startCol, startRow, +1);
  4034. };
  4035. var moveLeft$2 = function (matrix, startRow, startCol) {
  4036. return moveHorizontal(matrix, startRow, startCol, -1);
  4037. };
  4038. var moveRight$2 = function (matrix, startRow, startCol) {
  4039. return moveHorizontal(matrix, startRow, startCol, +1);
  4040. };
  4041. var moveUp = function (matrix, startRow, startCol) {
  4042. return moveVertical(matrix, startCol, startRow, -1);
  4043. };
  4044. var moveDown = function (matrix, startRow, startCol) {
  4045. return moveVertical(matrix, startCol, startRow, +1);
  4046. };
  4047. var schema$4 = [
  4048. strictObjOf('selectors', [
  4049. strict$1('row'),
  4050. strict$1('cell')
  4051. ]),
  4052. defaulted$1('cycles', true),
  4053. defaulted$1('previousSelector', Option.none),
  4054. defaulted$1('execute', defaultExecute)
  4055. ];
  4056. var focusIn$2 = function (component, matrixConfig) {
  4057. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4058. var selectors = matrixConfig.selectors;
  4059. return descendant$1(component.element(), selectors.cell);
  4060. });
  4061. focused.each(function (cell) {
  4062. matrixConfig.focusManager.set(component, cell);
  4063. });
  4064. };
  4065. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  4066. return search(component.element()).bind(function (focused) {
  4067. return matrixConfig.execute(component, simulatedEvent, focused);
  4068. });
  4069. };
  4070. var toMatrix = function (rows, matrixConfig) {
  4071. return map$1(rows, function (row) {
  4072. return descendants(row, matrixConfig.selectors.cell);
  4073. });
  4074. };
  4075. var doMove$2 = function (ifCycle, ifMove) {
  4076. return function (element, focused, matrixConfig) {
  4077. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4078. return closest$2(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4079. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4080. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  4081. var allRows = descendants(element, matrixConfig.selectors.row);
  4082. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  4083. var matrix = toMatrix(allRows, matrixConfig);
  4084. return move(matrix, rowIndex, colIndex).map(function (next) {
  4085. return next.cell();
  4086. });
  4087. });
  4088. });
  4089. });
  4090. };
  4091. };
  4092. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  4093. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  4094. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  4095. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  4096. var getKeydownRules$3 = constant([
  4097. rule(inSet(LEFT()), west(moveLeft$3, moveRight$3)),
  4098. rule(inSet(RIGHT()), east(moveLeft$3, moveRight$3)),
  4099. rule(inSet(UP()), north(moveNorth$1)),
  4100. rule(inSet(DOWN()), south(moveSouth$1)),
  4101. rule(inSet(SPACE().concat(ENTER())), execute$4)
  4102. ]);
  4103. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4104. var MatrixType = typical(schema$4, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4105. return Option.some(focusIn$2);
  4106. });
  4107. var schema$5 = [
  4108. strict$1('selector'),
  4109. defaulted$1('execute', defaultExecute),
  4110. defaulted$1('moveOnTab', false)
  4111. ];
  4112. var execute$5 = function (component, simulatedEvent, menuConfig) {
  4113. return menuConfig.focusManager.get(component).bind(function (focused) {
  4114. return menuConfig.execute(component, simulatedEvent, focused);
  4115. });
  4116. };
  4117. var focusIn$3 = function (component, menuConfig) {
  4118. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  4119. menuConfig.focusManager.set(component, first);
  4120. });
  4121. };
  4122. var moveUp$1 = function (element, focused, info) {
  4123. return horizontal(element, info.selector, focused, -1);
  4124. };
  4125. var moveDown$1 = function (element, focused, info) {
  4126. return horizontal(element, info.selector, focused, +1);
  4127. };
  4128. var fireShiftTab = function (component, simulatedEvent, menuConfig) {
  4129. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig) : Option.none();
  4130. };
  4131. var fireTab = function (component, simulatedEvent, menuConfig) {
  4132. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig) : Option.none();
  4133. };
  4134. var getKeydownRules$4 = constant([
  4135. rule(inSet(UP()), move(moveUp$1)),
  4136. rule(inSet(DOWN()), move(moveDown$1)),
  4137. rule(and([
  4138. isShift,
  4139. inSet(TAB())
  4140. ]), fireShiftTab),
  4141. rule(and([
  4142. isNotShift,
  4143. inSet(TAB())
  4144. ]), fireTab),
  4145. rule(inSet(ENTER()), execute$5),
  4146. rule(inSet(SPACE()), execute$5)
  4147. ]);
  4148. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  4149. var MenuType = typical(schema$5, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  4150. return Option.some(focusIn$3);
  4151. });
  4152. var schema$6 = [
  4153. onKeyboardHandler('onSpace'),
  4154. onKeyboardHandler('onEnter'),
  4155. onKeyboardHandler('onShiftEnter'),
  4156. onKeyboardHandler('onLeft'),
  4157. onKeyboardHandler('onRight'),
  4158. onKeyboardHandler('onTab'),
  4159. onKeyboardHandler('onShiftTab'),
  4160. onKeyboardHandler('onUp'),
  4161. onKeyboardHandler('onDown'),
  4162. onKeyboardHandler('onEscape'),
  4163. defaulted$1('stopSpaceKeyup', false),
  4164. option('focusIn')
  4165. ];
  4166. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  4167. return [
  4168. rule(inSet(SPACE()), specialInfo.onSpace),
  4169. rule(and([
  4170. isNotShift,
  4171. inSet(ENTER())
  4172. ]), specialInfo.onEnter),
  4173. rule(and([
  4174. isShift,
  4175. inSet(ENTER())
  4176. ]), specialInfo.onShiftEnter),
  4177. rule(and([
  4178. isShift,
  4179. inSet(TAB())
  4180. ]), specialInfo.onShiftTab),
  4181. rule(and([
  4182. isNotShift,
  4183. inSet(TAB())
  4184. ]), specialInfo.onTab),
  4185. rule(inSet(UP()), specialInfo.onUp),
  4186. rule(inSet(DOWN()), specialInfo.onDown),
  4187. rule(inSet(LEFT()), specialInfo.onLeft),
  4188. rule(inSet(RIGHT()), specialInfo.onRight),
  4189. rule(inSet(SPACE()), specialInfo.onSpace),
  4190. rule(inSet(ESCAPE()), specialInfo.onEscape)
  4191. ];
  4192. };
  4193. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  4194. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  4195. };
  4196. var SpecialType = typical(schema$6, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  4197. return specialInfo.focusIn;
  4198. });
  4199. var acyclic = AcyclicType.schema();
  4200. var cyclic = CyclicType.schema();
  4201. var flow = FlowType.schema();
  4202. var flatgrid$1 = FlatgridType.schema();
  4203. var matrix = MatrixType.schema();
  4204. var execution = ExecutionType.schema();
  4205. var menu = MenuType.schema();
  4206. var special = SpecialType.schema();
  4207. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4208. acyclic: acyclic,
  4209. cyclic: cyclic,
  4210. flow: flow,
  4211. flatgrid: flatgrid$1,
  4212. matrix: matrix,
  4213. execution: execution,
  4214. menu: menu,
  4215. special: special
  4216. });
  4217. var Keying = createModes$1({
  4218. branchKey: 'mode',
  4219. branches: KeyboardBranches,
  4220. name: 'keying',
  4221. active: {
  4222. events: function (keyingConfig, keyingState) {
  4223. var handler = keyingConfig.handler;
  4224. return handler.toEvents(keyingConfig, keyingState);
  4225. }
  4226. },
  4227. apis: {
  4228. focusIn: function (component, keyConfig, keyState) {
  4229. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4230. component.getSystem().triggerFocus(component.element(), component.element());
  4231. }, function (sendFocusIn) {
  4232. sendFocusIn(component, keyConfig, keyState);
  4233. });
  4234. },
  4235. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4236. if (!hasKey$1(keyState, 'setGridSize')) {
  4237. domGlobals.console.error('Layout does not support setGridSize');
  4238. } else {
  4239. keyState.setGridSize(numRows, numColumns);
  4240. }
  4241. }
  4242. },
  4243. state: KeyingState
  4244. });
  4245. var field$1 = function (name, forbidden) {
  4246. return defaultedObjOf(name, {}, map$1(forbidden, function (f) {
  4247. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4248. }).concat([state$1('dump', identity)]));
  4249. };
  4250. var get$5 = function (data) {
  4251. return data.dump;
  4252. };
  4253. var augment = function (data, original) {
  4254. return __assign(__assign({}, data.dump), derive$1(original));
  4255. };
  4256. var SketchBehaviours = {
  4257. field: field$1,
  4258. augment: augment,
  4259. get: get$5
  4260. };
  4261. var _placeholder = 'placeholder';
  4262. var adt$2 = Adt.generate([
  4263. {
  4264. single: [
  4265. 'required',
  4266. 'valueThunk'
  4267. ]
  4268. },
  4269. {
  4270. multiple: [
  4271. 'required',
  4272. 'valueThunks'
  4273. ]
  4274. }
  4275. ]);
  4276. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4277. if (owner.exists(function (o) {
  4278. return o !== compSpec.owner;
  4279. })) {
  4280. return adt$2.single(true, constant(compSpec));
  4281. }
  4282. return readOptFrom$1(placeholders, compSpec.name).fold(function () {
  4283. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4284. }, function (newSpec) {
  4285. return newSpec.replace();
  4286. });
  4287. };
  4288. var scan = function (owner, detail, compSpec, placeholders) {
  4289. if (compSpec.uiType === _placeholder) {
  4290. return subPlaceholder(owner, detail, compSpec, placeholders);
  4291. } else {
  4292. return adt$2.single(false, constant(compSpec));
  4293. }
  4294. };
  4295. var substitute = function (owner, detail, compSpec, placeholders) {
  4296. var base = scan(owner, detail, compSpec, placeholders);
  4297. return base.fold(function (req, valueThunk) {
  4298. var value = valueThunk(detail, compSpec.config, compSpec.validated);
  4299. var childSpecs = readOptFrom$1(value, 'components').getOr([]);
  4300. var substituted = bind(childSpecs, function (c) {
  4301. return substitute(owner, detail, c, placeholders);
  4302. });
  4303. return [__assign(__assign({}, value), { components: substituted })];
  4304. }, function (req, valuesThunk) {
  4305. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4306. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4307. return preprocessor(values);
  4308. });
  4309. };
  4310. var substituteAll = function (owner, detail, components, placeholders) {
  4311. return bind(components, function (c) {
  4312. return substitute(owner, detail, c, placeholders);
  4313. });
  4314. };
  4315. var oneReplace = function (label, replacements) {
  4316. var called = false;
  4317. var used = function () {
  4318. return called;
  4319. };
  4320. var replace = function () {
  4321. if (called === true) {
  4322. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4323. }
  4324. called = true;
  4325. return replacements;
  4326. };
  4327. var required = function () {
  4328. return replacements.fold(function (req, _) {
  4329. return req;
  4330. }, function (req, _) {
  4331. return req;
  4332. });
  4333. };
  4334. return {
  4335. name: constant(label),
  4336. required: required,
  4337. used: used,
  4338. replace: replace
  4339. };
  4340. };
  4341. var substitutePlaces = function (owner, detail, components, placeholders) {
  4342. var ps = map(placeholders, function (ph, name) {
  4343. return oneReplace(name, ph);
  4344. });
  4345. var outcome = substituteAll(owner, detail, components, ps);
  4346. each(ps, function (p) {
  4347. if (p.used() === false && p.required()) {
  4348. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4349. }
  4350. });
  4351. return outcome;
  4352. };
  4353. var single = adt$2.single;
  4354. var multiple = adt$2.multiple;
  4355. var placeholder = constant(_placeholder);
  4356. var unique = 0;
  4357. var generate$1 = function (prefix) {
  4358. var date = new Date();
  4359. var time = date.getTime();
  4360. var random = Math.floor(Math.random() * 1000000000);
  4361. unique++;
  4362. return prefix + '_' + random + unique + String(time);
  4363. };
  4364. var adt$3 = Adt.generate([
  4365. { required: ['data'] },
  4366. { external: ['data'] },
  4367. { optional: ['data'] },
  4368. { group: ['data'] }
  4369. ]);
  4370. var fFactory = defaulted$1('factory', { sketch: identity });
  4371. var fSchema = defaulted$1('schema', []);
  4372. var fName = strict$1('name');
  4373. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  4374. return '<alloy.' + generate$1(typeSpec.name) + '>';
  4375. }), anyValue$1());
  4376. var fGroupSchema = state$1('schema', function () {
  4377. return [option('preprocess')];
  4378. });
  4379. var fDefaults = defaulted$1('defaults', constant({}));
  4380. var fOverrides = defaulted$1('overrides', constant({}));
  4381. var requiredSpec = objOf([
  4382. fFactory,
  4383. fSchema,
  4384. fName,
  4385. fPname,
  4386. fDefaults,
  4387. fOverrides
  4388. ]);
  4389. var optionalSpec = objOf([
  4390. fFactory,
  4391. fSchema,
  4392. fName,
  4393. fPname,
  4394. fDefaults,
  4395. fOverrides
  4396. ]);
  4397. var groupSpec = objOf([
  4398. fFactory,
  4399. fGroupSchema,
  4400. fName,
  4401. strict$1('unit'),
  4402. fPname,
  4403. fDefaults,
  4404. fOverrides
  4405. ]);
  4406. var asNamedPart = function (part) {
  4407. return part.fold(Option.some, Option.none, Option.some, Option.some);
  4408. };
  4409. var name$1 = function (part) {
  4410. var get = function (data) {
  4411. return data.name;
  4412. };
  4413. return part.fold(get, get, get, get);
  4414. };
  4415. var convert = function (adtConstructor, partSchema) {
  4416. return function (spec) {
  4417. var data = asRawOrDie('Converting part type', partSchema, spec);
  4418. return adtConstructor(data);
  4419. };
  4420. };
  4421. var required = convert(adt$3.required, requiredSpec);
  4422. var optional = convert(adt$3.optional, optionalSpec);
  4423. var group = convert(adt$3.group, groupSpec);
  4424. var original = constant('entirety');
  4425. var combine = function (detail, data, partSpec, partValidated) {
  4426. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4427. };
  4428. var subs = function (owner, detail, parts) {
  4429. var internals = {};
  4430. var externals = {};
  4431. each$1(parts, function (part) {
  4432. part.fold(function (data) {
  4433. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  4434. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4435. });
  4436. }, function (data) {
  4437. var partSpec = detail.parts[data.name];
  4438. externals[data.name] = constant(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  4439. }, function (data) {
  4440. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  4441. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  4442. });
  4443. }, function (data) {
  4444. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4445. var units = detail[data.name];
  4446. return map$1(units, function (u) {
  4447. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4448. });
  4449. });
  4450. });
  4451. });
  4452. return {
  4453. internals: constant(internals),
  4454. externals: constant(externals)
  4455. };
  4456. };
  4457. var generate$2 = function (owner, parts) {
  4458. var r = {};
  4459. each$1(parts, function (part) {
  4460. asNamedPart(part).each(function (np) {
  4461. var g = doGenerateOne(owner, np.pname);
  4462. r[np.name] = function (config) {
  4463. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4464. return __assign(__assign({}, g), {
  4465. config: config,
  4466. validated: validated
  4467. });
  4468. };
  4469. });
  4470. });
  4471. return r;
  4472. };
  4473. var doGenerateOne = function (owner, pname) {
  4474. return {
  4475. uiType: placeholder(),
  4476. owner: owner,
  4477. name: pname
  4478. };
  4479. };
  4480. var generateOne = function (owner, pname, config) {
  4481. return {
  4482. uiType: placeholder(),
  4483. owner: owner,
  4484. name: pname,
  4485. config: config,
  4486. validated: {}
  4487. };
  4488. };
  4489. var schemas = function (parts) {
  4490. return bind(parts, function (part) {
  4491. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  4492. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  4493. }).toArray();
  4494. });
  4495. };
  4496. var names = function (parts) {
  4497. return map$1(parts, name$1);
  4498. };
  4499. var substitutes = function (owner, detail, parts) {
  4500. return subs(owner, detail, parts);
  4501. };
  4502. var components = function (owner, detail, internals) {
  4503. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  4504. };
  4505. var getPart = function (component, detail, partKey) {
  4506. var uid = detail.partUids[partKey];
  4507. return component.getSystem().getByUid(uid).toOption();
  4508. };
  4509. var getPartOrDie = function (component, detail, partKey) {
  4510. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4511. };
  4512. var getAllParts = function (component, detail) {
  4513. var system = component.getSystem();
  4514. return map(detail.partUids, function (pUid, k) {
  4515. return constant(system.getByUid(pUid));
  4516. });
  4517. };
  4518. var defaultUids = function (baseUid, partTypes) {
  4519. var partNames = names(partTypes);
  4520. return wrapAll$1(map$1(partNames, function (pn) {
  4521. return {
  4522. key: pn,
  4523. value: baseUid + '-' + pn
  4524. };
  4525. }));
  4526. };
  4527. var defaultUidsSchema = function (partTypes) {
  4528. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  4529. return defaultUids(spec.uid, partTypes);
  4530. }), anyValue$1());
  4531. };
  4532. var premadeTag = generate$1('alloy-premade');
  4533. var premade = function (comp) {
  4534. return wrap$1(premadeTag, comp);
  4535. };
  4536. var getPremade = function (spec) {
  4537. return readOptFrom$1(spec, premadeTag);
  4538. };
  4539. var makeApi = function (f) {
  4540. return markAsSketchApi(function (component) {
  4541. var rest = [];
  4542. for (var _i = 1; _i < arguments.length; _i++) {
  4543. rest[_i - 1] = arguments[_i];
  4544. }
  4545. return f.apply(undefined, [component.getApis()].concat([component].concat(rest)));
  4546. }, f);
  4547. };
  4548. var prefix$1 = constant('alloy-id-');
  4549. var idAttr = constant('data-alloy-id');
  4550. var prefix$2 = prefix$1();
  4551. var idAttr$1 = idAttr();
  4552. var write = function (label, elem) {
  4553. var id = generate$1(prefix$2 + label);
  4554. writeOnly(elem, id);
  4555. return id;
  4556. };
  4557. var writeOnly = function (elem, uid) {
  4558. Object.defineProperty(elem.dom(), idAttr$1, {
  4559. value: uid,
  4560. writable: true
  4561. });
  4562. };
  4563. var read$2 = function (elem) {
  4564. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  4565. return Option.from(id);
  4566. };
  4567. var generate$3 = function (prefix) {
  4568. return generate$1(prefix);
  4569. };
  4570. var base = function (partSchemas, partUidsSchemas) {
  4571. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  4572. return ps.concat([
  4573. strict$1('uid'),
  4574. defaulted$1('dom', {}),
  4575. defaulted$1('components', []),
  4576. snapshot('originalSpec'),
  4577. defaulted$1('debug.sketcher', {})
  4578. ]).concat(partUidsSchemas);
  4579. };
  4580. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4581. var baseS = base(partSchemas, partUidsSchemas);
  4582. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4583. };
  4584. var single$1 = function (owner, schema, factory, spec) {
  4585. var specWithUid = supplyUid(spec);
  4586. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  4587. return factory(detail, specWithUid);
  4588. };
  4589. var composite = function (owner, schema, partTypes, factory, spec) {
  4590. var specWithUid = supplyUid(spec);
  4591. var partSchemas = schemas(partTypes);
  4592. var partUidsSchema = defaultUidsSchema(partTypes);
  4593. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4594. var subs = substitutes(owner, detail, partTypes);
  4595. var components$1 = components(owner, detail, subs.internals());
  4596. return factory(detail, components$1, specWithUid, subs.externals());
  4597. };
  4598. var supplyUid = function (spec) {
  4599. return spec.hasOwnProperty('uid') ? spec : __assign(__assign({}, spec), { uid: generate$3('uid') });
  4600. };
  4601. function isSketchSpec(spec) {
  4602. return spec.uid !== undefined;
  4603. }
  4604. var singleSchema = objOfOnly([
  4605. strict$1('name'),
  4606. strict$1('factory'),
  4607. strict$1('configFields'),
  4608. defaulted$1('apis', {}),
  4609. defaulted$1('extraApis', {})
  4610. ]);
  4611. var compositeSchema = objOfOnly([
  4612. strict$1('name'),
  4613. strict$1('factory'),
  4614. strict$1('configFields'),
  4615. strict$1('partFields'),
  4616. defaulted$1('apis', {}),
  4617. defaulted$1('extraApis', {})
  4618. ]);
  4619. var single$2 = function (rawConfig) {
  4620. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4621. var sketch = function (spec) {
  4622. return single$1(config.name, config.configFields, config.factory, spec);
  4623. };
  4624. var apis = map(config.apis, makeApi);
  4625. var extraApis = map(config.extraApis, function (f, k) {
  4626. return markAsExtraApi(f, k);
  4627. });
  4628. return __assign(__assign({
  4629. name: constant(config.name),
  4630. partFields: constant([]),
  4631. configFields: constant(config.configFields),
  4632. sketch: sketch
  4633. }, apis), extraApis);
  4634. };
  4635. var composite$1 = function (rawConfig) {
  4636. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4637. var sketch = function (spec) {
  4638. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  4639. };
  4640. var parts = generate$2(config.name, config.partFields);
  4641. var apis = map(config.apis, makeApi);
  4642. var extraApis = map(config.extraApis, function (f, k) {
  4643. return markAsExtraApi(f, k);
  4644. });
  4645. return __assign(__assign({
  4646. name: constant(config.name),
  4647. partFields: constant(config.partFields),
  4648. configFields: constant(config.configFields),
  4649. sketch: sketch,
  4650. parts: constant(parts)
  4651. }, apis), extraApis);
  4652. };
  4653. var factory = function (detail) {
  4654. var events = events$2(detail.action);
  4655. var tag = detail.dom.tag;
  4656. var lookupAttr = function (attr) {
  4657. return readOptFrom$1(detail.dom, 'attributes').bind(function (attrs) {
  4658. return readOptFrom$1(attrs, attr);
  4659. });
  4660. };
  4661. var getModAttributes = function () {
  4662. if (tag === 'button') {
  4663. var type = lookupAttr('type').getOr('button');
  4664. var roleAttrs = lookupAttr('role').map(function (role) {
  4665. return { role: role };
  4666. }).getOr({});
  4667. return __assign({ type: type }, roleAttrs);
  4668. } else {
  4669. var role = lookupAttr('role').getOr('button');
  4670. return { role: role };
  4671. }
  4672. };
  4673. return {
  4674. uid: detail.uid,
  4675. dom: detail.dom,
  4676. components: detail.components,
  4677. events: events,
  4678. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4679. Focusing.config({}),
  4680. Keying.config({
  4681. mode: 'execution',
  4682. useSpace: true,
  4683. useEnter: true
  4684. })
  4685. ]),
  4686. domModification: { attributes: getModAttributes() },
  4687. eventOrder: detail.eventOrder
  4688. };
  4689. };
  4690. var Button = single$2({
  4691. name: 'Button',
  4692. factory: factory,
  4693. configFields: [
  4694. defaulted$1('uid', undefined),
  4695. strict$1('dom'),
  4696. defaulted$1('components', []),
  4697. SketchBehaviours.field('buttonBehaviours', [
  4698. Focusing,
  4699. Keying
  4700. ]),
  4701. option('action'),
  4702. option('role'),
  4703. defaulted$1('eventOrder', {})
  4704. ]
  4705. });
  4706. var exhibit$2 = function (base, unselectConfig) {
  4707. return nu$5({
  4708. styles: {
  4709. '-webkit-user-select': 'none',
  4710. 'user-select': 'none',
  4711. '-ms-user-select': 'none',
  4712. '-moz-user-select': '-moz-none'
  4713. },
  4714. attributes: { unselectable: 'on' }
  4715. });
  4716. };
  4717. var events$4 = function (unselectConfig) {
  4718. return derive([abort(selectstart(), constant(true))]);
  4719. };
  4720. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4721. events: events$4,
  4722. exhibit: exhibit$2
  4723. });
  4724. var Unselecting = create$1({
  4725. fields: [],
  4726. name: 'unselecting',
  4727. active: ActiveUnselecting
  4728. });
  4729. var getAttrs = function (elem) {
  4730. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  4731. return foldl(attributes, function (b, attr) {
  4732. var _a;
  4733. if (attr.name === 'class') {
  4734. return b;
  4735. } else {
  4736. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4737. }
  4738. }, {});
  4739. };
  4740. var getClasses = function (elem) {
  4741. return Array.prototype.slice.call(elem.dom().classList, 0);
  4742. };
  4743. var fromHtml$2 = function (html) {
  4744. var elem = Element.fromHtml(html);
  4745. var children$1 = children(elem);
  4746. var attrs = getAttrs(elem);
  4747. var classes = getClasses(elem);
  4748. var contents = children$1.length === 0 ? {} : { innerHtml: get$2(elem) };
  4749. return __assign({
  4750. tag: name(elem),
  4751. classes: classes,
  4752. attributes: attrs
  4753. }, contents);
  4754. };
  4755. var dom$1 = function (rawHtml) {
  4756. var html = supplant(rawHtml, { prefix: Styles.prefix() });
  4757. return fromHtml$2(html);
  4758. };
  4759. var spec = function (rawHtml) {
  4760. var sDom = dom$1(rawHtml);
  4761. return { dom: sDom };
  4762. };
  4763. var forToolbarCommand = function (editor, command) {
  4764. return forToolbar(command, function () {
  4765. editor.execCommand(command);
  4766. }, {}, editor);
  4767. };
  4768. var getToggleBehaviours = function (command) {
  4769. return derive$1([
  4770. Toggling.config({
  4771. toggleClass: Styles.resolve('toolbar-button-selected'),
  4772. toggleOnExecute: false,
  4773. aria: { mode: 'pressed' }
  4774. }),
  4775. Receivers.format(command, function (button, status) {
  4776. var toggle = status ? Toggling.on : Toggling.off;
  4777. toggle(button);
  4778. })
  4779. ]);
  4780. };
  4781. var forToolbarStateCommand = function (editor, command) {
  4782. var extraBehaviours = getToggleBehaviours(command);
  4783. return forToolbar(command, function () {
  4784. editor.execCommand(command);
  4785. }, extraBehaviours, editor);
  4786. };
  4787. var forToolbarStateAction = function (editor, clazz, command, action) {
  4788. var extraBehaviours = getToggleBehaviours(command);
  4789. return forToolbar(clazz, action, extraBehaviours, editor);
  4790. };
  4791. var getToolbarIconButton = function (clazz, editor) {
  4792. var icons = editor.ui.registry.getAll().icons;
  4793. var optOxideIcon = Option.from(icons[clazz]);
  4794. return optOxideIcon.fold(function () {
  4795. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4796. }, function (icon) {
  4797. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4798. });
  4799. };
  4800. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4801. return Button.sketch({
  4802. dom: getToolbarIconButton(clazz, editor),
  4803. action: action,
  4804. buttonBehaviours: deepMerge(derive$1([Unselecting.config({})]), extraBehaviours)
  4805. });
  4806. };
  4807. var Buttons = {
  4808. forToolbar: forToolbar,
  4809. forToolbarCommand: forToolbarCommand,
  4810. forToolbarStateAction: forToolbarStateAction,
  4811. forToolbarStateCommand: forToolbarStateCommand,
  4812. getToolbarIconButton: getToolbarIconButton
  4813. };
  4814. var platform$1 = detect$3();
  4815. var isTouch = platform$1.deviceType.isTouch();
  4816. var labelPart = optional({
  4817. schema: [strict$1('dom')],
  4818. name: 'label'
  4819. });
  4820. var edgePart = function (name) {
  4821. return optional({
  4822. name: '' + name + '-edge',
  4823. overrides: function (detail) {
  4824. var action = detail.model.manager.edgeActions[name];
  4825. return action.fold(function () {
  4826. return {};
  4827. }, function (a) {
  4828. var touchEvents = derive([runActionExtra(touchstart(), a, [detail])]);
  4829. var mouseEvents = derive([
  4830. runActionExtra(mousedown(), a, [detail]),
  4831. runActionExtra(mousemove(), function (l, det) {
  4832. if (det.mouseIsDown.get()) {
  4833. a(l, det);
  4834. }
  4835. }, [detail])
  4836. ]);
  4837. return { events: isTouch ? touchEvents : mouseEvents };
  4838. });
  4839. }
  4840. });
  4841. };
  4842. var tlEdgePart = edgePart('top-left');
  4843. var tedgePart = edgePart('top');
  4844. var trEdgePart = edgePart('top-right');
  4845. var redgePart = edgePart('right');
  4846. var brEdgePart = edgePart('bottom-right');
  4847. var bedgePart = edgePart('bottom');
  4848. var blEdgePart = edgePart('bottom-left');
  4849. var ledgePart = edgePart('left');
  4850. var thumbPart = required({
  4851. name: 'thumb',
  4852. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  4853. overrides: function (detail) {
  4854. return {
  4855. events: derive([
  4856. redirectToPart(touchstart(), detail, 'spectrum'),
  4857. redirectToPart(touchmove(), detail, 'spectrum'),
  4858. redirectToPart(touchend(), detail, 'spectrum'),
  4859. redirectToPart(mousedown(), detail, 'spectrum'),
  4860. redirectToPart(mousemove(), detail, 'spectrum'),
  4861. redirectToPart(mouseup(), detail, 'spectrum')
  4862. ])
  4863. };
  4864. }
  4865. });
  4866. var spectrumPart = required({
  4867. schema: [state$1('mouseIsDown', function () {
  4868. return Cell(false);
  4869. })],
  4870. name: 'spectrum',
  4871. overrides: function (detail) {
  4872. var modelDetail = detail.model;
  4873. var model = modelDetail.manager;
  4874. var setValueFrom = function (component, simulatedEvent) {
  4875. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  4876. return model.setValueFrom(component, detail, value);
  4877. });
  4878. };
  4879. var touchEvents = derive([
  4880. run(touchstart(), setValueFrom),
  4881. run(touchmove(), setValueFrom)
  4882. ]);
  4883. var mouseEvents = derive([
  4884. run(mousedown(), setValueFrom),
  4885. run(mousemove(), function (spectrum, se) {
  4886. if (detail.mouseIsDown.get()) {
  4887. setValueFrom(spectrum, se);
  4888. }
  4889. })
  4890. ]);
  4891. return {
  4892. behaviours: derive$1(isTouch ? [] : [
  4893. Keying.config({
  4894. mode: 'special',
  4895. onLeft: function (spectrum) {
  4896. return model.onLeft(spectrum, detail);
  4897. },
  4898. onRight: function (spectrum) {
  4899. return model.onRight(spectrum, detail);
  4900. },
  4901. onUp: function (spectrum) {
  4902. return model.onUp(spectrum, detail);
  4903. },
  4904. onDown: function (spectrum) {
  4905. return model.onDown(spectrum, detail);
  4906. }
  4907. }),
  4908. Focusing.config({})
  4909. ]),
  4910. events: isTouch ? touchEvents : mouseEvents
  4911. };
  4912. }
  4913. });
  4914. var SliderParts = [
  4915. labelPart,
  4916. ledgePart,
  4917. redgePart,
  4918. tedgePart,
  4919. bedgePart,
  4920. tlEdgePart,
  4921. trEdgePart,
  4922. blEdgePart,
  4923. brEdgePart,
  4924. thumbPart,
  4925. spectrumPart
  4926. ];
  4927. var onLoad$1 = function (component, repConfig, repState) {
  4928. repConfig.store.manager.onLoad(component, repConfig, repState);
  4929. };
  4930. var onUnload = function (component, repConfig, repState) {
  4931. repConfig.store.manager.onUnload(component, repConfig, repState);
  4932. };
  4933. var setValue = function (component, repConfig, repState, data) {
  4934. repConfig.store.manager.setValue(component, repConfig, repState, data);
  4935. };
  4936. var getValue = function (component, repConfig, repState) {
  4937. return repConfig.store.manager.getValue(component, repConfig, repState);
  4938. };
  4939. var getState = function (component, repConfig, repState) {
  4940. return repState;
  4941. };
  4942. var RepresentApis = /*#__PURE__*/Object.freeze({
  4943. onLoad: onLoad$1,
  4944. onUnload: onUnload,
  4945. setValue: setValue,
  4946. getValue: getValue,
  4947. getState: getState
  4948. });
  4949. var events$5 = function (repConfig, repState) {
  4950. var es = repConfig.resetOnDom ? [
  4951. runOnAttached(function (comp, se) {
  4952. onLoad$1(comp, repConfig, repState);
  4953. }),
  4954. runOnDetached(function (comp, se) {
  4955. onUnload(comp, repConfig, repState);
  4956. })
  4957. ] : [loadEvent(repConfig, repState, onLoad$1)];
  4958. return derive(es);
  4959. };
  4960. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  4961. events: events$5
  4962. });
  4963. var memory = function () {
  4964. var data = Cell(null);
  4965. var readState = function () {
  4966. return {
  4967. mode: 'memory',
  4968. value: data.get()
  4969. };
  4970. };
  4971. var isNotSet = function () {
  4972. return data.get() === null;
  4973. };
  4974. var clear = function () {
  4975. data.set(null);
  4976. };
  4977. return nu$6({
  4978. set: data.set,
  4979. get: data.get,
  4980. isNotSet: isNotSet,
  4981. clear: clear,
  4982. readState: readState
  4983. });
  4984. };
  4985. var manual = function () {
  4986. var readState = function () {
  4987. };
  4988. return nu$6({ readState: readState });
  4989. };
  4990. var dataset = function () {
  4991. var dataByValue = Cell({});
  4992. var dataByText = Cell({});
  4993. var readState = function () {
  4994. return {
  4995. mode: 'dataset',
  4996. dataByValue: dataByValue.get(),
  4997. dataByText: dataByText.get()
  4998. };
  4999. };
  5000. var clear = function () {
  5001. dataByValue.set({});
  5002. dataByText.set({});
  5003. };
  5004. var lookup = function (itemString) {
  5005. return readOptFrom$1(dataByValue.get(), itemString).orThunk(function () {
  5006. return readOptFrom$1(dataByText.get(), itemString);
  5007. });
  5008. };
  5009. var update = function (items) {
  5010. var currentDataByValue = dataByValue.get();
  5011. var currentDataByText = dataByText.get();
  5012. var newDataByValue = {};
  5013. var newDataByText = {};
  5014. each$1(items, function (item) {
  5015. newDataByValue[item.value] = item;
  5016. readOptFrom$1(item, 'meta').each(function (meta) {
  5017. readOptFrom$1(meta, 'text').each(function (text) {
  5018. newDataByText[text] = item;
  5019. });
  5020. });
  5021. });
  5022. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5023. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5024. };
  5025. return nu$6({
  5026. readState: readState,
  5027. lookup: lookup,
  5028. update: update,
  5029. clear: clear
  5030. });
  5031. };
  5032. var init$1 = function (spec) {
  5033. return spec.store.manager.state(spec);
  5034. };
  5035. var RepresentState = /*#__PURE__*/Object.freeze({
  5036. memory: memory,
  5037. dataset: dataset,
  5038. manual: manual,
  5039. init: init$1
  5040. });
  5041. var setValue$1 = function (component, repConfig, repState, data) {
  5042. var store = repConfig.store;
  5043. repState.update([data]);
  5044. store.setValue(component, data);
  5045. repConfig.onSetValue(component, data);
  5046. };
  5047. var getValue$1 = function (component, repConfig, repState) {
  5048. var store = repConfig.store;
  5049. var key = store.getDataKey(component);
  5050. return repState.lookup(key).fold(function () {
  5051. return store.getFallbackEntry(key);
  5052. }, function (data) {
  5053. return data;
  5054. });
  5055. };
  5056. var onLoad$2 = function (component, repConfig, repState) {
  5057. var store = repConfig.store;
  5058. store.initialValue.each(function (data) {
  5059. setValue$1(component, repConfig, repState, data);
  5060. });
  5061. };
  5062. var onUnload$1 = function (component, repConfig, repState) {
  5063. repState.clear();
  5064. };
  5065. var DatasetStore = [
  5066. option('initialValue'),
  5067. strict$1('getFallbackEntry'),
  5068. strict$1('getDataKey'),
  5069. strict$1('setValue'),
  5070. output('manager', {
  5071. setValue: setValue$1,
  5072. getValue: getValue$1,
  5073. onLoad: onLoad$2,
  5074. onUnload: onUnload$1,
  5075. state: dataset
  5076. })
  5077. ];
  5078. var getValue$2 = function (component, repConfig, repState) {
  5079. return repConfig.store.getValue(component);
  5080. };
  5081. var setValue$2 = function (component, repConfig, repState, data) {
  5082. repConfig.store.setValue(component, data);
  5083. repConfig.onSetValue(component, data);
  5084. };
  5085. var onLoad$3 = function (component, repConfig, repState) {
  5086. repConfig.store.initialValue.each(function (data) {
  5087. repConfig.store.setValue(component, data);
  5088. });
  5089. };
  5090. var ManualStore = [
  5091. strict$1('getValue'),
  5092. defaulted$1('setValue', noop),
  5093. option('initialValue'),
  5094. output('manager', {
  5095. setValue: setValue$2,
  5096. getValue: getValue$2,
  5097. onLoad: onLoad$3,
  5098. onUnload: noop,
  5099. state: NoState.init
  5100. })
  5101. ];
  5102. var setValue$3 = function (component, repConfig, repState, data) {
  5103. repState.set(data);
  5104. repConfig.onSetValue(component, data);
  5105. };
  5106. var getValue$3 = function (component, repConfig, repState) {
  5107. return repState.get();
  5108. };
  5109. var onLoad$4 = function (component, repConfig, repState) {
  5110. repConfig.store.initialValue.each(function (initVal) {
  5111. if (repState.isNotSet()) {
  5112. repState.set(initVal);
  5113. }
  5114. });
  5115. };
  5116. var onUnload$2 = function (component, repConfig, repState) {
  5117. repState.clear();
  5118. };
  5119. var MemoryStore = [
  5120. option('initialValue'),
  5121. output('manager', {
  5122. setValue: setValue$3,
  5123. getValue: getValue$3,
  5124. onLoad: onLoad$4,
  5125. onUnload: onUnload$2,
  5126. state: memory
  5127. })
  5128. ];
  5129. var RepresentSchema = [
  5130. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5131. memory: MemoryStore,
  5132. manual: ManualStore,
  5133. dataset: DatasetStore
  5134. })),
  5135. onHandler('onSetValue'),
  5136. defaulted$1('resetOnDom', false)
  5137. ];
  5138. var Representing = create$1({
  5139. fields: RepresentSchema,
  5140. name: 'representing',
  5141. active: ActiveRepresenting,
  5142. apis: RepresentApis,
  5143. extra: {
  5144. setValueFrom: function (component, source) {
  5145. var value = Representing.getValue(source);
  5146. Representing.setValue(component, value);
  5147. }
  5148. },
  5149. state: RepresentState
  5150. });
  5151. var api$1 = Dimension('width', function (element) {
  5152. return element.dom().offsetWidth;
  5153. });
  5154. var set$4 = function (element, h) {
  5155. api$1.set(element, h);
  5156. };
  5157. var get$6 = function (element) {
  5158. return api$1.get(element);
  5159. };
  5160. var r = function (left, top) {
  5161. var translate = function (x, y) {
  5162. return r(left + x, top + y);
  5163. };
  5164. return {
  5165. left: constant(left),
  5166. top: constant(top),
  5167. translate: translate
  5168. };
  5169. };
  5170. var Position = r;
  5171. var isTouch$1 = detect$3().deviceType.isTouch();
  5172. var _sliderChangeEvent = 'slider.change.value';
  5173. var sliderChangeEvent = constant(_sliderChangeEvent);
  5174. var getEventSource = function (simulatedEvent) {
  5175. var evt = simulatedEvent.event().raw();
  5176. if (isTouch$1) {
  5177. var touchEvent = evt;
  5178. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  5179. return Position(t.clientX, t.clientY);
  5180. }) : Option.none();
  5181. } else {
  5182. var mouseEvent = evt;
  5183. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  5184. return Position(me.clientX, me.clientY);
  5185. }) : Option.none();
  5186. }
  5187. };
  5188. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  5189. var minX = function (detail) {
  5190. return detail.model.minX;
  5191. };
  5192. var minY = function (detail) {
  5193. return detail.model.minY;
  5194. };
  5195. var min1X = function (detail) {
  5196. return detail.model.minX - 1;
  5197. };
  5198. var min1Y = function (detail) {
  5199. return detail.model.minY - 1;
  5200. };
  5201. var maxX = function (detail) {
  5202. return detail.model.maxX;
  5203. };
  5204. var maxY = function (detail) {
  5205. return detail.model.maxY;
  5206. };
  5207. var max1X = function (detail) {
  5208. return detail.model.maxX + 1;
  5209. };
  5210. var max1Y = function (detail) {
  5211. return detail.model.maxY + 1;
  5212. };
  5213. var range = function (detail, max, min) {
  5214. return max(detail) - min(detail);
  5215. };
  5216. var xRange = function (detail) {
  5217. return range(detail, maxX, minX);
  5218. };
  5219. var yRange = function (detail) {
  5220. return range(detail, maxY, minY);
  5221. };
  5222. var halfX = function (detail) {
  5223. return xRange(detail) / 2;
  5224. };
  5225. var halfY = function (detail) {
  5226. return yRange(detail) / 2;
  5227. };
  5228. var step = function (detail) {
  5229. return detail.stepSize;
  5230. };
  5231. var snap = function (detail) {
  5232. return detail.snapToGrid;
  5233. };
  5234. var snapStart = function (detail) {
  5235. return detail.snapStart;
  5236. };
  5237. var rounded = function (detail) {
  5238. return detail.rounded;
  5239. };
  5240. var hasEdge = function (detail, edgeName) {
  5241. return detail[edgeName + '-edge'] !== undefined;
  5242. };
  5243. var hasLEdge = function (detail) {
  5244. return hasEdge(detail, l);
  5245. };
  5246. var hasREdge = function (detail) {
  5247. return hasEdge(detail, r$1);
  5248. };
  5249. var hasTEdge = function (detail) {
  5250. return hasEdge(detail, t);
  5251. };
  5252. var hasBEdge = function (detail) {
  5253. return hasEdge(detail, b);
  5254. };
  5255. var currentValue = function (detail) {
  5256. return detail.model.value.get();
  5257. };
  5258. var xValue = function (x) {
  5259. return { x: constant(x) };
  5260. };
  5261. var yValue = function (y) {
  5262. return { y: constant(y) };
  5263. };
  5264. var xyValue = function (x, y) {
  5265. return {
  5266. x: constant(x),
  5267. y: constant(y)
  5268. };
  5269. };
  5270. var fireSliderChange = function (component, value) {
  5271. emitWith(component, sliderChangeEvent(), { value: value });
  5272. };
  5273. var setToTLEdgeXY = function (edge, detail) {
  5274. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  5275. };
  5276. var setToTEdge = function (edge, detail) {
  5277. fireSliderChange(edge, yValue(min1Y(detail)));
  5278. };
  5279. var setToTEdgeXY = function (edge, detail) {
  5280. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  5281. };
  5282. var setToTREdgeXY = function (edge, detail) {
  5283. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  5284. };
  5285. var setToREdge = function (edge, detail) {
  5286. fireSliderChange(edge, xValue(max1X(detail)));
  5287. };
  5288. var setToREdgeXY = function (edge, detail) {
  5289. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  5290. };
  5291. var setToBREdgeXY = function (edge, detail) {
  5292. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  5293. };
  5294. var setToBEdge = function (edge, detail) {
  5295. fireSliderChange(edge, yValue(max1Y(detail)));
  5296. };
  5297. var setToBEdgeXY = function (edge, detail) {
  5298. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  5299. };
  5300. var setToBLEdgeXY = function (edge, detail) {
  5301. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  5302. };
  5303. var setToLEdge = function (edge, detail) {
  5304. fireSliderChange(edge, xValue(min1X(detail)));
  5305. };
  5306. var setToLEdgeXY = function (edge, detail) {
  5307. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  5308. };
  5309. var reduceBy = function (value, min, max, step) {
  5310. if (value < min) {
  5311. return value;
  5312. } else if (value > max) {
  5313. return max;
  5314. } else if (value === min) {
  5315. return min - 1;
  5316. } else {
  5317. return Math.max(min, value - step);
  5318. }
  5319. };
  5320. var increaseBy = function (value, min, max, step) {
  5321. if (value > max) {
  5322. return value;
  5323. } else if (value < min) {
  5324. return min;
  5325. } else if (value === max) {
  5326. return max + 1;
  5327. } else {
  5328. return Math.min(max, value + step);
  5329. }
  5330. };
  5331. var capValue = function (value, min, max) {
  5332. return Math.max(min, Math.min(max, value));
  5333. };
  5334. var snapValueOf = function (value, min, max, step, snapStart) {
  5335. return snapStart.fold(function () {
  5336. var initValue = value - min;
  5337. var extraValue = Math.round(initValue / step) * step;
  5338. return capValue(min + extraValue, min - 1, max + 1);
  5339. }, function (start) {
  5340. var remainder = (value - start) % step;
  5341. var adjustment = Math.round(remainder / step);
  5342. var rawSteps = Math.floor((value - start) / step);
  5343. var maxSteps = Math.floor((max - start) / step);
  5344. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5345. var r = start + numSteps * step;
  5346. return Math.max(start, r);
  5347. });
  5348. };
  5349. var findOffsetOf = function (value, min, max) {
  5350. return Math.min(max, Math.max(value, min)) - min;
  5351. };
  5352. var findValueOf = function (args) {
  5353. 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;
  5354. var capMin = hasMinEdge ? min - 1 : min;
  5355. var capMax = hasMaxEdge ? max + 1 : max;
  5356. if (value < minBound) {
  5357. return capMin;
  5358. } else if (value > maxBound) {
  5359. return capMax;
  5360. } else {
  5361. var offset = findOffsetOf(value, minBound, maxBound);
  5362. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5363. if (snap && newValue >= min && newValue <= max) {
  5364. return snapValueOf(newValue, min, max, step, snapStart);
  5365. } else if (rounded) {
  5366. return Math.round(newValue);
  5367. } else {
  5368. return newValue;
  5369. }
  5370. }
  5371. };
  5372. var findOffsetOfValue = function (args) {
  5373. 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;
  5374. if (value < min) {
  5375. return hasMinEdge ? 0 : centerMinEdge;
  5376. } else if (value > max) {
  5377. return hasMaxEdge ? maxBound : centerMaxEdge;
  5378. } else {
  5379. return (value - min) / range * maxOffset;
  5380. }
  5381. };
  5382. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5383. var getBounds = function (component) {
  5384. return component.element().dom().getBoundingClientRect();
  5385. };
  5386. var getBoundsProperty = function (bounds, property) {
  5387. return bounds[property];
  5388. };
  5389. var getMinXBounds = function (component) {
  5390. var bounds = getBounds(component);
  5391. return getBoundsProperty(bounds, left);
  5392. };
  5393. var getMaxXBounds = function (component) {
  5394. var bounds = getBounds(component);
  5395. return getBoundsProperty(bounds, right);
  5396. };
  5397. var getMinYBounds = function (component) {
  5398. var bounds = getBounds(component);
  5399. return getBoundsProperty(bounds, top);
  5400. };
  5401. var getMaxYBounds = function (component) {
  5402. var bounds = getBounds(component);
  5403. return getBoundsProperty(bounds, bottom);
  5404. };
  5405. var getXScreenRange = function (component) {
  5406. var bounds = getBounds(component);
  5407. return getBoundsProperty(bounds, width);
  5408. };
  5409. var getYScreenRange = function (component) {
  5410. var bounds = getBounds(component);
  5411. return getBoundsProperty(bounds, height);
  5412. };
  5413. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5414. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5415. };
  5416. var getXCenterOffSetOf = function (component, spectrum) {
  5417. var componentBounds = getBounds(component);
  5418. var spectrumBounds = getBounds(spectrum);
  5419. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5420. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5421. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5422. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5423. };
  5424. var getYCenterOffSetOf = function (component, spectrum) {
  5425. var componentBounds = getBounds(component);
  5426. var spectrumBounds = getBounds(spectrum);
  5427. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5428. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5429. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5430. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5431. };
  5432. var fireSliderChange$1 = function (spectrum, value) {
  5433. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5434. };
  5435. var sliderValue = function (x) {
  5436. return { x: constant(x) };
  5437. };
  5438. var findValueOfOffset = function (spectrum, detail, left) {
  5439. var args = {
  5440. min: minX(detail),
  5441. max: maxX(detail),
  5442. range: xRange(detail),
  5443. value: left,
  5444. step: step(detail),
  5445. snap: snap(detail),
  5446. snapStart: snapStart(detail),
  5447. rounded: rounded(detail),
  5448. hasMinEdge: hasLEdge(detail),
  5449. hasMaxEdge: hasREdge(detail),
  5450. minBound: getMinXBounds(spectrum),
  5451. maxBound: getMaxXBounds(spectrum),
  5452. screenRange: getXScreenRange(spectrum)
  5453. };
  5454. return findValueOf(args);
  5455. };
  5456. var setValueFrom = function (spectrum, detail, value) {
  5457. var xValue = findValueOfOffset(spectrum, detail, value);
  5458. var sliderVal = sliderValue(xValue);
  5459. fireSliderChange$1(spectrum, sliderVal);
  5460. return xValue;
  5461. };
  5462. var setToMin = function (spectrum, detail) {
  5463. var min = minX(detail);
  5464. fireSliderChange$1(spectrum, sliderValue(min));
  5465. };
  5466. var setToMax = function (spectrum, detail) {
  5467. var max = maxX(detail);
  5468. fireSliderChange$1(spectrum, sliderValue(max));
  5469. };
  5470. var moveBy = function (direction, spectrum, detail) {
  5471. var f = direction > 0 ? increaseBy : reduceBy;
  5472. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  5473. fireSliderChange$1(spectrum, sliderValue(xValue));
  5474. return Option.some(xValue);
  5475. };
  5476. var handleMovement = function (direction) {
  5477. return function (spectrum, detail) {
  5478. return moveBy(direction, spectrum, detail).map(function () {
  5479. return true;
  5480. });
  5481. };
  5482. };
  5483. var getValueFromEvent = function (simulatedEvent) {
  5484. var pos = getEventSource(simulatedEvent);
  5485. return pos.map(function (p) {
  5486. return p.left();
  5487. });
  5488. };
  5489. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5490. var minOffset = 0;
  5491. var maxOffset = getXScreenRange(spectrum);
  5492. var centerMinEdge = minEdge.bind(function (edge) {
  5493. return Option.some(getXCenterOffSetOf(edge, spectrum));
  5494. }).getOr(minOffset);
  5495. var centerMaxEdge = maxEdge.bind(function (edge) {
  5496. return Option.some(getXCenterOffSetOf(edge, spectrum));
  5497. }).getOr(maxOffset);
  5498. var args = {
  5499. min: minX(detail),
  5500. max: maxX(detail),
  5501. range: xRange(detail),
  5502. value: value,
  5503. hasMinEdge: hasLEdge(detail),
  5504. hasMaxEdge: hasREdge(detail),
  5505. minBound: getMinXBounds(spectrum),
  5506. minOffset: minOffset,
  5507. maxBound: getMaxXBounds(spectrum),
  5508. maxOffset: maxOffset,
  5509. centerMinEdge: centerMinEdge,
  5510. centerMaxEdge: centerMaxEdge
  5511. };
  5512. return findOffsetOfValue(args);
  5513. };
  5514. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5515. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5516. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5517. };
  5518. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5519. var value = currentValue(detail);
  5520. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5521. var thumbRadius = get$6(thumb.element()) / 2;
  5522. set$3(thumb.element(), 'left', pos - thumbRadius + 'px');
  5523. };
  5524. var onLeft = handleMovement(-1);
  5525. var onRight = handleMovement(1);
  5526. var onUp = Option.none;
  5527. var onDown = Option.none;
  5528. var edgeActions = {
  5529. 'top-left': Option.none(),
  5530. 'top': Option.none(),
  5531. 'top-right': Option.none(),
  5532. 'right': Option.some(setToREdge),
  5533. 'bottom-right': Option.none(),
  5534. 'bottom': Option.none(),
  5535. 'bottom-left': Option.none(),
  5536. 'left': Option.some(setToLEdge)
  5537. };
  5538. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5539. setValueFrom: setValueFrom,
  5540. setToMin: setToMin,
  5541. setToMax: setToMax,
  5542. findValueOfOffset: findValueOfOffset,
  5543. getValueFromEvent: getValueFromEvent,
  5544. findPositionOfValue: findPositionOfValue,
  5545. setPositionFromValue: setPositionFromValue,
  5546. onLeft: onLeft,
  5547. onRight: onRight,
  5548. onUp: onUp,
  5549. onDown: onDown,
  5550. edgeActions: edgeActions
  5551. });
  5552. var fireSliderChange$2 = function (spectrum, value) {
  5553. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5554. };
  5555. var sliderValue$1 = function (y) {
  5556. return { y: constant(y) };
  5557. };
  5558. var findValueOfOffset$1 = function (spectrum, detail, top) {
  5559. var args = {
  5560. min: minY(detail),
  5561. max: maxY(detail),
  5562. range: yRange(detail),
  5563. value: top,
  5564. step: step(detail),
  5565. snap: snap(detail),
  5566. snapStart: snapStart(detail),
  5567. rounded: rounded(detail),
  5568. hasMinEdge: hasTEdge(detail),
  5569. hasMaxEdge: hasBEdge(detail),
  5570. minBound: getMinYBounds(spectrum),
  5571. maxBound: getMaxYBounds(spectrum),
  5572. screenRange: getYScreenRange(spectrum)
  5573. };
  5574. return findValueOf(args);
  5575. };
  5576. var setValueFrom$1 = function (spectrum, detail, value) {
  5577. var yValue = findValueOfOffset$1(spectrum, detail, value);
  5578. var sliderVal = sliderValue$1(yValue);
  5579. fireSliderChange$2(spectrum, sliderVal);
  5580. return yValue;
  5581. };
  5582. var setToMin$1 = function (spectrum, detail) {
  5583. var min = minY(detail);
  5584. fireSliderChange$2(spectrum, sliderValue$1(min));
  5585. };
  5586. var setToMax$1 = function (spectrum, detail) {
  5587. var max = maxY(detail);
  5588. fireSliderChange$2(spectrum, sliderValue$1(max));
  5589. };
  5590. var moveBy$1 = function (direction, spectrum, detail) {
  5591. var f = direction > 0 ? increaseBy : reduceBy;
  5592. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  5593. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  5594. return Option.some(yValue);
  5595. };
  5596. var handleMovement$1 = function (direction) {
  5597. return function (spectrum, detail) {
  5598. return moveBy$1(direction, spectrum, detail).map(function () {
  5599. return true;
  5600. });
  5601. };
  5602. };
  5603. var getValueFromEvent$1 = function (simulatedEvent) {
  5604. var pos = getEventSource(simulatedEvent);
  5605. return pos.map(function (p) {
  5606. return p.top();
  5607. });
  5608. };
  5609. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  5610. var minOffset = 0;
  5611. var maxOffset = getYScreenRange(spectrum);
  5612. var centerMinEdge = minEdge.bind(function (edge) {
  5613. return Option.some(getYCenterOffSetOf(edge, spectrum));
  5614. }).getOr(minOffset);
  5615. var centerMaxEdge = maxEdge.bind(function (edge) {
  5616. return Option.some(getYCenterOffSetOf(edge, spectrum));
  5617. }).getOr(maxOffset);
  5618. var args = {
  5619. min: minY(detail),
  5620. max: maxY(detail),
  5621. range: yRange(detail),
  5622. value: value,
  5623. hasMinEdge: hasTEdge(detail),
  5624. hasMaxEdge: hasBEdge(detail),
  5625. minBound: getMinYBounds(spectrum),
  5626. minOffset: minOffset,
  5627. maxBound: getMaxYBounds(spectrum),
  5628. maxOffset: maxOffset,
  5629. centerMinEdge: centerMinEdge,
  5630. centerMaxEdge: centerMaxEdge
  5631. };
  5632. return findOffsetOfValue(args);
  5633. };
  5634. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5635. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  5636. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5637. };
  5638. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5639. var value = currentValue(detail);
  5640. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5641. var thumbRadius = get$4(thumb.element()) / 2;
  5642. set$3(thumb.element(), 'top', pos - thumbRadius + 'px');
  5643. };
  5644. var onLeft$1 = Option.none;
  5645. var onRight$1 = Option.none;
  5646. var onUp$1 = handleMovement$1(-1);
  5647. var onDown$1 = handleMovement$1(1);
  5648. var edgeActions$1 = {
  5649. 'top-left': Option.none(),
  5650. 'top': Option.some(setToTEdge),
  5651. 'top-right': Option.none(),
  5652. 'right': Option.none(),
  5653. 'bottom-right': Option.none(),
  5654. 'bottom': Option.some(setToBEdge),
  5655. 'bottom-left': Option.none(),
  5656. 'left': Option.none()
  5657. };
  5658. var VerticalModel = /*#__PURE__*/Object.freeze({
  5659. setValueFrom: setValueFrom$1,
  5660. setToMin: setToMin$1,
  5661. setToMax: setToMax$1,
  5662. findValueOfOffset: findValueOfOffset$1,
  5663. getValueFromEvent: getValueFromEvent$1,
  5664. findPositionOfValue: findPositionOfValue$1,
  5665. setPositionFromValue: setPositionFromValue$1,
  5666. onLeft: onLeft$1,
  5667. onRight: onRight$1,
  5668. onUp: onUp$1,
  5669. onDown: onDown$1,
  5670. edgeActions: edgeActions$1
  5671. });
  5672. var fireSliderChange$3 = function (spectrum, value) {
  5673. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5674. };
  5675. var sliderValue$2 = function (x, y) {
  5676. return {
  5677. x: constant(x),
  5678. y: constant(y)
  5679. };
  5680. };
  5681. var setValueFrom$2 = function (spectrum, detail, value) {
  5682. var xValue = findValueOfOffset(spectrum, detail, value.left());
  5683. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  5684. var val = sliderValue$2(xValue, yValue);
  5685. fireSliderChange$3(spectrum, val);
  5686. return val;
  5687. };
  5688. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  5689. var f = direction > 0 ? increaseBy : reduceBy;
  5690. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  5691. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  5692. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  5693. return Option.some(xValue);
  5694. };
  5695. var handleMovement$2 = function (direction, isVerticalMovement) {
  5696. return function (spectrum, detail) {
  5697. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  5698. return true;
  5699. });
  5700. };
  5701. };
  5702. var setToMin$2 = function (spectrum, detail) {
  5703. var mX = minX(detail);
  5704. var mY = minY(detail);
  5705. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5706. };
  5707. var setToMax$2 = function (spectrum, detail) {
  5708. var mX = maxX(detail);
  5709. var mY = maxY(detail);
  5710. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  5711. };
  5712. var getValueFromEvent$2 = function (simulatedEvent) {
  5713. return getEventSource(simulatedEvent);
  5714. };
  5715. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5716. var value = currentValue(detail);
  5717. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5718. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5719. var thumbXRadius = get$6(thumb.element()) / 2;
  5720. var thumbYRadius = get$4(thumb.element()) / 2;
  5721. set$3(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  5722. set$3(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  5723. };
  5724. var onLeft$2 = handleMovement$2(-1, false);
  5725. var onRight$2 = handleMovement$2(1, false);
  5726. var onUp$2 = handleMovement$2(-1, true);
  5727. var onDown$2 = handleMovement$2(1, true);
  5728. var edgeActions$2 = {
  5729. 'top-left': Option.some(setToTLEdgeXY),
  5730. 'top': Option.some(setToTEdgeXY),
  5731. 'top-right': Option.some(setToTREdgeXY),
  5732. 'right': Option.some(setToREdgeXY),
  5733. 'bottom-right': Option.some(setToBREdgeXY),
  5734. 'bottom': Option.some(setToBEdgeXY),
  5735. 'bottom-left': Option.some(setToBLEdgeXY),
  5736. 'left': Option.some(setToLEdgeXY)
  5737. };
  5738. var TwoDModel = /*#__PURE__*/Object.freeze({
  5739. setValueFrom: setValueFrom$2,
  5740. setToMin: setToMin$2,
  5741. setToMax: setToMax$2,
  5742. getValueFromEvent: getValueFromEvent$2,
  5743. setPositionFromValue: setPositionFromValue$2,
  5744. onLeft: onLeft$2,
  5745. onRight: onRight$2,
  5746. onUp: onUp$2,
  5747. onDown: onDown$2,
  5748. edgeActions: edgeActions$2
  5749. });
  5750. var isTouch$2 = detect$3().deviceType.isTouch();
  5751. var SliderSchema = [
  5752. defaulted$1('stepSize', 1),
  5753. defaulted$1('onChange', noop),
  5754. defaulted$1('onChoose', noop),
  5755. defaulted$1('onInit', noop),
  5756. defaulted$1('onDragStart', noop),
  5757. defaulted$1('onDragEnd', noop),
  5758. defaulted$1('snapToGrid', false),
  5759. defaulted$1('rounded', true),
  5760. option('snapStart'),
  5761. strictOf('model', choose$1('mode', {
  5762. x: [
  5763. defaulted$1('minX', 0),
  5764. defaulted$1('maxX', 100),
  5765. state$1('value', function (spec) {
  5766. return Cell(spec.mode.minX);
  5767. }),
  5768. strict$1('getInitialValue'),
  5769. output('manager', HorizontalModel)
  5770. ],
  5771. y: [
  5772. defaulted$1('minY', 0),
  5773. defaulted$1('maxY', 100),
  5774. state$1('value', function (spec) {
  5775. return Cell(spec.mode.minY);
  5776. }),
  5777. strict$1('getInitialValue'),
  5778. output('manager', VerticalModel)
  5779. ],
  5780. xy: [
  5781. defaulted$1('minX', 0),
  5782. defaulted$1('maxX', 100),
  5783. defaulted$1('minY', 0),
  5784. defaulted$1('maxY', 100),
  5785. state$1('value', function (spec) {
  5786. return Cell({
  5787. x: constant(spec.mode.minX),
  5788. y: constant(spec.mode.minY)
  5789. });
  5790. }),
  5791. strict$1('getInitialValue'),
  5792. output('manager', TwoDModel)
  5793. ]
  5794. })),
  5795. field$1('sliderBehaviours', [
  5796. Keying,
  5797. Representing
  5798. ])
  5799. ].concat(!isTouch$2 ? [state$1('mouseIsDown', function () {
  5800. return Cell(false);
  5801. })] : []);
  5802. var isTouch$3 = detect$3().deviceType.isTouch();
  5803. var sketch = function (detail, components, _spec, _externals) {
  5804. var getThumb = function (component) {
  5805. return getPartOrDie(component, detail, 'thumb');
  5806. };
  5807. var getSpectrum = function (component) {
  5808. return getPartOrDie(component, detail, 'spectrum');
  5809. };
  5810. var getLeftEdge = function (component) {
  5811. return getPart(component, detail, 'left-edge');
  5812. };
  5813. var getRightEdge = function (component) {
  5814. return getPart(component, detail, 'right-edge');
  5815. };
  5816. var getTopEdge = function (component) {
  5817. return getPart(component, detail, 'top-edge');
  5818. };
  5819. var getBottomEdge = function (component) {
  5820. return getPart(component, detail, 'bottom-edge');
  5821. };
  5822. var modelDetail = detail.model;
  5823. var model = modelDetail.manager;
  5824. var refresh = function (slider, thumb) {
  5825. model.setPositionFromValue(slider, thumb, detail, {
  5826. getLeftEdge: getLeftEdge,
  5827. getRightEdge: getRightEdge,
  5828. getTopEdge: getTopEdge,
  5829. getBottomEdge: getBottomEdge,
  5830. getSpectrum: getSpectrum
  5831. });
  5832. };
  5833. var changeValue = function (slider, newValue) {
  5834. modelDetail.value.set(newValue);
  5835. var thumb = getThumb(slider);
  5836. refresh(slider, thumb);
  5837. detail.onChange(slider, thumb, newValue);
  5838. return Option.some(true);
  5839. };
  5840. var resetToMin = function (slider) {
  5841. model.setToMin(slider, detail);
  5842. };
  5843. var resetToMax = function (slider) {
  5844. model.setToMax(slider, detail);
  5845. };
  5846. var touchEvents = [
  5847. run(touchstart(), function (slider, _simulatedEvent) {
  5848. detail.onDragStart(slider, getThumb(slider));
  5849. }),
  5850. run(touchend(), function (slider, _simulatedEvent) {
  5851. detail.onDragEnd(slider, getThumb(slider));
  5852. })
  5853. ];
  5854. var mouseEvents = [
  5855. run(mousedown(), function (slider, simulatedEvent) {
  5856. simulatedEvent.stop();
  5857. detail.onDragStart(slider, getThumb(slider));
  5858. detail.mouseIsDown.set(true);
  5859. }),
  5860. run(mouseup(), function (slider, _simulatedEvent) {
  5861. detail.onDragEnd(slider, getThumb(slider));
  5862. })
  5863. ];
  5864. var uiEventsArr = isTouch$3 ? touchEvents : mouseEvents;
  5865. return {
  5866. uid: detail.uid,
  5867. dom: detail.dom,
  5868. components: components,
  5869. behaviours: augment(detail.sliderBehaviours, flatten([
  5870. !isTouch$3 ? [Keying.config({
  5871. mode: 'special',
  5872. focusIn: function (slider) {
  5873. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  5874. }
  5875. })] : [],
  5876. [
  5877. Representing.config({
  5878. store: {
  5879. mode: 'manual',
  5880. getValue: function (_) {
  5881. return modelDetail.value.get();
  5882. }
  5883. }
  5884. }),
  5885. Receiving.config({
  5886. channels: {
  5887. 'mouse.released': {
  5888. onReceive: function (slider, se) {
  5889. var fireOnChoose = function () {
  5890. getPart(slider, detail, 'thumb').each(function (thumb) {
  5891. var value = modelDetail.value.get();
  5892. detail.onChoose(slider, thumb, value);
  5893. });
  5894. };
  5895. if (isTouch$3) {
  5896. fireOnChoose();
  5897. } else {
  5898. var wasDown = detail.mouseIsDown.get();
  5899. detail.mouseIsDown.set(false);
  5900. if (wasDown) {
  5901. fireOnChoose();
  5902. }
  5903. }
  5904. }
  5905. }
  5906. }
  5907. })
  5908. ]
  5909. ])),
  5910. events: derive([
  5911. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  5912. changeValue(slider, simulatedEvent.event().value());
  5913. }),
  5914. runOnAttached(function (slider, simulatedEvent) {
  5915. var getInitial = modelDetail.getInitialValue();
  5916. modelDetail.value.set(getInitial);
  5917. var thumb = getThumb(slider);
  5918. refresh(slider, thumb);
  5919. var spectrum = getSpectrum(slider);
  5920. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  5921. })
  5922. ].concat(uiEventsArr)),
  5923. apis: {
  5924. resetToMin: resetToMin,
  5925. resetToMax: resetToMax,
  5926. changeValue: changeValue,
  5927. refresh: refresh
  5928. },
  5929. domModification: { styles: { position: 'relative' } }
  5930. };
  5931. };
  5932. var Slider = composite$1({
  5933. name: 'Slider',
  5934. configFields: SliderSchema,
  5935. partFields: SliderParts,
  5936. factory: sketch,
  5937. apis: {
  5938. resetToMin: function (apis, slider) {
  5939. apis.resetToMin(slider);
  5940. },
  5941. resetToMax: function (apis, slider) {
  5942. apis.resetToMax(slider);
  5943. },
  5944. refresh: function (apis, slider) {
  5945. apis.refresh(slider);
  5946. }
  5947. }
  5948. });
  5949. var button = function (realm, clazz, makeItems, editor) {
  5950. return Buttons.forToolbar(clazz, function () {
  5951. var items = makeItems();
  5952. realm.setContextToolbar([{
  5953. label: clazz + ' group',
  5954. items: items
  5955. }]);
  5956. }, {}, editor);
  5957. };
  5958. var BLACK = -1;
  5959. var makeSlider = function (spec$1) {
  5960. var getColor = function (hue) {
  5961. if (hue < 0) {
  5962. return 'black';
  5963. } else if (hue > 360) {
  5964. return 'white';
  5965. } else {
  5966. return 'hsl(' + hue + ', 100%, 50%)';
  5967. }
  5968. };
  5969. var onInit = function (slider, thumb, spectrum, value) {
  5970. var color = getColor(value.x());
  5971. set$3(thumb.element(), 'background-color', color);
  5972. };
  5973. var onChange = function (slider, thumb, value) {
  5974. var color = getColor(value.x());
  5975. set$3(thumb.element(), 'background-color', color);
  5976. spec$1.onChange(slider, thumb, color);
  5977. };
  5978. return Slider.sketch({
  5979. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  5980. components: [
  5981. Slider.parts()['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  5982. Slider.parts().spectrum({
  5983. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  5984. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  5985. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  5986. }),
  5987. Slider.parts()['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  5988. Slider.parts().thumb({
  5989. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  5990. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  5991. })
  5992. ],
  5993. onChange: onChange,
  5994. onDragStart: function (slider, thumb) {
  5995. Toggling.on(thumb);
  5996. },
  5997. onDragEnd: function (slider, thumb) {
  5998. Toggling.off(thumb);
  5999. },
  6000. onInit: onInit,
  6001. stepSize: 10,
  6002. model: {
  6003. mode: 'x',
  6004. minX: 0,
  6005. maxX: 360,
  6006. getInitialValue: function () {
  6007. return {
  6008. x: function () {
  6009. return spec$1.getInitialValue();
  6010. }
  6011. };
  6012. }
  6013. },
  6014. sliderBehaviours: derive$1([Receivers.orientation(Slider.refresh)])
  6015. });
  6016. };
  6017. var makeItems = function (spec) {
  6018. return [makeSlider(spec)];
  6019. };
  6020. var sketch$1 = function (realm, editor) {
  6021. var spec = {
  6022. onChange: function (slider, thumb, color) {
  6023. editor.undoManager.transact(function () {
  6024. editor.formatter.apply('forecolor', { value: color });
  6025. editor.nodeChanged();
  6026. });
  6027. },
  6028. getInitialValue: function () {
  6029. return BLACK;
  6030. }
  6031. };
  6032. return button(realm, 'color-levels', function () {
  6033. return makeItems(spec);
  6034. }, editor);
  6035. };
  6036. var ColorSlider = {
  6037. makeItems: makeItems,
  6038. sketch: sketch$1
  6039. };
  6040. var schema$7 = objOfOnly([
  6041. strict$1('getInitialValue'),
  6042. strict$1('onChange'),
  6043. strict$1('category'),
  6044. strict$1('sizes')
  6045. ]);
  6046. var sketch$2 = function (rawSpec) {
  6047. var spec$1 = asRawOrDie('SizeSlider', schema$7, rawSpec);
  6048. var isValidValue = function (valueIndex) {
  6049. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6050. };
  6051. var onChange = function (slider, thumb, valueIndex) {
  6052. var index = valueIndex.x();
  6053. if (isValidValue(index)) {
  6054. spec$1.onChange(index);
  6055. }
  6056. };
  6057. return Slider.sketch({
  6058. dom: {
  6059. tag: 'div',
  6060. classes: [
  6061. Styles.resolve('slider-' + spec$1.category + '-size-container'),
  6062. Styles.resolve('slider'),
  6063. Styles.resolve('slider-size-container')
  6064. ]
  6065. },
  6066. onChange: onChange,
  6067. onDragStart: function (slider, thumb) {
  6068. Toggling.on(thumb);
  6069. },
  6070. onDragEnd: function (slider, thumb) {
  6071. Toggling.off(thumb);
  6072. },
  6073. model: {
  6074. mode: 'x',
  6075. minX: 0,
  6076. maxX: spec$1.sizes.length - 1,
  6077. getInitialValue: function () {
  6078. return {
  6079. x: function () {
  6080. return spec$1.getInitialValue();
  6081. }
  6082. };
  6083. }
  6084. },
  6085. stepSize: 1,
  6086. snapToGrid: true,
  6087. sliderBehaviours: derive$1([Receivers.orientation(Slider.refresh)]),
  6088. components: [
  6089. Slider.parts().spectrum({
  6090. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6091. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  6092. }),
  6093. Slider.parts().thumb({
  6094. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6095. behaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
  6096. })
  6097. ]
  6098. });
  6099. };
  6100. var SizeSlider = { sketch: sketch$2 };
  6101. var candidates = [
  6102. '9px',
  6103. '10px',
  6104. '11px',
  6105. '12px',
  6106. '14px',
  6107. '16px',
  6108. '18px',
  6109. '20px',
  6110. '24px',
  6111. '32px',
  6112. '36px'
  6113. ];
  6114. var defaultSize = 'medium';
  6115. var defaultIndex = 2;
  6116. var indexToSize = function (index) {
  6117. return Option.from(candidates[index]);
  6118. };
  6119. var sizeToIndex = function (size) {
  6120. return findIndex(candidates, function (v) {
  6121. return v === size;
  6122. });
  6123. };
  6124. var getRawOrComputed = function (isRoot, rawStart) {
  6125. var optStart = isElement(rawStart) ? Option.some(rawStart) : parent(rawStart).filter(isElement);
  6126. return optStart.map(function (start) {
  6127. var inline = closest(start, function (elem) {
  6128. return getRaw(elem, 'font-size').isSome();
  6129. }, isRoot).bind(function (elem) {
  6130. return getRaw(elem, 'font-size');
  6131. });
  6132. return inline.getOrThunk(function () {
  6133. return get$3(start, 'font-size');
  6134. });
  6135. }).getOr('');
  6136. };
  6137. var getSize = function (editor) {
  6138. var node = editor.selection.getStart();
  6139. var elem = Element.fromDom(node);
  6140. var root = Element.fromDom(editor.getBody());
  6141. var isRoot = function (e) {
  6142. return eq(root, e);
  6143. };
  6144. var elemSize = getRawOrComputed(isRoot, elem);
  6145. return find$2(candidates, function (size) {
  6146. return elemSize === size;
  6147. }).getOr(defaultSize);
  6148. };
  6149. var applySize = function (editor, value) {
  6150. var currentValue = getSize(editor);
  6151. if (currentValue !== value) {
  6152. editor.execCommand('fontSize', false, value);
  6153. }
  6154. };
  6155. var get$7 = function (editor) {
  6156. var size = getSize(editor);
  6157. return sizeToIndex(size).getOr(defaultIndex);
  6158. };
  6159. var apply$1 = function (editor, index) {
  6160. indexToSize(index).each(function (size) {
  6161. applySize(editor, size);
  6162. });
  6163. };
  6164. var FontSizes = {
  6165. candidates: constant(candidates),
  6166. get: get$7,
  6167. apply: apply$1
  6168. };
  6169. var sizes = FontSizes.candidates();
  6170. var makeSlider$1 = function (spec) {
  6171. return SizeSlider.sketch({
  6172. onChange: spec.onChange,
  6173. sizes: sizes,
  6174. category: 'font',
  6175. getInitialValue: spec.getInitialValue
  6176. });
  6177. };
  6178. var makeItems$1 = function (spec$1) {
  6179. return [
  6180. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6181. makeSlider$1(spec$1),
  6182. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6183. ];
  6184. };
  6185. var sketch$3 = function (realm, editor) {
  6186. var spec = {
  6187. onChange: function (value) {
  6188. FontSizes.apply(editor, value);
  6189. },
  6190. getInitialValue: function () {
  6191. return FontSizes.get(editor);
  6192. }
  6193. };
  6194. return button(realm, 'font-size', function () {
  6195. return makeItems$1(spec);
  6196. }, editor);
  6197. };
  6198. var record = function (spec) {
  6199. var uid = isSketchSpec(spec) && hasKey$1(spec, 'uid') ? spec.uid : generate$3('memento');
  6200. var get = function (anyInSystem) {
  6201. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6202. };
  6203. var getOpt = function (anyInSystem) {
  6204. return anyInSystem.getSystem().getByUid(uid).toOption();
  6205. };
  6206. var asSpec = function () {
  6207. return __assign(__assign({}, spec), { uid: uid });
  6208. };
  6209. return {
  6210. get: get,
  6211. getOpt: getOpt,
  6212. asSpec: asSpec
  6213. };
  6214. };
  6215. var promise = function () {
  6216. var Promise = function (fn) {
  6217. if (typeof this !== 'object') {
  6218. throw new TypeError('Promises must be constructed via new');
  6219. }
  6220. if (typeof fn !== 'function') {
  6221. throw new TypeError('not a function');
  6222. }
  6223. this._state = null;
  6224. this._value = null;
  6225. this._deferreds = [];
  6226. doResolve(fn, bind(resolve, this), bind(reject, this));
  6227. };
  6228. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  6229. domGlobals.setTimeout(fn, 1);
  6230. };
  6231. function bind(fn, thisArg) {
  6232. return function () {
  6233. return fn.apply(thisArg, arguments);
  6234. };
  6235. }
  6236. var isArray = Array.isArray || function (value) {
  6237. return Object.prototype.toString.call(value) === '[object Array]';
  6238. };
  6239. function handle(deferred) {
  6240. var me = this;
  6241. if (this._state === null) {
  6242. this._deferreds.push(deferred);
  6243. return;
  6244. }
  6245. asap(function () {
  6246. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  6247. if (cb === null) {
  6248. (me._state ? deferred.resolve : deferred.reject)(me._value);
  6249. return;
  6250. }
  6251. var ret;
  6252. try {
  6253. ret = cb(me._value);
  6254. } catch (e) {
  6255. deferred.reject(e);
  6256. return;
  6257. }
  6258. deferred.resolve(ret);
  6259. });
  6260. }
  6261. function resolve(newValue) {
  6262. try {
  6263. if (newValue === this) {
  6264. throw new TypeError('A promise cannot be resolved with itself.');
  6265. }
  6266. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6267. var then = newValue.then;
  6268. if (typeof then === 'function') {
  6269. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  6270. return;
  6271. }
  6272. }
  6273. this._state = true;
  6274. this._value = newValue;
  6275. finale.call(this);
  6276. } catch (e) {
  6277. reject.call(this, e);
  6278. }
  6279. }
  6280. function reject(newValue) {
  6281. this._state = false;
  6282. this._value = newValue;
  6283. finale.call(this);
  6284. }
  6285. function finale() {
  6286. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  6287. var deferred = _a[_i];
  6288. handle.call(this, deferred);
  6289. }
  6290. this._deferreds = [];
  6291. }
  6292. function Handler(onFulfilled, onRejected, resolve, reject) {
  6293. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6294. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6295. this.resolve = resolve;
  6296. this.reject = reject;
  6297. }
  6298. function doResolve(fn, onFulfilled, onRejected) {
  6299. var done = false;
  6300. try {
  6301. fn(function (value) {
  6302. if (done) {
  6303. return;
  6304. }
  6305. done = true;
  6306. onFulfilled(value);
  6307. }, function (reason) {
  6308. if (done) {
  6309. return;
  6310. }
  6311. done = true;
  6312. onRejected(reason);
  6313. });
  6314. } catch (ex) {
  6315. if (done) {
  6316. return;
  6317. }
  6318. done = true;
  6319. onRejected(ex);
  6320. }
  6321. }
  6322. Promise.prototype.catch = function (onRejected) {
  6323. return this.then(null, onRejected);
  6324. };
  6325. Promise.prototype.then = function (onFulfilled, onRejected) {
  6326. var me = this;
  6327. return new Promise(function (resolve, reject) {
  6328. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  6329. });
  6330. };
  6331. Promise.all = function () {
  6332. var values = [];
  6333. for (var _i = 0; _i < arguments.length; _i++) {
  6334. values[_i] = arguments[_i];
  6335. }
  6336. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  6337. return new Promise(function (resolve, reject) {
  6338. if (args.length === 0) {
  6339. return resolve([]);
  6340. }
  6341. var remaining = args.length;
  6342. function res(i, val) {
  6343. try {
  6344. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6345. var then = val.then;
  6346. if (typeof then === 'function') {
  6347. then.call(val, function (val) {
  6348. res(i, val);
  6349. }, reject);
  6350. return;
  6351. }
  6352. }
  6353. args[i] = val;
  6354. if (--remaining === 0) {
  6355. resolve(args);
  6356. }
  6357. } catch (ex) {
  6358. reject(ex);
  6359. }
  6360. }
  6361. for (var i = 0; i < args.length; i++) {
  6362. res(i, args[i]);
  6363. }
  6364. });
  6365. };
  6366. Promise.resolve = function (value) {
  6367. if (value && typeof value === 'object' && value.constructor === Promise) {
  6368. return value;
  6369. }
  6370. return new Promise(function (resolve) {
  6371. resolve(value);
  6372. });
  6373. };
  6374. Promise.reject = function (reason) {
  6375. return new Promise(function (resolve, reject) {
  6376. reject(reason);
  6377. });
  6378. };
  6379. Promise.race = function (values) {
  6380. return new Promise(function (resolve, reject) {
  6381. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  6382. var value = values_1[_i];
  6383. value.then(resolve, reject);
  6384. }
  6385. });
  6386. };
  6387. return Promise;
  6388. };
  6389. var Promise = window.Promise ? window.Promise : promise();
  6390. function blobToDataUri(blob) {
  6391. return new Promise(function (resolve) {
  6392. var reader = new domGlobals.FileReader();
  6393. reader.onloadend = function () {
  6394. resolve(reader.result);
  6395. };
  6396. reader.readAsDataURL(blob);
  6397. });
  6398. }
  6399. function blobToBase64(blob) {
  6400. return blobToDataUri(blob).then(function (dataUri) {
  6401. return dataUri.split(',')[1];
  6402. });
  6403. }
  6404. var blobToBase64$1 = function (blob) {
  6405. return blobToBase64(blob);
  6406. };
  6407. var addImage = function (editor, blob) {
  6408. blobToBase64$1(blob).then(function (base64) {
  6409. editor.undoManager.transact(function () {
  6410. var cache = editor.editorUpload.blobCache;
  6411. var info = cache.create(generate$1('mceu'), blob, base64);
  6412. cache.add(info);
  6413. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6414. editor.insertContent(img);
  6415. });
  6416. });
  6417. };
  6418. var extractBlob = function (simulatedEvent) {
  6419. var event = simulatedEvent.event();
  6420. var files = event.raw().target.files || event.raw().dataTransfer.files;
  6421. return Option.from(files[0]);
  6422. };
  6423. var sketch$4 = function (editor) {
  6424. var pickerDom = {
  6425. tag: 'input',
  6426. attributes: {
  6427. accept: 'image/*',
  6428. type: 'file',
  6429. title: ''
  6430. },
  6431. styles: {
  6432. visibility: 'hidden',
  6433. position: 'absolute'
  6434. }
  6435. };
  6436. var memPicker = record({
  6437. dom: pickerDom,
  6438. events: derive([
  6439. cutter(click()),
  6440. run(change(), function (picker, simulatedEvent) {
  6441. extractBlob(simulatedEvent).each(function (blob) {
  6442. addImage(editor, blob);
  6443. });
  6444. })
  6445. ])
  6446. });
  6447. return Button.sketch({
  6448. dom: Buttons.getToolbarIconButton('image', editor),
  6449. components: [memPicker.asSpec()],
  6450. action: function (button) {
  6451. var picker = memPicker.get(button);
  6452. picker.element().dom().click();
  6453. }
  6454. });
  6455. };
  6456. var get$8 = function (element) {
  6457. return element.dom().textContent;
  6458. };
  6459. var set$5 = function (element, value) {
  6460. element.dom().textContent = value;
  6461. };
  6462. var isNotEmpty = function (val) {
  6463. return val.length > 0;
  6464. };
  6465. var defaultToEmpty = function (str) {
  6466. return str === undefined || str === null ? '' : str;
  6467. };
  6468. var noLink = function (editor) {
  6469. var text = editor.selection.getContent({ format: 'text' });
  6470. return {
  6471. url: '',
  6472. text: text,
  6473. title: '',
  6474. target: '',
  6475. link: Option.none()
  6476. };
  6477. };
  6478. var fromLink = function (link) {
  6479. var text = get$8(link);
  6480. var url = get(link, 'href');
  6481. var title = get(link, 'title');
  6482. var target = get(link, 'target');
  6483. return {
  6484. url: defaultToEmpty(url),
  6485. text: text !== url ? defaultToEmpty(text) : '',
  6486. title: defaultToEmpty(title),
  6487. target: defaultToEmpty(target),
  6488. link: Option.some(link)
  6489. };
  6490. };
  6491. var getInfo = function (editor) {
  6492. return query(editor).fold(function () {
  6493. return noLink(editor);
  6494. }, function (link) {
  6495. return fromLink(link);
  6496. });
  6497. };
  6498. var wasSimple = function (link) {
  6499. var prevHref = get(link, 'href');
  6500. var prevText = get$8(link);
  6501. return prevHref === prevText;
  6502. };
  6503. var getTextToApply = function (link, url, info) {
  6504. return info.text.toOption().filter(isNotEmpty).fold(function () {
  6505. return wasSimple(link) ? Option.some(url) : Option.none();
  6506. }, Option.some);
  6507. };
  6508. var unlinkIfRequired = function (editor, info) {
  6509. var activeLink = info.link.bind(identity);
  6510. activeLink.each(function (link) {
  6511. editor.execCommand('unlink');
  6512. });
  6513. };
  6514. var getAttrs$1 = function (url, info) {
  6515. var attrs = {};
  6516. attrs.href = url;
  6517. info.title.toOption().filter(isNotEmpty).each(function (title) {
  6518. attrs.title = title;
  6519. });
  6520. info.target.toOption().filter(isNotEmpty).each(function (target) {
  6521. attrs.target = target;
  6522. });
  6523. return attrs;
  6524. };
  6525. var applyInfo = function (editor, info) {
  6526. info.url.toOption().filter(isNotEmpty).fold(function () {
  6527. unlinkIfRequired(editor, info);
  6528. }, function (url) {
  6529. var attrs = getAttrs$1(url, info);
  6530. var activeLink = info.link.bind(identity);
  6531. activeLink.fold(function () {
  6532. var text = info.text.toOption().filter(isNotEmpty).getOr(url);
  6533. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6534. }, function (link) {
  6535. var text = getTextToApply(link, url, info);
  6536. setAll(link, attrs);
  6537. text.each(function (newText) {
  6538. set$5(link, newText);
  6539. });
  6540. });
  6541. });
  6542. };
  6543. var query = function (editor) {
  6544. var start = Element.fromDom(editor.selection.getStart());
  6545. return closest$2(start, 'a');
  6546. };
  6547. var LinkBridge = {
  6548. getInfo: getInfo,
  6549. applyInfo: applyInfo,
  6550. query: query
  6551. };
  6552. var platform$2 = detect$3();
  6553. var preserve = function (f, editor) {
  6554. var rng = editor.selection.getRng();
  6555. f();
  6556. editor.selection.setRng(rng);
  6557. };
  6558. var forAndroid = function (editor, f) {
  6559. var wrapper = platform$2.os.isAndroid() ? preserve : apply;
  6560. wrapper(f, editor);
  6561. };
  6562. var RangePreserver = { forAndroid: forAndroid };
  6563. var events$6 = function (name, eventHandlers) {
  6564. var events = derive(eventHandlers);
  6565. return create$1({
  6566. fields: [strict$1('enabled')],
  6567. name: name,
  6568. active: { events: constant(events) }
  6569. });
  6570. };
  6571. var config = function (name, eventHandlers) {
  6572. var me = events$6(name, eventHandlers);
  6573. return {
  6574. key: name,
  6575. value: {
  6576. config: {},
  6577. me: me,
  6578. configAsRaw: constant({}),
  6579. initialConfig: {},
  6580. state: NoState
  6581. }
  6582. };
  6583. };
  6584. var getCurrent = function (component, composeConfig, composeState) {
  6585. return composeConfig.find(component);
  6586. };
  6587. var ComposeApis = /*#__PURE__*/Object.freeze({
  6588. getCurrent: getCurrent
  6589. });
  6590. var ComposeSchema = [strict$1('find')];
  6591. var Composing = create$1({
  6592. fields: ComposeSchema,
  6593. name: 'composing',
  6594. apis: ComposeApis
  6595. });
  6596. var factory$1 = function (detail) {
  6597. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6598. return {
  6599. uid: detail.uid,
  6600. dom: __assign({
  6601. tag: 'div',
  6602. attributes: __assign({ role: 'presentation' }, attributes)
  6603. }, domWithoutAttributes),
  6604. components: detail.components,
  6605. behaviours: get$5(detail.containerBehaviours),
  6606. events: detail.events,
  6607. domModification: detail.domModification,
  6608. eventOrder: detail.eventOrder
  6609. };
  6610. };
  6611. var Container = single$2({
  6612. name: 'Container',
  6613. factory: factory$1,
  6614. configFields: [
  6615. defaulted$1('components', []),
  6616. field$1('containerBehaviours', []),
  6617. defaulted$1('events', {}),
  6618. defaulted$1('domModification', {}),
  6619. defaulted$1('eventOrder', {})
  6620. ]
  6621. });
  6622. var factory$2 = function (detail) {
  6623. return {
  6624. uid: detail.uid,
  6625. dom: detail.dom,
  6626. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6627. Representing.config({
  6628. store: {
  6629. mode: 'memory',
  6630. initialValue: detail.getInitialValue()
  6631. }
  6632. }),
  6633. Composing.config({ find: Option.some })
  6634. ]),
  6635. events: derive([runOnAttached(function (component, simulatedEvent) {
  6636. Representing.setValue(component, detail.getInitialValue());
  6637. })])
  6638. };
  6639. };
  6640. var DataField = single$2({
  6641. name: 'DataField',
  6642. factory: factory$2,
  6643. configFields: [
  6644. strict$1('uid'),
  6645. strict$1('dom'),
  6646. strict$1('getInitialValue'),
  6647. SketchBehaviours.field('dataBehaviours', [
  6648. Representing,
  6649. Composing
  6650. ])
  6651. ]
  6652. });
  6653. var get$9 = function (element) {
  6654. return element.dom().value;
  6655. };
  6656. var set$6 = function (element, value) {
  6657. if (value === undefined) {
  6658. throw new Error('Value.set was undefined');
  6659. }
  6660. element.dom().value = value;
  6661. };
  6662. var schema$8 = constant([
  6663. option('data'),
  6664. defaulted$1('inputAttributes', {}),
  6665. defaulted$1('inputStyles', {}),
  6666. defaulted$1('tag', 'input'),
  6667. defaulted$1('inputClasses', []),
  6668. onHandler('onSetValue'),
  6669. defaulted$1('styles', {}),
  6670. defaulted$1('eventOrder', {}),
  6671. field$1('inputBehaviours', [
  6672. Representing,
  6673. Focusing
  6674. ]),
  6675. defaulted$1('selectOnFocus', true)
  6676. ]);
  6677. var focusBehaviours = function (detail) {
  6678. return derive$1([Focusing.config({
  6679. onFocus: detail.selectOnFocus === false ? noop : function (component) {
  6680. var input = component.element();
  6681. var value = get$9(input);
  6682. input.dom().setSelectionRange(0, value.length);
  6683. }
  6684. })]);
  6685. };
  6686. var behaviours = function (detail) {
  6687. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6688. store: {
  6689. mode: 'manual',
  6690. initialValue: detail.data.getOr(undefined),
  6691. getValue: function (input) {
  6692. return get$9(input.element());
  6693. },
  6694. setValue: function (input, data) {
  6695. var current = get$9(input.element());
  6696. if (current !== data) {
  6697. set$6(input.element(), data);
  6698. }
  6699. }
  6700. },
  6701. onSetValue: detail.onSetValue
  6702. })]));
  6703. };
  6704. var dom$2 = function (detail) {
  6705. return {
  6706. tag: detail.tag,
  6707. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6708. styles: detail.inputStyles,
  6709. classes: detail.inputClasses
  6710. };
  6711. };
  6712. var factory$3 = function (detail, spec) {
  6713. return {
  6714. uid: detail.uid,
  6715. dom: dom$2(detail),
  6716. components: [],
  6717. behaviours: behaviours(detail),
  6718. eventOrder: detail.eventOrder
  6719. };
  6720. };
  6721. var Input = single$2({
  6722. name: 'Input',
  6723. configFields: schema$8(),
  6724. factory: factory$3
  6725. });
  6726. var exhibit$3 = function (base, tabConfig) {
  6727. return nu$5({
  6728. attributes: wrapAll$1([{
  6729. key: tabConfig.tabAttr,
  6730. value: 'true'
  6731. }])
  6732. });
  6733. };
  6734. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6735. exhibit: exhibit$3
  6736. });
  6737. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  6738. var Tabstopping = create$1({
  6739. fields: TabstopSchema,
  6740. name: 'tabstopping',
  6741. active: ActiveTabstopping
  6742. });
  6743. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6744. var clearInputBehaviour = 'input-clearing';
  6745. var field$2 = function (name, placeholder) {
  6746. var inputSpec = record(Input.sketch({
  6747. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6748. onSetValue: function (input$1, data) {
  6749. emit(input$1, input());
  6750. },
  6751. inputBehaviours: derive$1([
  6752. Composing.config({ find: Option.some }),
  6753. Tabstopping.config({}),
  6754. Keying.config({ mode: 'execution' })
  6755. ]),
  6756. selectOnFocus: false
  6757. }));
  6758. var buttonSpec = record(Button.sketch({
  6759. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6760. action: function (button) {
  6761. var input = inputSpec.get(button);
  6762. Representing.setValue(input, '');
  6763. }
  6764. }));
  6765. return {
  6766. name: name,
  6767. spec: Container.sketch({
  6768. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6769. components: [
  6770. inputSpec.asSpec(),
  6771. buttonSpec.asSpec()
  6772. ],
  6773. containerBehaviours: derive$1([
  6774. Toggling.config({ toggleClass: Styles.resolve('input-container-empty') }),
  6775. Composing.config({
  6776. find: function (comp) {
  6777. return Option.some(inputSpec.get(comp));
  6778. }
  6779. }),
  6780. config(clearInputBehaviour, [run(input(), function (iContainer) {
  6781. var input = inputSpec.get(iContainer);
  6782. var val = Representing.getValue(input);
  6783. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6784. f(iContainer);
  6785. })])
  6786. ])
  6787. })
  6788. };
  6789. };
  6790. var hidden = function (name) {
  6791. return {
  6792. name: name,
  6793. spec: DataField.sketch({
  6794. dom: {
  6795. tag: 'span',
  6796. styles: { display: 'none' }
  6797. },
  6798. getInitialValue: function () {
  6799. return Option.none();
  6800. }
  6801. })
  6802. };
  6803. };
  6804. var nativeDisabled = [
  6805. 'input',
  6806. 'button',
  6807. 'textarea',
  6808. 'select'
  6809. ];
  6810. var onLoad$5 = function (component, disableConfig, disableState) {
  6811. if (disableConfig.disabled) {
  6812. disable(component, disableConfig);
  6813. }
  6814. };
  6815. var hasNative = function (component, config) {
  6816. return config.useNative === true && contains(nativeDisabled, name(component.element()));
  6817. };
  6818. var nativeIsDisabled = function (component) {
  6819. return has$1(component.element(), 'disabled');
  6820. };
  6821. var nativeDisable = function (component) {
  6822. set(component.element(), 'disabled', 'disabled');
  6823. };
  6824. var nativeEnable = function (component) {
  6825. remove$1(component.element(), 'disabled');
  6826. };
  6827. var ariaIsDisabled = function (component) {
  6828. return get(component.element(), 'aria-disabled') === 'true';
  6829. };
  6830. var ariaDisable = function (component) {
  6831. set(component.element(), 'aria-disabled', 'true');
  6832. };
  6833. var ariaEnable = function (component) {
  6834. set(component.element(), 'aria-disabled', 'false');
  6835. };
  6836. var disable = function (component, disableConfig, disableState) {
  6837. disableConfig.disableClass.each(function (disableClass) {
  6838. add$2(component.element(), disableClass);
  6839. });
  6840. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6841. f(component);
  6842. disableConfig.onDisabled(component);
  6843. };
  6844. var enable = function (component, disableConfig, disableState) {
  6845. disableConfig.disableClass.each(function (disableClass) {
  6846. remove$4(component.element(), disableClass);
  6847. });
  6848. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6849. f(component);
  6850. disableConfig.onEnabled(component);
  6851. };
  6852. var isDisabled = function (component, disableConfig) {
  6853. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6854. };
  6855. var set$7 = function (component, disableConfig, disableState, disabled) {
  6856. var f = disabled ? disable : enable;
  6857. f(component, disableConfig, disableState);
  6858. };
  6859. var DisableApis = /*#__PURE__*/Object.freeze({
  6860. enable: enable,
  6861. disable: disable,
  6862. isDisabled: isDisabled,
  6863. onLoad: onLoad$5,
  6864. set: set$7
  6865. });
  6866. var exhibit$4 = function (base, disableConfig, disableState) {
  6867. return nu$5({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  6868. };
  6869. var events$7 = function (disableConfig, disableState) {
  6870. return derive([
  6871. abort(execute(), function (component, simulatedEvent) {
  6872. return isDisabled(component, disableConfig);
  6873. }),
  6874. loadEvent(disableConfig, disableState, onLoad$5)
  6875. ]);
  6876. };
  6877. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6878. exhibit: exhibit$4,
  6879. events: events$7
  6880. });
  6881. var DisableSchema = [
  6882. defaulted$1('disabled', false),
  6883. defaulted$1('useNative', true),
  6884. option('disableClass'),
  6885. onHandler('onDisabled'),
  6886. onHandler('onEnabled')
  6887. ];
  6888. var Disabling = create$1({
  6889. fields: DisableSchema,
  6890. name: 'disabling',
  6891. active: ActiveDisable,
  6892. apis: DisableApis
  6893. });
  6894. var owner$1 = 'form';
  6895. var schema$9 = [field$1('formBehaviours', [Representing])];
  6896. var getPartName = function (name) {
  6897. return '<alloy.field.' + name + '>';
  6898. };
  6899. var sketch$5 = function (fSpec) {
  6900. var parts = function () {
  6901. var record = [];
  6902. var field = function (name, config) {
  6903. record.push(name);
  6904. return generateOne(owner$1, getPartName(name), config);
  6905. };
  6906. return {
  6907. field: field,
  6908. record: function () {
  6909. return record;
  6910. }
  6911. };
  6912. }();
  6913. var spec = fSpec(parts);
  6914. var partNames = parts.record();
  6915. var fieldParts = map$1(partNames, function (n) {
  6916. return required({
  6917. name: n,
  6918. pname: getPartName(n)
  6919. });
  6920. });
  6921. return composite(owner$1, schema$9, fieldParts, make, spec);
  6922. };
  6923. var toResult$1 = function (o, e) {
  6924. return o.fold(function () {
  6925. return Result.error(e);
  6926. }, Result.value);
  6927. };
  6928. var make = function (detail, components, spec) {
  6929. return {
  6930. uid: detail.uid,
  6931. dom: detail.dom,
  6932. components: components,
  6933. behaviours: augment(detail.formBehaviours, [Representing.config({
  6934. store: {
  6935. mode: 'manual',
  6936. getValue: function (form) {
  6937. var resPs = getAllParts(form, detail);
  6938. return map(resPs, function (resPThunk, pName) {
  6939. return resPThunk().bind(function (v) {
  6940. var opt = Composing.getCurrent(v);
  6941. return toResult$1(opt, 'missing current');
  6942. }).map(Representing.getValue);
  6943. });
  6944. },
  6945. setValue: function (form, values) {
  6946. each(values, function (newValue, key) {
  6947. getPart(form, detail, key).each(function (wrapper) {
  6948. Composing.getCurrent(wrapper).each(function (field) {
  6949. Representing.setValue(field, newValue);
  6950. });
  6951. });
  6952. });
  6953. }
  6954. }
  6955. })]),
  6956. apis: {
  6957. getField: function (form, key) {
  6958. return getPart(form, detail, key).bind(Composing.getCurrent);
  6959. }
  6960. }
  6961. };
  6962. };
  6963. var Form = {
  6964. getField: makeApi(function (apis, component, key) {
  6965. return apis.getField(component, key);
  6966. }),
  6967. sketch: sketch$5
  6968. };
  6969. var api$2 = function () {
  6970. var subject = Cell(Option.none());
  6971. var revoke = function () {
  6972. subject.get().each(function (s) {
  6973. s.destroy();
  6974. });
  6975. };
  6976. var clear = function () {
  6977. revoke();
  6978. subject.set(Option.none());
  6979. };
  6980. var set = function (s) {
  6981. revoke();
  6982. subject.set(Option.some(s));
  6983. };
  6984. var run = function (f) {
  6985. subject.get().each(f);
  6986. };
  6987. var isSet = function () {
  6988. return subject.get().isSome();
  6989. };
  6990. return {
  6991. clear: clear,
  6992. isSet: isSet,
  6993. set: set,
  6994. run: run
  6995. };
  6996. };
  6997. var value$2 = function () {
  6998. var subject = Cell(Option.none());
  6999. var clear = function () {
  7000. subject.set(Option.none());
  7001. };
  7002. var set = function (s) {
  7003. subject.set(Option.some(s));
  7004. };
  7005. var on = function (f) {
  7006. subject.get().each(f);
  7007. };
  7008. var isSet = function () {
  7009. return subject.get().isSome();
  7010. };
  7011. return {
  7012. clear: clear,
  7013. set: set,
  7014. isSet: isSet,
  7015. on: on
  7016. };
  7017. };
  7018. var SWIPING_LEFT = 1;
  7019. var SWIPING_RIGHT = -1;
  7020. var SWIPING_NONE = 0;
  7021. var init$2 = function (xValue) {
  7022. return {
  7023. xValue: xValue,
  7024. points: []
  7025. };
  7026. };
  7027. var move$1 = function (model, xValue) {
  7028. if (xValue === model.xValue) {
  7029. return model;
  7030. }
  7031. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7032. var newPoint = {
  7033. direction: currentDirection,
  7034. xValue: xValue
  7035. };
  7036. var priorPoints = function () {
  7037. if (model.points.length === 0) {
  7038. return [];
  7039. } else {
  7040. var prev = model.points[model.points.length - 1];
  7041. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7042. }
  7043. }();
  7044. return {
  7045. xValue: xValue,
  7046. points: priorPoints.concat([newPoint])
  7047. };
  7048. };
  7049. var complete = function (model) {
  7050. if (model.points.length === 0) {
  7051. return SWIPING_NONE;
  7052. } else {
  7053. var firstDirection = model.points[0].direction;
  7054. var lastDirection = model.points[model.points.length - 1].direction;
  7055. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7056. }
  7057. };
  7058. var SwipingModel = {
  7059. init: init$2,
  7060. move: move$1,
  7061. complete: complete
  7062. };
  7063. var sketch$6 = function (rawSpec) {
  7064. var navigateEvent = 'navigateEvent';
  7065. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7066. var formAdhocEvents = 'form-events';
  7067. var schema = objOf([
  7068. strict$1('fields'),
  7069. defaulted$1('maxFieldIndex', rawSpec.fields.length - 1),
  7070. strict$1('onExecute'),
  7071. strict$1('getInitialValue'),
  7072. state$1('state', function () {
  7073. return {
  7074. dialogSwipeState: value$2(),
  7075. currentScreen: Cell(0)
  7076. };
  7077. })
  7078. ]);
  7079. var spec$1 = asRawOrDie('SerialisedDialog', schema, rawSpec);
  7080. var navigationButton = function (direction, directionName, enabled) {
  7081. return Button.sketch({
  7082. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7083. action: function (button) {
  7084. emitWith(button, navigateEvent, { direction: direction });
  7085. },
  7086. buttonBehaviours: derive$1([Disabling.config({
  7087. disableClass: Styles.resolve('toolbar-navigation-disabled'),
  7088. disabled: !enabled
  7089. })])
  7090. });
  7091. };
  7092. var reposition = function (dialog, message) {
  7093. descendant$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
  7094. set$3(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  7095. });
  7096. };
  7097. var navigate = function (dialog, direction) {
  7098. var screens = descendants(dialog.element(), '.' + Styles.resolve('serialised-dialog-screen'));
  7099. descendant$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
  7100. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  7101. getRaw(parent, 'left').each(function (left) {
  7102. var currentLeft = parseInt(left, 10);
  7103. var w = get$6(screens[0]);
  7104. set$3(parent, 'left', currentLeft - direction * w + 'px');
  7105. });
  7106. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  7107. }
  7108. });
  7109. };
  7110. var focusInput = function (dialog) {
  7111. var inputs = descendants(dialog.element(), 'input');
  7112. var optInput = Option.from(inputs[spec$1.state.currentScreen.get()]);
  7113. optInput.each(function (input) {
  7114. dialog.getSystem().getByDom(input).each(function (inputComp) {
  7115. dispatchFocus(dialog, inputComp.element());
  7116. });
  7117. });
  7118. var dotitems = memDots.get(dialog);
  7119. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  7120. };
  7121. var resetState = function () {
  7122. spec$1.state.currentScreen.set(0);
  7123. spec$1.state.dialogSwipeState.clear();
  7124. };
  7125. var memForm = record(Form.sketch(function (parts) {
  7126. return {
  7127. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  7128. components: [Container.sketch({
  7129. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  7130. components: map$1(spec$1.fields, function (field, i) {
  7131. return i <= spec$1.maxFieldIndex ? Container.sketch({
  7132. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  7133. components: [
  7134. navigationButton(-1, 'previous', i > 0),
  7135. parts.field(field.name, field.spec),
  7136. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  7137. ]
  7138. }) : parts.field(field.name, field.spec);
  7139. })
  7140. })],
  7141. formBehaviours: derive$1([
  7142. Receivers.orientation(function (dialog, message) {
  7143. reposition(dialog, message);
  7144. }),
  7145. Keying.config({
  7146. mode: 'special',
  7147. focusIn: function (dialog) {
  7148. focusInput(dialog);
  7149. },
  7150. onTab: function (dialog) {
  7151. navigate(dialog, +1);
  7152. return Option.some(true);
  7153. },
  7154. onShiftTab: function (dialog) {
  7155. navigate(dialog, -1);
  7156. return Option.some(true);
  7157. }
  7158. }),
  7159. config(formAdhocEvents, [
  7160. runOnAttached(function (dialog, simulatedEvent) {
  7161. resetState();
  7162. var dotitems = memDots.get(dialog);
  7163. Highlighting.highlightFirst(dotitems);
  7164. spec$1.getInitialValue(dialog).each(function (v) {
  7165. Representing.setValue(dialog, v);
  7166. });
  7167. }),
  7168. runOnExecute(spec$1.onExecute),
  7169. run(transitionend(), function (dialog, simulatedEvent) {
  7170. var event = simulatedEvent.event();
  7171. if (event.raw().propertyName === 'left') {
  7172. focusInput(dialog);
  7173. }
  7174. }),
  7175. run(navigateEvent, function (dialog, simulatedEvent) {
  7176. var event = simulatedEvent.event();
  7177. var direction = event.direction();
  7178. navigate(dialog, direction);
  7179. })
  7180. ])
  7181. ])
  7182. };
  7183. }));
  7184. var memDots = record({
  7185. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7186. behaviours: derive$1([Highlighting.config({
  7187. highlightClass: Styles.resolve('dot-active'),
  7188. itemClass: Styles.resolve('dot-item')
  7189. })]),
  7190. components: bind(spec$1.fields, function (_f, i) {
  7191. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7192. })
  7193. });
  7194. return {
  7195. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7196. components: [
  7197. memForm.asSpec(),
  7198. memDots.asSpec()
  7199. ],
  7200. behaviours: derive$1([
  7201. Keying.config({
  7202. mode: 'special',
  7203. focusIn: function (wrapper) {
  7204. var form = memForm.get(wrapper);
  7205. Keying.focusIn(form);
  7206. }
  7207. }),
  7208. config(wrapperAdhocEvents, [
  7209. run(touchstart(), function (wrapper, simulatedEvent) {
  7210. var event = simulatedEvent.event();
  7211. spec$1.state.dialogSwipeState.set(SwipingModel.init(event.raw().touches[0].clientX));
  7212. }),
  7213. run(touchmove(), function (wrapper, simulatedEvent) {
  7214. var event = simulatedEvent.event();
  7215. spec$1.state.dialogSwipeState.on(function (state) {
  7216. simulatedEvent.event().prevent();
  7217. spec$1.state.dialogSwipeState.set(SwipingModel.move(state, event.raw().touches[0].clientX));
  7218. });
  7219. }),
  7220. run(touchend(), function (wrapper) {
  7221. spec$1.state.dialogSwipeState.on(function (state) {
  7222. var dialog = memForm.get(wrapper);
  7223. var direction = -1 * SwipingModel.complete(state);
  7224. navigate(dialog, direction);
  7225. });
  7226. })
  7227. ])
  7228. ])
  7229. };
  7230. };
  7231. var getGroups = cached(function (realm, editor) {
  7232. return [{
  7233. label: 'the link group',
  7234. items: [sketch$6({
  7235. fields: [
  7236. field$2('url', 'Type or paste URL'),
  7237. field$2('text', 'Link text'),
  7238. field$2('title', 'Link title'),
  7239. field$2('target', 'Link target'),
  7240. hidden('link')
  7241. ],
  7242. maxFieldIndex: [
  7243. 'url',
  7244. 'text',
  7245. 'title',
  7246. 'target'
  7247. ].length - 1,
  7248. getInitialValue: function () {
  7249. return Option.some(LinkBridge.getInfo(editor));
  7250. },
  7251. onExecute: function (dialog) {
  7252. var info = Representing.getValue(dialog);
  7253. LinkBridge.applyInfo(editor, info);
  7254. realm.restoreToolbar();
  7255. editor.focus();
  7256. }
  7257. })]
  7258. }];
  7259. });
  7260. var sketch$7 = function (realm, editor) {
  7261. return Buttons.forToolbarStateAction(editor, 'link', 'link', function () {
  7262. var groups = getGroups(realm, editor);
  7263. realm.setContextToolbar(groups);
  7264. RangePreserver.forAndroid(editor, function () {
  7265. realm.focusToolbar();
  7266. });
  7267. LinkBridge.query(editor).each(function (link) {
  7268. editor.selection.select(link.dom());
  7269. });
  7270. });
  7271. };
  7272. var DefaultStyleFormats = [
  7273. {
  7274. title: 'Headings',
  7275. items: [
  7276. {
  7277. title: 'Heading 1',
  7278. format: 'h1'
  7279. },
  7280. {
  7281. title: 'Heading 2',
  7282. format: 'h2'
  7283. },
  7284. {
  7285. title: 'Heading 3',
  7286. format: 'h3'
  7287. },
  7288. {
  7289. title: 'Heading 4',
  7290. format: 'h4'
  7291. },
  7292. {
  7293. title: 'Heading 5',
  7294. format: 'h5'
  7295. },
  7296. {
  7297. title: 'Heading 6',
  7298. format: 'h6'
  7299. }
  7300. ]
  7301. },
  7302. {
  7303. title: 'Inline',
  7304. items: [
  7305. {
  7306. title: 'Bold',
  7307. icon: 'bold',
  7308. format: 'bold'
  7309. },
  7310. {
  7311. title: 'Italic',
  7312. icon: 'italic',
  7313. format: 'italic'
  7314. },
  7315. {
  7316. title: 'Underline',
  7317. icon: 'underline',
  7318. format: 'underline'
  7319. },
  7320. {
  7321. title: 'Strikethrough',
  7322. icon: 'strikethrough',
  7323. format: 'strikethrough'
  7324. },
  7325. {
  7326. title: 'Superscript',
  7327. icon: 'superscript',
  7328. format: 'superscript'
  7329. },
  7330. {
  7331. title: 'Subscript',
  7332. icon: 'subscript',
  7333. format: 'subscript'
  7334. },
  7335. {
  7336. title: 'Code',
  7337. icon: 'code',
  7338. format: 'code'
  7339. }
  7340. ]
  7341. },
  7342. {
  7343. title: 'Blocks',
  7344. items: [
  7345. {
  7346. title: 'Paragraph',
  7347. format: 'p'
  7348. },
  7349. {
  7350. title: 'Blockquote',
  7351. format: 'blockquote'
  7352. },
  7353. {
  7354. title: 'Div',
  7355. format: 'div'
  7356. },
  7357. {
  7358. title: 'Pre',
  7359. format: 'pre'
  7360. }
  7361. ]
  7362. },
  7363. {
  7364. title: 'Alignment',
  7365. items: [
  7366. {
  7367. title: 'Left',
  7368. icon: 'alignleft',
  7369. format: 'alignleft'
  7370. },
  7371. {
  7372. title: 'Center',
  7373. icon: 'aligncenter',
  7374. format: 'aligncenter'
  7375. },
  7376. {
  7377. title: 'Right',
  7378. icon: 'alignright',
  7379. format: 'alignright'
  7380. },
  7381. {
  7382. title: 'Justify',
  7383. icon: 'alignjustify',
  7384. format: 'alignjustify'
  7385. }
  7386. ]
  7387. }
  7388. ];
  7389. var isRecursive = function (component, originator, target) {
  7390. return eq(originator, component.element()) && !eq(originator, target);
  7391. };
  7392. var events$8 = derive([can(focus(), function (component, simulatedEvent) {
  7393. var originator = simulatedEvent.event().originator();
  7394. var target = simulatedEvent.event().target();
  7395. if (isRecursive(component, originator, target)) {
  7396. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  7397. return false;
  7398. } else {
  7399. return true;
  7400. }
  7401. })]);
  7402. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7403. events: events$8
  7404. });
  7405. var make$1 = identity;
  7406. var NoContextApi = function (getComp) {
  7407. var fail = function (event) {
  7408. return function () {
  7409. throw new Error('The component must be in a context to send: ' + event + '\n' + element(getComp().element()) + ' is not in context.');
  7410. };
  7411. };
  7412. return {
  7413. debugInfo: constant('fake'),
  7414. triggerEvent: fail('triggerEvent'),
  7415. triggerFocus: fail('triggerFocus'),
  7416. triggerEscape: fail('triggerEscape'),
  7417. build: fail('build'),
  7418. addToWorld: fail('addToWorld'),
  7419. removeFromWorld: fail('removeFromWorld'),
  7420. addToGui: fail('addToGui'),
  7421. removeFromGui: fail('removeFromGui'),
  7422. getByUid: fail('getByUid'),
  7423. getByDom: fail('getByDom'),
  7424. broadcast: fail('broadcast'),
  7425. broadcastOn: fail('broadcastOn'),
  7426. broadcastEvent: fail('broadcastEvent'),
  7427. isConnected: constant(false)
  7428. };
  7429. };
  7430. var singleton = NoContextApi();
  7431. var generateFrom = function (spec, all) {
  7432. var schema = map$1(all, function (a) {
  7433. return optionObjOf(a.name(), [
  7434. strict$1('config'),
  7435. defaulted$1('state', NoState)
  7436. ]);
  7437. });
  7438. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7439. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7440. }, function (v) {
  7441. return v;
  7442. });
  7443. return {
  7444. list: all,
  7445. data: map(validated, function (optBlobThunk) {
  7446. var optBlob = optBlobThunk;
  7447. var output = optBlob.map(function (blob) {
  7448. return {
  7449. config: blob.config,
  7450. state: blob.state.init(blob.config)
  7451. };
  7452. });
  7453. return function () {
  7454. return output;
  7455. };
  7456. })
  7457. };
  7458. };
  7459. var getBehaviours = function (bData) {
  7460. return bData.list;
  7461. };
  7462. var getData = function (bData) {
  7463. return bData.data;
  7464. };
  7465. var byInnerKey = function (data, tuple) {
  7466. var r = {};
  7467. each(data, function (detail, key) {
  7468. each(detail, function (value, indexKey) {
  7469. var chain = readOr$1(indexKey, [])(r);
  7470. r[indexKey] = chain.concat([tuple(key, value)]);
  7471. });
  7472. });
  7473. return r;
  7474. };
  7475. var combine$1 = function (info, baseMod, behaviours, base) {
  7476. var modsByBehaviour = __assign({}, baseMod);
  7477. each$1(behaviours, function (behaviour) {
  7478. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7479. });
  7480. var nameAndMod = function (name, modification) {
  7481. return {
  7482. name: name,
  7483. modification: modification
  7484. };
  7485. };
  7486. var byAspect = byInnerKey(modsByBehaviour, nameAndMod);
  7487. var combineObjects = function (objects) {
  7488. return foldr(objects, function (b, a) {
  7489. return __assign(__assign({}, a.modification), b);
  7490. }, {});
  7491. };
  7492. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7493. return a.modification.concat(b);
  7494. }, []);
  7495. var combinedAttributes = combineObjects(byAspect.attributes);
  7496. var combinedStyles = combineObjects(byAspect.styles);
  7497. return nu$5({
  7498. classes: combinedClasses,
  7499. attributes: combinedAttributes,
  7500. styles: combinedStyles
  7501. });
  7502. };
  7503. var sortKeys = function (label, keyName, array, order) {
  7504. var sliced = array.slice(0);
  7505. try {
  7506. var sorted = sliced.sort(function (a, b) {
  7507. var aKey = a[keyName]();
  7508. var bKey = b[keyName]();
  7509. var aIndex = order.indexOf(aKey);
  7510. var bIndex = order.indexOf(bKey);
  7511. if (aIndex === -1) {
  7512. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7513. }
  7514. if (bIndex === -1) {
  7515. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7516. }
  7517. if (aIndex < bIndex) {
  7518. return -1;
  7519. } else if (bIndex < aIndex) {
  7520. return 1;
  7521. } else {
  7522. return 0;
  7523. }
  7524. });
  7525. return Result.value(sorted);
  7526. } catch (err) {
  7527. return Result.error([err]);
  7528. }
  7529. };
  7530. var uncurried = function (handler, purpose) {
  7531. return {
  7532. handler: handler,
  7533. purpose: constant(purpose)
  7534. };
  7535. };
  7536. var curried = function (handler, purpose) {
  7537. return {
  7538. cHandler: handler,
  7539. purpose: constant(purpose)
  7540. };
  7541. };
  7542. var curryArgs = function (descHandler, extraArgs) {
  7543. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  7544. };
  7545. var getCurried = function (descHandler) {
  7546. return descHandler.cHandler;
  7547. };
  7548. var behaviourTuple = function (name, handler) {
  7549. return {
  7550. name: constant(name),
  7551. handler: constant(handler)
  7552. };
  7553. };
  7554. var nameToHandlers = function (behaviours, info) {
  7555. var r = {};
  7556. each$1(behaviours, function (behaviour) {
  7557. r[behaviour.name()] = behaviour.handlers(info);
  7558. });
  7559. return r;
  7560. };
  7561. var groupByEvents = function (info, behaviours, base) {
  7562. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7563. return byInnerKey(behaviourEvents, behaviourTuple);
  7564. };
  7565. var combine$2 = function (info, eventOrder, behaviours, base) {
  7566. var byEventName = groupByEvents(info, behaviours, base);
  7567. return combineGroups(byEventName, eventOrder);
  7568. };
  7569. var assemble = function (rawHandler) {
  7570. var handler = read(rawHandler);
  7571. return function (component, simulatedEvent) {
  7572. var rest = [];
  7573. for (var _i = 2; _i < arguments.length; _i++) {
  7574. rest[_i - 2] = arguments[_i];
  7575. }
  7576. var args = [
  7577. component,
  7578. simulatedEvent
  7579. ].concat(rest);
  7580. if (handler.abort.apply(undefined, args)) {
  7581. simulatedEvent.stop();
  7582. } else if (handler.can.apply(undefined, args)) {
  7583. handler.run.apply(undefined, args);
  7584. }
  7585. };
  7586. };
  7587. var missingOrderError = function (eventName, tuples) {
  7588. 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) {
  7589. return c.name();
  7590. }), null, 2)]);
  7591. };
  7592. var fuse$1 = function (tuples, eventOrder, eventName) {
  7593. var order = eventOrder[eventName];
  7594. if (!order) {
  7595. return missingOrderError(eventName, tuples);
  7596. } else {
  7597. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7598. var handlers = map$1(sortedTuples, function (tuple) {
  7599. return tuple.handler();
  7600. });
  7601. return fuse(handlers);
  7602. });
  7603. }
  7604. };
  7605. var combineGroups = function (byEventName, eventOrder) {
  7606. var r = mapToArray(byEventName, function (tuples, eventName) {
  7607. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  7608. return combined.map(function (handler) {
  7609. var assembled = assemble(handler);
  7610. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  7611. return exists(tuples, function (t) {
  7612. return t.name() === o;
  7613. });
  7614. }).join(' > ') : tuples[0].name();
  7615. return wrap$1(eventName, uncurried(assembled, purpose));
  7616. });
  7617. });
  7618. return consolidate(r, {});
  7619. };
  7620. var toInfo = function (spec) {
  7621. return asRaw('custom.definition', objOf([
  7622. field('dom', 'dom', strict(), objOf([
  7623. strict$1('tag'),
  7624. defaulted$1('styles', {}),
  7625. defaulted$1('classes', []),
  7626. defaulted$1('attributes', {}),
  7627. option('value'),
  7628. option('innerHtml')
  7629. ])),
  7630. strict$1('components'),
  7631. strict$1('uid'),
  7632. defaulted$1('events', {}),
  7633. defaulted$1('apis', {}),
  7634. field('eventOrder', 'eventOrder', mergeWith({
  7635. 'alloy.execute': [
  7636. 'disabling',
  7637. 'alloy.base.behaviour',
  7638. 'toggling',
  7639. 'typeaheadevents'
  7640. ],
  7641. 'alloy.focus': [
  7642. 'alloy.base.behaviour',
  7643. 'focusing',
  7644. 'keying'
  7645. ],
  7646. 'alloy.system.init': [
  7647. 'alloy.base.behaviour',
  7648. 'disabling',
  7649. 'toggling',
  7650. 'representing'
  7651. ],
  7652. 'input': [
  7653. 'alloy.base.behaviour',
  7654. 'representing',
  7655. 'streaming',
  7656. 'invalidating'
  7657. ],
  7658. 'alloy.system.detached': [
  7659. 'alloy.base.behaviour',
  7660. 'representing',
  7661. 'item-events',
  7662. 'tooltipping'
  7663. ],
  7664. 'mousedown': [
  7665. 'focusing',
  7666. 'alloy.base.behaviour',
  7667. 'item-type-events'
  7668. ],
  7669. 'mouseover': [
  7670. 'item-type-events',
  7671. 'tooltipping'
  7672. ]
  7673. }), anyValue$1()),
  7674. option('domModification')
  7675. ]), spec);
  7676. };
  7677. var toDefinition = function (detail) {
  7678. return __assign(__assign({}, detail.dom), {
  7679. uid: detail.uid,
  7680. domChildren: map$1(detail.components, function (comp) {
  7681. return comp.element();
  7682. })
  7683. });
  7684. };
  7685. var toModification = function (detail) {
  7686. return detail.domModification.fold(function () {
  7687. return nu$5({});
  7688. }, nu$5);
  7689. };
  7690. var toEvents = function (info) {
  7691. return info.events;
  7692. };
  7693. var add$3 = function (element, classes) {
  7694. each$1(classes, function (x) {
  7695. add$2(element, x);
  7696. });
  7697. };
  7698. var remove$6 = function (element, classes) {
  7699. each$1(classes, function (x) {
  7700. remove$4(element, x);
  7701. });
  7702. };
  7703. var renderToDom = function (definition) {
  7704. var subject = Element.fromTag(definition.tag);
  7705. setAll(subject, definition.attributes);
  7706. add$3(subject, definition.classes);
  7707. setAll$1(subject, definition.styles);
  7708. definition.innerHtml.each(function (html) {
  7709. return set$1(subject, html);
  7710. });
  7711. var children = definition.domChildren;
  7712. append$1(subject, children);
  7713. definition.value.each(function (value) {
  7714. set$6(subject, value);
  7715. });
  7716. if (!definition.uid) {
  7717. debugger;
  7718. }
  7719. writeOnly(subject, definition.uid);
  7720. return subject;
  7721. };
  7722. var getBehaviours$1 = function (spec) {
  7723. var behaviours = readOr$1('behaviours', {})(spec);
  7724. var keys$1 = filter(keys(behaviours), function (k) {
  7725. return behaviours[k] !== undefined;
  7726. });
  7727. return map$1(keys$1, function (k) {
  7728. return behaviours[k].me;
  7729. });
  7730. };
  7731. var generateFrom$1 = function (spec, all) {
  7732. return generateFrom(spec, all);
  7733. };
  7734. var generate$4 = function (spec) {
  7735. var all = getBehaviours$1(spec);
  7736. return generateFrom$1(spec, all);
  7737. };
  7738. var getDomDefinition = function (info, bList, bData) {
  7739. var definition = toDefinition(info);
  7740. var infoModification = toModification(info);
  7741. var baseModification = { 'alloy.base.modification': infoModification };
  7742. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7743. return merge$1(definition, modification);
  7744. };
  7745. var getEvents = function (info, bList, bData) {
  7746. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7747. return combine$2(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7748. };
  7749. var build = function (spec) {
  7750. var getMe = function () {
  7751. return me;
  7752. };
  7753. var systemApi = Cell(singleton);
  7754. var info = getOrDie(toInfo(spec));
  7755. var bBlob = generate$4(spec);
  7756. var bList = getBehaviours(bBlob);
  7757. var bData = getData(bBlob);
  7758. var modDefinition = getDomDefinition(info, bList, bData);
  7759. var item = renderToDom(modDefinition);
  7760. var events = getEvents(info, bList, bData);
  7761. var subcomponents = Cell(info.components);
  7762. var connect = function (newApi) {
  7763. systemApi.set(newApi);
  7764. };
  7765. var disconnect = function () {
  7766. systemApi.set(NoContextApi(getMe));
  7767. };
  7768. var syncComponents = function () {
  7769. var children$1 = children(item);
  7770. var subs = bind(children$1, function (child) {
  7771. return systemApi.get().getByDom(child).fold(function () {
  7772. return [];
  7773. }, function (c) {
  7774. return [c];
  7775. });
  7776. });
  7777. subcomponents.set(subs);
  7778. };
  7779. var config = function (behaviour) {
  7780. var b = bData;
  7781. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7782. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7783. };
  7784. return f();
  7785. };
  7786. var hasConfigured = function (behaviour) {
  7787. return isFunction(bData[behaviour.name()]);
  7788. };
  7789. var getApis = function () {
  7790. return info.apis;
  7791. };
  7792. var readState = function (behaviourName) {
  7793. return bData[behaviourName]().map(function (b) {
  7794. return b.state.readState();
  7795. }).getOr('not enabled');
  7796. };
  7797. var me = {
  7798. getSystem: systemApi.get,
  7799. config: config,
  7800. hasConfigured: hasConfigured,
  7801. spec: constant(spec),
  7802. readState: readState,
  7803. getApis: getApis,
  7804. connect: connect,
  7805. disconnect: disconnect,
  7806. element: constant(item),
  7807. syncComponents: syncComponents,
  7808. components: subcomponents.get,
  7809. events: constant(events)
  7810. };
  7811. return me;
  7812. };
  7813. var buildSubcomponents = function (spec) {
  7814. var components = readOr$1('components', [])(spec);
  7815. return map$1(components, build$1);
  7816. };
  7817. var buildFromSpec = function (userSpec) {
  7818. var _a = make$1(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7819. var components = buildSubcomponents(spec);
  7820. var completeSpec = __assign(__assign({}, spec), {
  7821. events: __assign(__assign({}, DefaultEvents), specEvents),
  7822. components: components
  7823. });
  7824. return Result.value(build(completeSpec));
  7825. };
  7826. var text = function (textContent) {
  7827. var element = Element.fromText(textContent);
  7828. return external({ element: element });
  7829. };
  7830. var external = function (spec) {
  7831. var extSpec = asRawOrDie('external.component', objOfOnly([
  7832. strict$1('element'),
  7833. option('uid')
  7834. ]), spec);
  7835. var systemApi = Cell(NoContextApi());
  7836. var connect = function (newApi) {
  7837. systemApi.set(newApi);
  7838. };
  7839. var disconnect = function () {
  7840. systemApi.set(NoContextApi(function () {
  7841. return me;
  7842. }));
  7843. };
  7844. extSpec.uid.each(function (uid) {
  7845. writeOnly(extSpec.element, uid);
  7846. });
  7847. var me = {
  7848. getSystem: systemApi.get,
  7849. config: Option.none,
  7850. hasConfigured: constant(false),
  7851. connect: connect,
  7852. disconnect: disconnect,
  7853. getApis: function () {
  7854. return {};
  7855. },
  7856. element: constant(extSpec.element),
  7857. spec: constant(spec),
  7858. readState: constant('No state'),
  7859. syncComponents: noop,
  7860. components: constant([]),
  7861. events: constant({})
  7862. };
  7863. return premade(me);
  7864. };
  7865. var uids = generate$3;
  7866. var build$1 = function (spec) {
  7867. return getPremade(spec).fold(function () {
  7868. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  7869. return buildFromSpec(userSpecWithUid).getOrDie();
  7870. }, function (prebuilt) {
  7871. return prebuilt;
  7872. });
  7873. };
  7874. var premade$1 = premade;
  7875. var hoverEvent = 'alloy.item-hover';
  7876. var focusEvent = 'alloy.item-focus';
  7877. var onHover = function (item) {
  7878. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  7879. if (!Focusing.isFocused(item)) {
  7880. Focusing.focus(item);
  7881. }
  7882. emitWith(item, hoverEvent, { item: item });
  7883. }
  7884. };
  7885. var onFocus = function (item) {
  7886. emitWith(item, focusEvent, { item: item });
  7887. };
  7888. var hover = constant(hoverEvent);
  7889. var focus$3 = constant(focusEvent);
  7890. var builder = function (detail) {
  7891. return {
  7892. dom: detail.dom,
  7893. domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem' }, detail.domModification.attributes), { 'aria-haspopup': detail.hasSubmenu }), detail.hasSubmenu ? { 'aria-expanded': false } : {}) }),
  7894. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7895. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7896. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7897. }),
  7898. Focusing.config({
  7899. ignore: detail.ignoreFocus,
  7900. stopMousedown: detail.ignoreFocus,
  7901. onFocus: function (component) {
  7902. onFocus(component);
  7903. }
  7904. }),
  7905. Keying.config({ mode: 'execution' }),
  7906. Representing.config({
  7907. store: {
  7908. mode: 'memory',
  7909. initialValue: detail.data
  7910. }
  7911. }),
  7912. config('item-type-events', [
  7913. run(tapOrClick(), emitExecute),
  7914. cutter(mousedown()),
  7915. run(mouseover(), onHover),
  7916. run(focusItem(), Focusing.focus)
  7917. ])
  7918. ]),
  7919. components: detail.components,
  7920. eventOrder: detail.eventOrder
  7921. };
  7922. };
  7923. var schema$a = [
  7924. strict$1('data'),
  7925. strict$1('components'),
  7926. strict$1('dom'),
  7927. defaulted$1('hasSubmenu', false),
  7928. option('toggling'),
  7929. SketchBehaviours.field('itemBehaviours', [
  7930. Toggling,
  7931. Focusing,
  7932. Keying,
  7933. Representing
  7934. ]),
  7935. defaulted$1('ignoreFocus', false),
  7936. defaulted$1('domModification', {}),
  7937. output('builder', builder),
  7938. defaulted$1('eventOrder', {})
  7939. ];
  7940. var builder$1 = function (detail) {
  7941. return {
  7942. dom: detail.dom,
  7943. components: detail.components,
  7944. events: derive([stopper(focusItem())])
  7945. };
  7946. };
  7947. var schema$b = [
  7948. strict$1('dom'),
  7949. strict$1('components'),
  7950. output('builder', builder$1)
  7951. ];
  7952. var owner$2 = function () {
  7953. return 'item-widget';
  7954. };
  7955. var parts = constant([required({
  7956. name: 'widget',
  7957. overrides: function (detail) {
  7958. return {
  7959. behaviours: derive$1([Representing.config({
  7960. store: {
  7961. mode: 'manual',
  7962. getValue: function (component) {
  7963. return detail.data;
  7964. },
  7965. setValue: function () {
  7966. }
  7967. }
  7968. })])
  7969. };
  7970. }
  7971. })]);
  7972. var builder$2 = function (detail) {
  7973. var subs = substitutes(owner$2(), detail, parts());
  7974. var components$1 = components(owner$2(), detail, subs.internals());
  7975. var focusWidget = function (component) {
  7976. return getPart(component, detail, 'widget').map(function (widget) {
  7977. Keying.focusIn(widget);
  7978. return widget;
  7979. });
  7980. };
  7981. var onHorizontalArrow = function (component, simulatedEvent) {
  7982. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  7983. if (detail.autofocus) {
  7984. simulatedEvent.setSource(component.element());
  7985. return Option.none();
  7986. } else {
  7987. return Option.none();
  7988. }
  7989. }();
  7990. };
  7991. return {
  7992. dom: detail.dom,
  7993. components: components$1,
  7994. domModification: detail.domModification,
  7995. events: derive([
  7996. runOnExecute(function (component, simulatedEvent) {
  7997. focusWidget(component).each(function (widget) {
  7998. simulatedEvent.stop();
  7999. });
  8000. }),
  8001. run(mouseover(), onHover),
  8002. run(focusItem(), function (component, simulatedEvent) {
  8003. if (detail.autofocus) {
  8004. focusWidget(component);
  8005. } else {
  8006. Focusing.focus(component);
  8007. }
  8008. })
  8009. ]),
  8010. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  8011. Representing.config({
  8012. store: {
  8013. mode: 'memory',
  8014. initialValue: detail.data
  8015. }
  8016. }),
  8017. Focusing.config({
  8018. ignore: detail.ignoreFocus,
  8019. onFocus: function (component) {
  8020. onFocus(component);
  8021. }
  8022. }),
  8023. Keying.config({
  8024. mode: 'special',
  8025. focusIn: detail.autofocus ? function (component) {
  8026. focusWidget(component);
  8027. } : revoke(),
  8028. onLeft: onHorizontalArrow,
  8029. onRight: onHorizontalArrow,
  8030. onEscape: function (component, simulatedEvent) {
  8031. if (!Focusing.isFocused(component) && !detail.autofocus) {
  8032. Focusing.focus(component);
  8033. return Option.some(true);
  8034. } else if (detail.autofocus) {
  8035. simulatedEvent.setSource(component.element());
  8036. return Option.none();
  8037. } else {
  8038. return Option.none();
  8039. }
  8040. }
  8041. })
  8042. ])
  8043. };
  8044. };
  8045. var schema$c = [
  8046. strict$1('uid'),
  8047. strict$1('data'),
  8048. strict$1('components'),
  8049. strict$1('dom'),
  8050. defaulted$1('autofocus', false),
  8051. defaulted$1('ignoreFocus', false),
  8052. SketchBehaviours.field('widgetBehaviours', [
  8053. Representing,
  8054. Focusing,
  8055. Keying
  8056. ]),
  8057. defaulted$1('domModification', {}),
  8058. defaultUidsSchema(parts()),
  8059. output('builder', builder$2)
  8060. ];
  8061. var itemSchema$1 = choose$1('type', {
  8062. widget: schema$c,
  8063. item: schema$a,
  8064. separator: schema$b
  8065. });
  8066. var configureGrid = function (detail, movementInfo) {
  8067. return {
  8068. mode: 'flatgrid',
  8069. selector: '.' + detail.markers.item,
  8070. initSize: {
  8071. numColumns: movementInfo.initSize.numColumns,
  8072. numRows: movementInfo.initSize.numRows
  8073. },
  8074. focusManager: detail.focusManager
  8075. };
  8076. };
  8077. var configureMatrix = function (detail, movementInfo) {
  8078. return {
  8079. mode: 'matrix',
  8080. selectors: {
  8081. row: movementInfo.rowSelector,
  8082. cell: '.' + detail.markers.item
  8083. },
  8084. focusManager: detail.focusManager
  8085. };
  8086. };
  8087. var configureMenu = function (detail, movementInfo) {
  8088. return {
  8089. mode: 'menu',
  8090. selector: '.' + detail.markers.item,
  8091. moveOnTab: movementInfo.moveOnTab,
  8092. focusManager: detail.focusManager
  8093. };
  8094. };
  8095. var parts$1 = constant([group({
  8096. factory: {
  8097. sketch: function (spec) {
  8098. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  8099. return itemInfo.builder(itemInfo);
  8100. }
  8101. },
  8102. name: 'items',
  8103. unit: 'item',
  8104. defaults: function (detail, u) {
  8105. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$3('item') });
  8106. },
  8107. overrides: function (detail, u) {
  8108. return {
  8109. type: u.type,
  8110. ignoreFocus: detail.fakeFocus,
  8111. domModification: { classes: [detail.markers.item] }
  8112. };
  8113. }
  8114. })]);
  8115. var schema$d = constant([
  8116. strict$1('value'),
  8117. strict$1('items'),
  8118. strict$1('dom'),
  8119. strict$1('components'),
  8120. defaulted$1('eventOrder', {}),
  8121. field$1('menuBehaviours', [
  8122. Highlighting,
  8123. Representing,
  8124. Composing,
  8125. Keying
  8126. ]),
  8127. defaultedOf('movement', {
  8128. mode: 'menu',
  8129. moveOnTab: true
  8130. }, choose$1('mode', {
  8131. grid: [
  8132. initSize(),
  8133. output('config', configureGrid)
  8134. ],
  8135. matrix: [
  8136. output('config', configureMatrix),
  8137. strict$1('rowSelector')
  8138. ],
  8139. menu: [
  8140. defaulted$1('moveOnTab', true),
  8141. output('config', configureMenu)
  8142. ]
  8143. })),
  8144. itemMarkers(),
  8145. defaulted$1('fakeFocus', false),
  8146. defaulted$1('focusManager', dom()),
  8147. onHandler('onHighlight')
  8148. ]);
  8149. var focus$4 = constant('alloy.menu-focus');
  8150. var make$2 = function (detail, components, spec, externals) {
  8151. return {
  8152. uid: detail.uid,
  8153. dom: detail.dom,
  8154. markers: detail.markers,
  8155. behaviours: augment(detail.menuBehaviours, [
  8156. Highlighting.config({
  8157. highlightClass: detail.markers.selectedItem,
  8158. itemClass: detail.markers.item,
  8159. onHighlight: detail.onHighlight
  8160. }),
  8161. Representing.config({
  8162. store: {
  8163. mode: 'memory',
  8164. initialValue: detail.value
  8165. }
  8166. }),
  8167. Composing.config({ find: Option.some }),
  8168. Keying.config(detail.movement.config(detail, detail.movement))
  8169. ]),
  8170. events: derive([
  8171. run(focus$3(), function (menu, simulatedEvent) {
  8172. var event = simulatedEvent.event();
  8173. menu.getSystem().getByDom(event.target()).each(function (item) {
  8174. Highlighting.highlight(menu, item);
  8175. simulatedEvent.stop();
  8176. emitWith(menu, focus$4(), {
  8177. menu: menu,
  8178. item: item
  8179. });
  8180. });
  8181. }),
  8182. run(hover(), function (menu, simulatedEvent) {
  8183. var item = simulatedEvent.event().item();
  8184. Highlighting.highlight(menu, item);
  8185. })
  8186. ]),
  8187. components: components,
  8188. eventOrder: detail.eventOrder,
  8189. domModification: { attributes: { role: 'menu' } }
  8190. };
  8191. };
  8192. var Menu = composite$1({
  8193. name: 'Menu',
  8194. configFields: schema$d(),
  8195. partFields: parts$1(),
  8196. factory: make$2
  8197. });
  8198. var preserve$1 = function (f, container) {
  8199. var ownerDoc = owner(container);
  8200. var refocus = active(ownerDoc).bind(function (focused) {
  8201. var hasFocus = function (elem) {
  8202. return eq(focused, elem);
  8203. };
  8204. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  8205. });
  8206. var result = f(container);
  8207. refocus.each(function (oldFocus) {
  8208. active(ownerDoc).filter(function (newFocus) {
  8209. return eq(newFocus, oldFocus);
  8210. }).fold(function () {
  8211. focus$1(oldFocus);
  8212. }, noop);
  8213. });
  8214. return result;
  8215. };
  8216. var set$8 = function (component, replaceConfig, replaceState, data) {
  8217. preserve$1(function () {
  8218. var newChildren = map$1(data, component.getSystem().build);
  8219. replaceChildren(component, newChildren);
  8220. }, component.element());
  8221. };
  8222. var insert = function (component, replaceConfig, insertion, childSpec) {
  8223. var child = component.getSystem().build(childSpec);
  8224. attachWith(component, child, insertion);
  8225. };
  8226. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  8227. insert(component, replaceConfig, append, appendee);
  8228. };
  8229. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  8230. insert(component, replaceConfig, prepend, prependee);
  8231. };
  8232. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  8233. var children = contents(component);
  8234. var foundChild = find$2(children, function (child) {
  8235. return eq(removee.element(), child.element());
  8236. });
  8237. foundChild.each(detach);
  8238. };
  8239. var contents = function (component, replaceConfig) {
  8240. return component.components();
  8241. };
  8242. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8243. var children = contents(component);
  8244. return Option.from(children[replaceeIndex]).map(function (replacee) {
  8245. remove$7(component, replaceConfig, replaceState, replacee);
  8246. replacer.each(function (r) {
  8247. insert(component, replaceConfig, function (p, c) {
  8248. appendAt(p, c, replaceeIndex);
  8249. }, r);
  8250. });
  8251. return replacee;
  8252. });
  8253. };
  8254. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8255. var children = contents(component);
  8256. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  8257. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8258. });
  8259. };
  8260. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8261. append: append$2,
  8262. prepend: prepend$1,
  8263. remove: remove$7,
  8264. replaceAt: replaceAt,
  8265. replaceBy: replaceBy,
  8266. set: set$8,
  8267. contents: contents
  8268. });
  8269. var Replacing = create$1({
  8270. fields: [],
  8271. name: 'replacing',
  8272. apis: ReplaceApis
  8273. });
  8274. var transpose = function (obj) {
  8275. return tupleMap(obj, function (v, k) {
  8276. return {
  8277. k: v,
  8278. v: k
  8279. };
  8280. });
  8281. };
  8282. var trace = function (items, byItem, byMenu, finish) {
  8283. return readOptFrom$1(byMenu, finish).bind(function (triggerItem) {
  8284. return readOptFrom$1(items, triggerItem).bind(function (triggerMenu) {
  8285. var rest = trace(items, byItem, byMenu, triggerMenu);
  8286. return Option.some([triggerMenu].concat(rest));
  8287. });
  8288. }).getOr([]);
  8289. };
  8290. var generate$5 = function (menus, expansions) {
  8291. var items = {};
  8292. each(menus, function (menuItems, menu) {
  8293. each$1(menuItems, function (item) {
  8294. items[item] = menu;
  8295. });
  8296. });
  8297. var byItem = expansions;
  8298. var byMenu = transpose(expansions);
  8299. var menuPaths = map(byMenu, function (_triggerItem, submenu) {
  8300. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8301. });
  8302. return map(items, function (menu) {
  8303. return readOptFrom$1(menuPaths, menu).getOr([menu]);
  8304. });
  8305. };
  8306. var init$3 = function () {
  8307. var expansions = Cell({});
  8308. var menus = Cell({});
  8309. var paths = Cell({});
  8310. var primary = Cell(Option.none());
  8311. var directory = Cell({});
  8312. var clear = function () {
  8313. expansions.set({});
  8314. menus.set({});
  8315. paths.set({});
  8316. primary.set(Option.none());
  8317. };
  8318. var isClear = function () {
  8319. return primary.get().isNone();
  8320. };
  8321. var setMenuBuilt = function (menuName, built) {
  8322. var _a;
  8323. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8324. type: 'prepared',
  8325. menu: built
  8326. }, _a)));
  8327. };
  8328. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8329. primary.set(Option.some(sPrimary));
  8330. expansions.set(sExpansions);
  8331. menus.set(sMenus);
  8332. directory.set(dir);
  8333. var sPaths = generate$5(dir, sExpansions);
  8334. paths.set(sPaths);
  8335. };
  8336. var getTriggeringItem = function (menuValue) {
  8337. return find(expansions.get(), function (v, k) {
  8338. return v === menuValue;
  8339. });
  8340. };
  8341. var getTriggerData = function (menuValue, getItemByValue, path) {
  8342. return getPreparedMenu(menuValue).bind(function (menu) {
  8343. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8344. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8345. return {
  8346. triggeredMenu: menu,
  8347. triggeringItem: triggeredItem,
  8348. triggeringPath: path
  8349. };
  8350. });
  8351. });
  8352. });
  8353. };
  8354. var getTriggeringPath = function (itemValue, getItemByValue) {
  8355. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  8356. return getPreparedMenu(menuValue).isSome();
  8357. });
  8358. return readOptFrom$1(paths.get(), itemValue).bind(function (path) {
  8359. var revPath = reverse(extraPath.concat(path));
  8360. var triggers = bind(revPath, function (menuValue, menuIndex) {
  8361. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8362. return primary.get().is(menuValue) ? [] : [Option.none()];
  8363. }, function (data) {
  8364. return [Option.some(data)];
  8365. });
  8366. });
  8367. return sequence(triggers);
  8368. });
  8369. };
  8370. var expand = function (itemValue) {
  8371. return readOptFrom$1(expansions.get(), itemValue).map(function (menu) {
  8372. var current = readOptFrom$1(paths.get(), itemValue).getOr([]);
  8373. return [menu].concat(current);
  8374. });
  8375. };
  8376. var collapse = function (itemValue) {
  8377. return readOptFrom$1(paths.get(), itemValue).bind(function (path) {
  8378. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  8379. });
  8380. };
  8381. var refresh = function (itemValue) {
  8382. return readOptFrom$1(paths.get(), itemValue);
  8383. };
  8384. var getPreparedMenu = function (menuValue) {
  8385. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8386. };
  8387. var lookupMenu = function (menuValue) {
  8388. return readOptFrom$1(menus.get(), menuValue);
  8389. };
  8390. var lookupItem = function (itemValue) {
  8391. return readOptFrom$1(expansions.get(), itemValue);
  8392. };
  8393. var otherMenus = function (path) {
  8394. var menuValues = directory.get();
  8395. return difference(keys(menuValues), path);
  8396. };
  8397. var getPrimary = function () {
  8398. return primary.get().bind(getPreparedMenu);
  8399. };
  8400. var getMenus = function () {
  8401. return menus.get();
  8402. };
  8403. return {
  8404. setMenuBuilt: setMenuBuilt,
  8405. setContents: setContents,
  8406. expand: expand,
  8407. refresh: refresh,
  8408. collapse: collapse,
  8409. lookupMenu: lookupMenu,
  8410. lookupItem: lookupItem,
  8411. otherMenus: otherMenus,
  8412. getPrimary: getPrimary,
  8413. getMenus: getMenus,
  8414. clear: clear,
  8415. isClear: isClear,
  8416. getTriggeringPath: getTriggeringPath
  8417. };
  8418. };
  8419. var extractPreparedMenu = function (prep) {
  8420. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  8421. };
  8422. var LayeredState = {
  8423. init: init$3,
  8424. extractPreparedMenu: extractPreparedMenu
  8425. };
  8426. var make$3 = function (detail, rawUiSpec) {
  8427. var submenuParentItems = Cell(Option.none());
  8428. var buildMenus = function (container, primaryName, menus) {
  8429. return map(menus, function (spec, name) {
  8430. var makeSketch = function () {
  8431. return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), {
  8432. value: name,
  8433. items: spec.items,
  8434. markers: detail.markers,
  8435. fakeFocus: detail.fakeFocus,
  8436. onHighlight: detail.onHighlight,
  8437. focusManager: detail.fakeFocus ? highlights() : dom()
  8438. }));
  8439. };
  8440. return name === primaryName ? {
  8441. type: 'prepared',
  8442. menu: container.getSystem().build(makeSketch())
  8443. } : {
  8444. type: 'notbuilt',
  8445. nbMenu: makeSketch
  8446. };
  8447. });
  8448. };
  8449. var layeredState = LayeredState.init();
  8450. var setup = function (container) {
  8451. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8452. var directory = toDirectory();
  8453. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8454. return layeredState.getPrimary();
  8455. };
  8456. var getItemValue = function (item) {
  8457. return Representing.getValue(item).value;
  8458. };
  8459. var getItemByValue = function (container, menus, itemValue) {
  8460. return findMap(menus, function (menu) {
  8461. if (!menu.getSystem().isConnected()) {
  8462. return Option.none();
  8463. }
  8464. var candidates = Highlighting.getCandidates(menu);
  8465. return find$2(candidates, function (c) {
  8466. return getItemValue(c) === itemValue;
  8467. });
  8468. });
  8469. };
  8470. var toDirectory = function (container) {
  8471. return map(detail.data.menus, function (data, menuName) {
  8472. return bind(data.items, function (item) {
  8473. return item.type === 'separator' ? [] : [item.data.value];
  8474. });
  8475. });
  8476. };
  8477. var setActiveMenu = function (container, menu) {
  8478. Highlighting.highlight(container, menu);
  8479. Highlighting.getHighlighted(menu).orThunk(function () {
  8480. return Highlighting.getFirst(menu);
  8481. }).each(function (item) {
  8482. dispatch(container, item.element(), focusItem());
  8483. });
  8484. };
  8485. var getMenus = function (state, menuValues) {
  8486. return cat(map$1(menuValues, function (mv) {
  8487. return state.lookupMenu(mv).bind(function (prep) {
  8488. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  8489. });
  8490. }));
  8491. };
  8492. var closeOthers = function (container, state, path) {
  8493. var others = getMenus(state, state.otherMenus(path));
  8494. each$1(others, function (o) {
  8495. remove$6(o.element(), [detail.markers.backgroundMenu]);
  8496. if (!detail.stayInDom) {
  8497. Replacing.remove(container, o);
  8498. }
  8499. });
  8500. };
  8501. var getSubmenuParents = function (container) {
  8502. return submenuParentItems.get().getOrThunk(function () {
  8503. var r = {};
  8504. var items = descendants(container.element(), '.' + detail.markers.item);
  8505. var parentItems = filter(items, function (i) {
  8506. return get(i, 'aria-haspopup') === 'true';
  8507. });
  8508. each$1(parentItems, function (i) {
  8509. container.getSystem().getByDom(i).each(function (itemComp) {
  8510. var key = getItemValue(itemComp);
  8511. r[key] = itemComp;
  8512. });
  8513. });
  8514. submenuParentItems.set(Option.some(r));
  8515. return r;
  8516. });
  8517. };
  8518. var updateAriaExpansions = function (container, path) {
  8519. var parentItems = getSubmenuParents(container);
  8520. each(parentItems, function (v, k) {
  8521. var expanded = contains(path, k);
  8522. set(v.element(), 'aria-expanded', expanded);
  8523. });
  8524. };
  8525. var updateMenuPath = function (container, state, path) {
  8526. return Option.from(path[0]).bind(function (latestMenuName) {
  8527. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8528. if (menuPrep.type === 'notbuilt') {
  8529. return Option.none();
  8530. } else {
  8531. var activeMenu = menuPrep.menu;
  8532. var rest = getMenus(state, path.slice(1));
  8533. each$1(rest, function (r) {
  8534. add$2(r.element(), detail.markers.backgroundMenu);
  8535. });
  8536. if (!inBody(activeMenu.element())) {
  8537. Replacing.append(container, premade$1(activeMenu));
  8538. }
  8539. remove$6(activeMenu.element(), [detail.markers.backgroundMenu]);
  8540. setActiveMenu(container, activeMenu);
  8541. closeOthers(container, state, path);
  8542. return Option.some(activeMenu);
  8543. }
  8544. });
  8545. });
  8546. };
  8547. var ExpandHighlightDecision;
  8548. (function (ExpandHighlightDecision) {
  8549. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8550. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8551. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8552. var buildIfRequired = function (container, menuName, menuPrep) {
  8553. if (menuPrep.type === 'notbuilt') {
  8554. var menu = container.getSystem().build(menuPrep.nbMenu());
  8555. layeredState.setMenuBuilt(menuName, menu);
  8556. return menu;
  8557. } else {
  8558. return menuPrep.menu;
  8559. }
  8560. };
  8561. var expandRight = function (container, item, decision) {
  8562. if (decision === void 0) {
  8563. decision = ExpandHighlightDecision.HighlightSubmenu;
  8564. }
  8565. var value = getItemValue(item);
  8566. return layeredState.expand(value).bind(function (path) {
  8567. updateAriaExpansions(container, path);
  8568. return Option.from(path[0]).bind(function (menuName) {
  8569. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8570. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8571. if (!inBody(activeMenu.element())) {
  8572. Replacing.append(container, premade$1(activeMenu));
  8573. }
  8574. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8575. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8576. Highlighting.highlightFirst(activeMenu);
  8577. return updateMenuPath(container, layeredState, path);
  8578. } else {
  8579. Highlighting.dehighlightAll(activeMenu);
  8580. return Option.some(item);
  8581. }
  8582. });
  8583. });
  8584. });
  8585. };
  8586. var collapseLeft = function (container, item) {
  8587. var value = getItemValue(item);
  8588. return layeredState.collapse(value).bind(function (path) {
  8589. updateAriaExpansions(container, path);
  8590. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8591. detail.onCollapseMenu(container, item, activeMenu);
  8592. return activeMenu;
  8593. });
  8594. });
  8595. };
  8596. var updateView = function (container, item) {
  8597. var value = getItemValue(item);
  8598. return layeredState.refresh(value).bind(function (path) {
  8599. updateAriaExpansions(container, path);
  8600. return updateMenuPath(container, layeredState, path);
  8601. });
  8602. };
  8603. var onRight = function (container, item) {
  8604. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8605. };
  8606. var onLeft = function (container, item) {
  8607. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  8608. };
  8609. var onEscape = function (container, item) {
  8610. return collapseLeft(container, item).orThunk(function () {
  8611. return detail.onEscape(container, item).map(function () {
  8612. return container;
  8613. });
  8614. });
  8615. };
  8616. var keyOnItem = function (f) {
  8617. return function (container, simulatedEvent) {
  8618. return closest$2(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8619. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  8620. return f(container, item).map(function () {
  8621. return true;
  8622. });
  8623. });
  8624. });
  8625. };
  8626. };
  8627. var events = derive([
  8628. run(focus$4(), function (sandbox, simulatedEvent) {
  8629. var item = simulatedEvent.event().item();
  8630. layeredState.lookupItem(getItemValue(item)).each(function () {
  8631. var menu = simulatedEvent.event().menu();
  8632. Highlighting.highlight(sandbox, menu);
  8633. var value = getItemValue(simulatedEvent.event().item());
  8634. layeredState.refresh(value).each(function (path) {
  8635. return closeOthers(sandbox, layeredState, path);
  8636. });
  8637. });
  8638. }),
  8639. runOnExecute(function (component, simulatedEvent) {
  8640. var target = simulatedEvent.event().target();
  8641. component.getSystem().getByDom(target).each(function (item) {
  8642. var itemValue = getItemValue(item);
  8643. if (itemValue.indexOf('collapse-item') === 0) {
  8644. collapseLeft(component, item);
  8645. }
  8646. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8647. detail.onExecute(component, item);
  8648. }, function () {
  8649. });
  8650. });
  8651. }),
  8652. runOnAttached(function (container, simulatedEvent) {
  8653. setup(container).each(function (primary) {
  8654. Replacing.append(container, premade$1(primary));
  8655. detail.onOpenMenu(container, primary);
  8656. if (detail.highlightImmediately) {
  8657. setActiveMenu(container, primary);
  8658. }
  8659. });
  8660. })
  8661. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8662. var item = simulatedEvent.event().item();
  8663. updateView(sandbox, item);
  8664. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8665. detail.onHover(sandbox, item);
  8666. })] : []));
  8667. var getActiveItem = function (container) {
  8668. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8669. };
  8670. var collapseMenuApi = function (container) {
  8671. getActiveItem(container).each(function (currentItem) {
  8672. collapseLeft(container, currentItem);
  8673. });
  8674. };
  8675. var highlightPrimary = function (container) {
  8676. layeredState.getPrimary().each(function (primary) {
  8677. setActiveMenu(container, primary);
  8678. });
  8679. };
  8680. var extractMenuFromContainer = function (container) {
  8681. return Option.from(container.components()[0]).filter(function (comp) {
  8682. return get(comp.element(), 'role') === 'menu';
  8683. });
  8684. };
  8685. var repositionMenus = function (container) {
  8686. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8687. return getActiveItem(container).bind(function (currentItem) {
  8688. var itemValue = getItemValue(currentItem);
  8689. var allMenus = values(layeredState.getMenus());
  8690. var preparedMenus = cat(map$1(allMenus, LayeredState.extractPreparedMenu));
  8691. return layeredState.getTriggeringPath(itemValue, function (v) {
  8692. return getItemByValue(container, preparedMenus, v);
  8693. });
  8694. }).map(function (triggeringPath) {
  8695. return {
  8696. primary: primary,
  8697. triggeringPath: triggeringPath
  8698. };
  8699. });
  8700. });
  8701. maybeActivePrimary.fold(function () {
  8702. extractMenuFromContainer(container).each(function (primaryMenu) {
  8703. detail.onRepositionMenu(container, primaryMenu, []);
  8704. });
  8705. }, function (_a) {
  8706. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8707. detail.onRepositionMenu(container, primary, triggeringPath);
  8708. });
  8709. };
  8710. var apis = {
  8711. collapseMenu: collapseMenuApi,
  8712. highlightPrimary: highlightPrimary,
  8713. repositionMenus: repositionMenus
  8714. };
  8715. return {
  8716. uid: detail.uid,
  8717. dom: detail.dom,
  8718. markers: detail.markers,
  8719. behaviours: augment(detail.tmenuBehaviours, [
  8720. Keying.config({
  8721. mode: 'special',
  8722. onRight: keyOnItem(onRight),
  8723. onLeft: keyOnItem(onLeft),
  8724. onEscape: keyOnItem(onEscape),
  8725. focusIn: function (container, keyInfo) {
  8726. layeredState.getPrimary().each(function (primary) {
  8727. dispatch(container, primary.element(), focusItem());
  8728. });
  8729. }
  8730. }),
  8731. Highlighting.config({
  8732. highlightClass: detail.markers.selectedMenu,
  8733. itemClass: detail.markers.menu
  8734. }),
  8735. Composing.config({
  8736. find: function (container) {
  8737. return Highlighting.getHighlighted(container);
  8738. }
  8739. }),
  8740. Replacing.config({})
  8741. ]),
  8742. eventOrder: detail.eventOrder,
  8743. apis: apis,
  8744. events: events
  8745. };
  8746. };
  8747. var collapseItem = constant('collapse-item');
  8748. var tieredData = function (primary, menus, expansions) {
  8749. return {
  8750. primary: primary,
  8751. menus: menus,
  8752. expansions: expansions
  8753. };
  8754. };
  8755. var singleData = function (name, menu) {
  8756. return {
  8757. primary: name,
  8758. menus: wrap$1(name, menu),
  8759. expansions: {}
  8760. };
  8761. };
  8762. var collapseItem$1 = function (text) {
  8763. return {
  8764. value: generate$1(collapseItem()),
  8765. meta: { text: text }
  8766. };
  8767. };
  8768. var tieredMenu = single$2({
  8769. name: 'TieredMenu',
  8770. configFields: [
  8771. onStrictKeyboardHandler('onExecute'),
  8772. onStrictKeyboardHandler('onEscape'),
  8773. onStrictHandler('onOpenMenu'),
  8774. onStrictHandler('onOpenSubmenu'),
  8775. onStrictHandler('onRepositionMenu'),
  8776. onHandler('onCollapseMenu'),
  8777. defaulted$1('highlightImmediately', true),
  8778. strictObjOf('data', [
  8779. strict$1('primary'),
  8780. strict$1('menus'),
  8781. strict$1('expansions')
  8782. ]),
  8783. defaulted$1('fakeFocus', false),
  8784. onHandler('onHighlight'),
  8785. onHandler('onHover'),
  8786. tieredMenuMarkers(),
  8787. strict$1('dom'),
  8788. defaulted$1('navigateOnHover', true),
  8789. defaulted$1('stayInDom', false),
  8790. field$1('tmenuBehaviours', [
  8791. Keying,
  8792. Highlighting,
  8793. Composing,
  8794. Replacing
  8795. ]),
  8796. defaulted$1('eventOrder', {})
  8797. ],
  8798. apis: {
  8799. collapseMenu: function (apis, tmenu) {
  8800. apis.collapseMenu(tmenu);
  8801. },
  8802. highlightPrimary: function (apis, tmenu) {
  8803. apis.highlightPrimary(tmenu);
  8804. },
  8805. repositionMenus: function (apis, tmenu) {
  8806. apis.repositionMenus(tmenu);
  8807. }
  8808. },
  8809. factory: make$3,
  8810. extraApis: {
  8811. tieredData: tieredData,
  8812. singleData: singleData,
  8813. collapseItem: collapseItem$1
  8814. }
  8815. });
  8816. var findRoute = function (component, transConfig, transState, route) {
  8817. return readOptFrom$1(transConfig.routes, route.start).bind(function (sConfig) {
  8818. return readOptFrom$1(sConfig, route.destination);
  8819. });
  8820. };
  8821. var getTransition = function (comp, transConfig, transState) {
  8822. var route = getCurrentRoute(comp, transConfig);
  8823. return route.bind(function (r) {
  8824. return getTransitionOf(comp, transConfig, transState, r);
  8825. });
  8826. };
  8827. var getTransitionOf = function (comp, transConfig, transState, route) {
  8828. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8829. return r.transition.map(function (t) {
  8830. return {
  8831. transition: t,
  8832. route: r
  8833. };
  8834. });
  8835. });
  8836. };
  8837. var disableTransition = function (comp, transConfig, transState) {
  8838. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8839. var t = routeTransition.transition;
  8840. remove$4(comp.element(), t.transitionClass);
  8841. remove$1(comp.element(), transConfig.destinationAttr);
  8842. });
  8843. };
  8844. var getNewRoute = function (comp, transConfig, transState, destination) {
  8845. return {
  8846. start: get(comp.element(), transConfig.stateAttr),
  8847. destination: destination
  8848. };
  8849. };
  8850. var getCurrentRoute = function (comp, transConfig, transState) {
  8851. var el = comp.element();
  8852. return has$1(el, transConfig.destinationAttr) ? Option.some({
  8853. start: get(comp.element(), transConfig.stateAttr),
  8854. destination: get(comp.element(), transConfig.destinationAttr)
  8855. }) : Option.none();
  8856. };
  8857. var jumpTo = function (comp, transConfig, transState, destination) {
  8858. disableTransition(comp, transConfig, transState);
  8859. if (has$1(comp.element(), transConfig.stateAttr) && get(comp.element(), transConfig.stateAttr) !== destination) {
  8860. transConfig.onFinish(comp, destination);
  8861. }
  8862. set(comp.element(), transConfig.stateAttr, destination);
  8863. };
  8864. var fasttrack = function (comp, transConfig, transState, destination) {
  8865. if (has$1(comp.element(), transConfig.destinationAttr)) {
  8866. set(comp.element(), transConfig.stateAttr, get(comp.element(), transConfig.destinationAttr));
  8867. remove$1(comp.element(), transConfig.destinationAttr);
  8868. }
  8869. };
  8870. var progressTo = function (comp, transConfig, transState, destination) {
  8871. fasttrack(comp, transConfig);
  8872. var route = getNewRoute(comp, transConfig, transState, destination);
  8873. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8874. jumpTo(comp, transConfig, transState, destination);
  8875. }, function (routeTransition) {
  8876. disableTransition(comp, transConfig, transState);
  8877. var t = routeTransition.transition;
  8878. add$2(comp.element(), t.transitionClass);
  8879. set(comp.element(), transConfig.destinationAttr, destination);
  8880. });
  8881. };
  8882. var getState$1 = function (comp, transConfig, transState) {
  8883. var e = comp.element();
  8884. return has$1(e, transConfig.stateAttr) ? Option.some(get(e, transConfig.stateAttr)) : Option.none();
  8885. };
  8886. var TransitionApis = /*#__PURE__*/Object.freeze({
  8887. findRoute: findRoute,
  8888. disableTransition: disableTransition,
  8889. getCurrentRoute: getCurrentRoute,
  8890. jumpTo: jumpTo,
  8891. progressTo: progressTo,
  8892. getState: getState$1
  8893. });
  8894. var events$9 = function (transConfig, transState) {
  8895. return derive([
  8896. run(transitionend(), function (component, simulatedEvent) {
  8897. var raw = simulatedEvent.event().raw();
  8898. getCurrentRoute(component, transConfig).each(function (route) {
  8899. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8900. rInfo.transition.each(function (rTransition) {
  8901. if (raw.propertyName === rTransition.property) {
  8902. jumpTo(component, transConfig, transState, route.destination);
  8903. transConfig.onTransition(component, route);
  8904. }
  8905. });
  8906. });
  8907. });
  8908. }),
  8909. runOnAttached(function (comp, se) {
  8910. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8911. })
  8912. ]);
  8913. };
  8914. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8915. events: events$9
  8916. });
  8917. var TransitionSchema = [
  8918. defaulted$1('destinationAttr', 'data-transitioning-destination'),
  8919. defaulted$1('stateAttr', 'data-transitioning-state'),
  8920. strict$1('initialState'),
  8921. onHandler('onTransition'),
  8922. onHandler('onFinish'),
  8923. strictOf('routes', setOf$1(Result.value, setOf$1(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8924. strict$1('property'),
  8925. strict$1('transitionClass')
  8926. ])]))))
  8927. ];
  8928. var createRoutes = function (routes) {
  8929. var r = {};
  8930. each(routes, function (v, k) {
  8931. var waypoints = k.split('<->');
  8932. r[waypoints[0]] = wrap$1(waypoints[1], v);
  8933. r[waypoints[1]] = wrap$1(waypoints[0], v);
  8934. });
  8935. return r;
  8936. };
  8937. var createBistate = function (first, second, transitions) {
  8938. return wrapAll$1([
  8939. {
  8940. key: first,
  8941. value: wrap$1(second, transitions)
  8942. },
  8943. {
  8944. key: second,
  8945. value: wrap$1(first, transitions)
  8946. }
  8947. ]);
  8948. };
  8949. var createTristate = function (first, second, third, transitions) {
  8950. return wrapAll$1([
  8951. {
  8952. key: first,
  8953. value: wrapAll$1([
  8954. {
  8955. key: second,
  8956. value: transitions
  8957. },
  8958. {
  8959. key: third,
  8960. value: transitions
  8961. }
  8962. ])
  8963. },
  8964. {
  8965. key: second,
  8966. value: wrapAll$1([
  8967. {
  8968. key: first,
  8969. value: transitions
  8970. },
  8971. {
  8972. key: third,
  8973. value: transitions
  8974. }
  8975. ])
  8976. },
  8977. {
  8978. key: third,
  8979. value: wrapAll$1([
  8980. {
  8981. key: first,
  8982. value: transitions
  8983. },
  8984. {
  8985. key: second,
  8986. value: transitions
  8987. }
  8988. ])
  8989. }
  8990. ]);
  8991. };
  8992. var Transitioning = create$1({
  8993. fields: TransitionSchema,
  8994. name: 'transitioning',
  8995. active: ActiveTransitioning,
  8996. apis: TransitionApis,
  8997. extra: {
  8998. createRoutes: createRoutes,
  8999. createBistate: createBistate,
  9000. createTristate: createTristate
  9001. }
  9002. });
  9003. var scrollable = Styles.resolve('scrollable');
  9004. var register = function (element) {
  9005. add$2(element, scrollable);
  9006. };
  9007. var deregister = function (element) {
  9008. remove$4(element, scrollable);
  9009. };
  9010. var Scrollable = {
  9011. register: register,
  9012. deregister: deregister,
  9013. scrollable: constant(scrollable)
  9014. };
  9015. var getValue$4 = function (item) {
  9016. return readOptFrom$1(item, 'format').getOr(item.title);
  9017. };
  9018. var convert$1 = function (formats, memMenuThunk) {
  9019. var mainMenu = makeMenu('Styles', [].concat(map$1(formats.items, function (k) {
  9020. return makeItem(getValue$4(k), k.title, k.isSelected(), k.getPreview(), hasKey$1(formats.expansions, getValue$4(k)));
  9021. })), memMenuThunk, false);
  9022. var submenus = map(formats.menus, function (menuItems, menuName) {
  9023. var items = map$1(menuItems, function (item) {
  9024. 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)));
  9025. });
  9026. return makeMenu(menuName, items, memMenuThunk, true);
  9027. });
  9028. var menus = deepMerge(submenus, wrap$1('styles', mainMenu));
  9029. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  9030. return { tmenu: tmenu };
  9031. };
  9032. var makeItem = function (value, text, selected, preview, isMenu) {
  9033. return {
  9034. data: {
  9035. value: value,
  9036. text: text
  9037. },
  9038. type: 'item',
  9039. dom: {
  9040. tag: 'div',
  9041. classes: isMenu ? [Styles.resolve('styles-item-is-menu')] : []
  9042. },
  9043. toggling: {
  9044. toggleOnExecute: false,
  9045. toggleClass: Styles.resolve('format-matches'),
  9046. selected: selected
  9047. },
  9048. itemBehaviours: derive$1(isMenu ? [] : [Receivers.format(value, function (comp, status) {
  9049. var toggle = status ? Toggling.on : Toggling.off;
  9050. toggle(comp);
  9051. })]),
  9052. components: [{
  9053. dom: {
  9054. tag: 'div',
  9055. attributes: { style: preview },
  9056. innerHtml: text
  9057. }
  9058. }]
  9059. };
  9060. };
  9061. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  9062. return {
  9063. value: value,
  9064. dom: { tag: 'div' },
  9065. components: [
  9066. Button.sketch({
  9067. dom: {
  9068. tag: 'div',
  9069. classes: [Styles.resolve('styles-collapser')]
  9070. },
  9071. components: collapsable ? [
  9072. {
  9073. dom: {
  9074. tag: 'span',
  9075. classes: [Styles.resolve('styles-collapse-icon')]
  9076. }
  9077. },
  9078. text(value)
  9079. ] : [text(value)],
  9080. action: function (item) {
  9081. if (collapsable) {
  9082. var comp = memMenuThunk().get(item);
  9083. tieredMenu.collapseMenu(comp);
  9084. }
  9085. }
  9086. }),
  9087. {
  9088. dom: {
  9089. tag: 'div',
  9090. classes: [Styles.resolve('styles-menu-items-container')]
  9091. },
  9092. components: [Menu.parts().items({})],
  9093. behaviours: derive$1([config('adhoc-scrollable-menu', [
  9094. runOnAttached(function (component, simulatedEvent) {
  9095. set$3(component.element(), 'overflow-y', 'auto');
  9096. set$3(component.element(), '-webkit-overflow-scrolling', 'touch');
  9097. Scrollable.register(component.element());
  9098. }),
  9099. runOnDetached(function (component) {
  9100. remove$5(component.element(), 'overflow-y');
  9101. remove$5(component.element(), '-webkit-overflow-scrolling');
  9102. Scrollable.deregister(component.element());
  9103. })
  9104. ])])
  9105. }
  9106. ],
  9107. items: items,
  9108. menuBehaviours: derive$1([Transitioning.config({
  9109. initialState: 'after',
  9110. routes: Transitioning.createTristate('before', 'current', 'after', {
  9111. transition: {
  9112. property: 'transform',
  9113. transitionClass: 'transitioning'
  9114. }
  9115. })
  9116. })])
  9117. };
  9118. };
  9119. var sketch$8 = function (settings) {
  9120. var dataset = convert$1(settings.formats, function () {
  9121. return memMenu;
  9122. });
  9123. var memMenu = record(tieredMenu.sketch({
  9124. dom: {
  9125. tag: 'div',
  9126. classes: [Styles.resolve('styles-menu')]
  9127. },
  9128. components: [],
  9129. fakeFocus: true,
  9130. stayInDom: true,
  9131. onExecute: function (tmenu, item) {
  9132. var v = Representing.getValue(item);
  9133. settings.handle(item, v.value);
  9134. return Option.none();
  9135. },
  9136. onEscape: function () {
  9137. return Option.none();
  9138. },
  9139. onOpenMenu: function (container, menu) {
  9140. var w = get$6(container.element());
  9141. set$4(menu.element(), w);
  9142. Transitioning.jumpTo(menu, 'current');
  9143. },
  9144. onOpenSubmenu: function (container, item, submenu) {
  9145. var w = get$6(container.element());
  9146. var menu = ancestor$1(item.element(), '[role="menu"]').getOrDie('hacky');
  9147. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9148. set$4(submenu.element(), w);
  9149. Transitioning.progressTo(menuComp, 'before');
  9150. Transitioning.jumpTo(submenu, 'after');
  9151. Transitioning.progressTo(submenu, 'current');
  9152. },
  9153. onCollapseMenu: function (container, item, menu) {
  9154. var submenu = ancestor$1(item.element(), '[role="menu"]').getOrDie('hacky');
  9155. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9156. Transitioning.progressTo(submenuComp, 'after');
  9157. Transitioning.progressTo(menu, 'current');
  9158. },
  9159. navigateOnHover: false,
  9160. highlightImmediately: true,
  9161. data: dataset.tmenu,
  9162. markers: {
  9163. backgroundMenu: Styles.resolve('styles-background-menu'),
  9164. menu: Styles.resolve('styles-menu'),
  9165. selectedMenu: Styles.resolve('styles-selected-menu'),
  9166. item: Styles.resolve('styles-item'),
  9167. selectedItem: Styles.resolve('styles-selected-item')
  9168. }
  9169. }));
  9170. return memMenu.asSpec();
  9171. };
  9172. var StylesMenu = { sketch: sketch$8 };
  9173. var getFromExpandingItem = function (item) {
  9174. var newItem = deepMerge(exclude$1(item, ['items']), { menu: true });
  9175. var rest = expand(item.items);
  9176. var newMenus = deepMerge(rest.menus, wrap$1(item.title, rest.items));
  9177. var newExpansions = deepMerge(rest.expansions, wrap$1(item.title, item.title));
  9178. return {
  9179. item: newItem,
  9180. menus: newMenus,
  9181. expansions: newExpansions
  9182. };
  9183. };
  9184. var getFromItem = function (item) {
  9185. return hasKey$1(item, 'items') ? getFromExpandingItem(item) : {
  9186. item: item,
  9187. menus: {},
  9188. expansions: {}
  9189. };
  9190. };
  9191. var expand = function (items) {
  9192. return foldr(items, function (acc, item) {
  9193. var newData = getFromItem(item);
  9194. return {
  9195. menus: deepMerge(acc.menus, newData.menus),
  9196. items: [newData.item].concat(acc.items),
  9197. expansions: deepMerge(acc.expansions, newData.expansions)
  9198. };
  9199. }, {
  9200. menus: {},
  9201. expansions: {},
  9202. items: []
  9203. });
  9204. };
  9205. var StyleConversions = { expand: expand };
  9206. var register$1 = function (editor, settings) {
  9207. var isSelectedFor = function (format) {
  9208. return function () {
  9209. return editor.formatter.match(format);
  9210. };
  9211. };
  9212. var getPreview = function (format) {
  9213. return function () {
  9214. var styles = editor.formatter.getCssText(format);
  9215. return styles;
  9216. };
  9217. };
  9218. var enrichSupported = function (item) {
  9219. return deepMerge(item, {
  9220. isSelected: isSelectedFor(item.format),
  9221. getPreview: getPreview(item.format)
  9222. });
  9223. };
  9224. var enrichMenu = function (item) {
  9225. return deepMerge(item, {
  9226. isSelected: constant(false),
  9227. getPreview: constant('')
  9228. });
  9229. };
  9230. var enrichCustom = function (item) {
  9231. var formatName = generate$1(item.title);
  9232. var newItem = deepMerge(item, {
  9233. format: formatName,
  9234. isSelected: isSelectedFor(formatName),
  9235. getPreview: getPreview(formatName)
  9236. });
  9237. editor.formatter.register(formatName, newItem);
  9238. return newItem;
  9239. };
  9240. var formats = readOptFrom$1(settings, 'style_formats').getOr(DefaultStyleFormats);
  9241. var doEnrich = function (items) {
  9242. return map$1(items, function (item) {
  9243. if (hasKey$1(item, 'items')) {
  9244. var newItems = doEnrich(item.items);
  9245. return deepMerge(enrichMenu(item), { items: newItems });
  9246. } else if (hasKey$1(item, 'format')) {
  9247. return enrichSupported(item);
  9248. } else {
  9249. return enrichCustom(item);
  9250. }
  9251. });
  9252. };
  9253. return doEnrich(formats);
  9254. };
  9255. var prune = function (editor, formats) {
  9256. var doPrune = function (items) {
  9257. return bind(items, function (item) {
  9258. if (item.items !== undefined) {
  9259. var newItems = doPrune(item.items);
  9260. return newItems.length > 0 ? [item] : [];
  9261. } else {
  9262. var keep = hasKey$1(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9263. return keep ? [item] : [];
  9264. }
  9265. });
  9266. };
  9267. var prunedItems = doPrune(formats);
  9268. return StyleConversions.expand(prunedItems);
  9269. };
  9270. var ui = function (editor, formats, onDone) {
  9271. var pruned = prune(editor, formats);
  9272. return StylesMenu.sketch({
  9273. formats: pruned,
  9274. handle: function (item, value) {
  9275. editor.undoManager.transact(function () {
  9276. if (Toggling.isOn(item)) {
  9277. editor.formatter.remove(value);
  9278. } else {
  9279. editor.formatter.apply(value);
  9280. }
  9281. });
  9282. onDone();
  9283. }
  9284. });
  9285. };
  9286. var StyleFormats = {
  9287. register: register$1,
  9288. ui: ui
  9289. };
  9290. var defaults = [
  9291. 'undo',
  9292. 'bold',
  9293. 'italic',
  9294. 'link',
  9295. 'image',
  9296. 'bullist',
  9297. 'styleselect'
  9298. ];
  9299. var extract$1 = function (rawToolbar) {
  9300. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9301. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9302. };
  9303. var identifyFromArray = function (toolbar) {
  9304. return bind(toolbar, function (item) {
  9305. return isArray(item) ? identifyFromArray(item) : extract$1(item);
  9306. });
  9307. };
  9308. var identify = function (settings) {
  9309. var toolbar = settings.toolbar !== undefined ? settings.toolbar : defaults;
  9310. return isArray(toolbar) ? identifyFromArray(toolbar) : extract$1(toolbar);
  9311. };
  9312. var setup = function (realm, editor) {
  9313. var commandSketch = function (name) {
  9314. return function () {
  9315. return Buttons.forToolbarCommand(editor, name);
  9316. };
  9317. };
  9318. var stateCommandSketch = function (name) {
  9319. return function () {
  9320. return Buttons.forToolbarStateCommand(editor, name);
  9321. };
  9322. };
  9323. var actionSketch = function (name, query, action) {
  9324. return function () {
  9325. return Buttons.forToolbarStateAction(editor, name, query, action);
  9326. };
  9327. };
  9328. var undo = commandSketch('undo');
  9329. var redo = commandSketch('redo');
  9330. var bold = stateCommandSketch('bold');
  9331. var italic = stateCommandSketch('italic');
  9332. var underline = stateCommandSketch('underline');
  9333. var removeformat = commandSketch('removeformat');
  9334. var link = function () {
  9335. return sketch$7(realm, editor);
  9336. };
  9337. var unlink = actionSketch('unlink', 'link', function () {
  9338. editor.execCommand('unlink', null, false);
  9339. });
  9340. var image = function () {
  9341. return sketch$4(editor);
  9342. };
  9343. var bullist = actionSketch('unordered-list', 'ul', function () {
  9344. editor.execCommand('InsertUnorderedList', null, false);
  9345. });
  9346. var numlist = actionSketch('ordered-list', 'ol', function () {
  9347. editor.execCommand('InsertOrderedList', null, false);
  9348. });
  9349. var fontsizeselect = function () {
  9350. return sketch$3(realm, editor);
  9351. };
  9352. var forecolor = function () {
  9353. return ColorSlider.sketch(realm, editor);
  9354. };
  9355. var styleFormats = StyleFormats.register(editor, editor.settings);
  9356. var styleFormatsMenu = function () {
  9357. return StyleFormats.ui(editor, styleFormats, function () {
  9358. editor.fire('scrollIntoView');
  9359. });
  9360. };
  9361. var styleselect = function () {
  9362. return Buttons.forToolbar('style-formats', function (button) {
  9363. editor.fire('toReading');
  9364. realm.dropup().appear(styleFormatsMenu, Toggling.on, button);
  9365. }, derive$1([
  9366. Toggling.config({
  9367. toggleClass: Styles.resolve('toolbar-button-selected'),
  9368. toggleOnExecute: false,
  9369. aria: { mode: 'pressed' }
  9370. }),
  9371. Receiving.config({
  9372. channels: wrapAll$1([
  9373. Receivers.receive(TinyChannels.orientationChanged(), Toggling.off),
  9374. Receivers.receive(TinyChannels.dropupDismissed(), Toggling.off)
  9375. ])
  9376. })
  9377. ]), editor);
  9378. };
  9379. var feature = function (prereq, sketch) {
  9380. return {
  9381. isSupported: function () {
  9382. var buttons = editor.ui.registry.getAll().buttons;
  9383. return prereq.forall(function (p) {
  9384. return hasKey$1(buttons, p);
  9385. });
  9386. },
  9387. sketch: sketch
  9388. };
  9389. };
  9390. return {
  9391. undo: feature(Option.none(), undo),
  9392. redo: feature(Option.none(), redo),
  9393. bold: feature(Option.none(), bold),
  9394. italic: feature(Option.none(), italic),
  9395. underline: feature(Option.none(), underline),
  9396. removeformat: feature(Option.none(), removeformat),
  9397. link: feature(Option.none(), link),
  9398. unlink: feature(Option.none(), unlink),
  9399. image: feature(Option.none(), image),
  9400. bullist: feature(Option.some('bullist'), bullist),
  9401. numlist: feature(Option.some('numlist'), numlist),
  9402. fontsizeselect: feature(Option.none(), fontsizeselect),
  9403. forecolor: feature(Option.none(), forecolor),
  9404. styleselect: feature(Option.none(), styleselect)
  9405. };
  9406. };
  9407. var detect$4 = function (settings, features) {
  9408. var itemNames = identify(settings);
  9409. var present = {};
  9410. return bind(itemNames, function (iName) {
  9411. var r = !hasKey$1(present, iName) && hasKey$1(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9412. present[iName] = true;
  9413. return r;
  9414. });
  9415. };
  9416. var Features = {
  9417. identify: identify,
  9418. setup: setup,
  9419. detect: detect$4
  9420. };
  9421. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9422. return {
  9423. target: constant(target),
  9424. x: constant(x),
  9425. y: constant(y),
  9426. stop: stop,
  9427. prevent: prevent,
  9428. kill: kill,
  9429. raw: constant(raw)
  9430. };
  9431. };
  9432. var fromRawEvent = function (rawEvent) {
  9433. var target = Element.fromDom(rawEvent.target);
  9434. var stop = function () {
  9435. rawEvent.stopPropagation();
  9436. };
  9437. var prevent = function () {
  9438. rawEvent.preventDefault();
  9439. };
  9440. var kill = compose(prevent, stop);
  9441. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9442. };
  9443. var handle = function (filter, handler) {
  9444. return function (rawEvent) {
  9445. if (!filter(rawEvent)) {
  9446. return;
  9447. }
  9448. handler(fromRawEvent(rawEvent));
  9449. };
  9450. };
  9451. var binder = function (element, event, filter, handler, useCapture) {
  9452. var wrapped = handle(filter, handler);
  9453. element.dom().addEventListener(event, wrapped, useCapture);
  9454. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9455. };
  9456. var bind$2 = function (element, event, filter, handler) {
  9457. return binder(element, event, filter, handler, false);
  9458. };
  9459. var capture = function (element, event, filter, handler) {
  9460. return binder(element, event, filter, handler, true);
  9461. };
  9462. var unbind = function (element, event, handler, useCapture) {
  9463. element.dom().removeEventListener(event, handler, useCapture);
  9464. };
  9465. var filter$1 = constant(true);
  9466. var bind$3 = function (element, event, handler) {
  9467. return bind$2(element, event, filter$1, handler);
  9468. };
  9469. var capture$1 = function (element, event, handler) {
  9470. return capture(element, event, filter$1, handler);
  9471. };
  9472. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9473. var INTERVAL = 50;
  9474. var INSURANCE = 1000 / INTERVAL;
  9475. var get$a = function (outerWindow) {
  9476. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9477. return { isPortrait: constant(isPortrait) };
  9478. };
  9479. var getActualWidth = function (outerWindow) {
  9480. var isIos = detect$3().os.isiOS();
  9481. var isPortrait = get$a(outerWindow).isPortrait();
  9482. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9483. };
  9484. var onChange = function (outerWindow, listeners) {
  9485. var win = Element.fromDom(outerWindow);
  9486. var poller = null;
  9487. var change = function () {
  9488. global$4.clearInterval(poller);
  9489. var orientation = get$a(outerWindow);
  9490. listeners.onChange(orientation);
  9491. onAdjustment(function () {
  9492. listeners.onReady(orientation);
  9493. });
  9494. };
  9495. var orientationHandle = bind$3(win, 'orientationchange', change);
  9496. var onAdjustment = function (f) {
  9497. global$4.clearInterval(poller);
  9498. var flag = outerWindow.innerHeight;
  9499. var insurance = 0;
  9500. poller = global$4.setInterval(function () {
  9501. if (flag !== outerWindow.innerHeight) {
  9502. global$4.clearInterval(poller);
  9503. f(Option.some(outerWindow.innerHeight));
  9504. } else if (insurance > INSURANCE) {
  9505. global$4.clearInterval(poller);
  9506. f(Option.none());
  9507. }
  9508. insurance++;
  9509. }, INTERVAL);
  9510. };
  9511. var destroy = function () {
  9512. orientationHandle.unbind();
  9513. };
  9514. return {
  9515. onAdjustment: onAdjustment,
  9516. destroy: destroy
  9517. };
  9518. };
  9519. var Orientation = {
  9520. get: get$a,
  9521. onChange: onChange,
  9522. getActualWidth: getActualWidth
  9523. };
  9524. function DelayedFunction (fun, delay) {
  9525. var ref = null;
  9526. var schedule = function () {
  9527. var args = [];
  9528. for (var _i = 0; _i < arguments.length; _i++) {
  9529. args[_i] = arguments[_i];
  9530. }
  9531. ref = domGlobals.setTimeout(function () {
  9532. fun.apply(null, args);
  9533. ref = null;
  9534. }, delay);
  9535. };
  9536. var cancel = function () {
  9537. if (ref !== null) {
  9538. domGlobals.clearTimeout(ref);
  9539. ref = null;
  9540. }
  9541. };
  9542. return {
  9543. cancel: cancel,
  9544. schedule: schedule
  9545. };
  9546. }
  9547. var SIGNIFICANT_MOVE = 5;
  9548. var LONGPRESS_DELAY = 400;
  9549. var getTouch = function (event) {
  9550. var raw = event.raw();
  9551. if (raw.touches === undefined || raw.touches.length !== 1) {
  9552. return Option.none();
  9553. }
  9554. return Option.some(raw.touches[0]);
  9555. };
  9556. var isFarEnough = function (touch, data) {
  9557. var distX = Math.abs(touch.clientX - data.x());
  9558. var distY = Math.abs(touch.clientY - data.y());
  9559. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  9560. };
  9561. var monitor = function (settings) {
  9562. var startData = Cell(Option.none());
  9563. var longpressFired = Cell(false);
  9564. var longpress$1 = DelayedFunction(function (event) {
  9565. settings.triggerEvent(longpress(), event);
  9566. longpressFired.set(true);
  9567. }, LONGPRESS_DELAY);
  9568. var handleTouchstart = function (event) {
  9569. getTouch(event).each(function (touch) {
  9570. longpress$1.cancel();
  9571. var data = {
  9572. x: constant(touch.clientX),
  9573. y: constant(touch.clientY),
  9574. target: event.target
  9575. };
  9576. longpress$1.schedule(event);
  9577. longpressFired.set(false);
  9578. startData.set(Option.some(data));
  9579. });
  9580. return Option.none();
  9581. };
  9582. var handleTouchmove = function (event) {
  9583. longpress$1.cancel();
  9584. getTouch(event).each(function (touch) {
  9585. startData.get().each(function (data) {
  9586. if (isFarEnough(touch, data)) {
  9587. startData.set(Option.none());
  9588. }
  9589. });
  9590. });
  9591. return Option.none();
  9592. };
  9593. var handleTouchend = function (event) {
  9594. longpress$1.cancel();
  9595. var isSame = function (data) {
  9596. return eq(data.target(), event.target());
  9597. };
  9598. return startData.get().filter(isSame).map(function (data) {
  9599. if (longpressFired.get()) {
  9600. event.prevent();
  9601. return false;
  9602. } else {
  9603. return settings.triggerEvent(tap(), event);
  9604. }
  9605. });
  9606. };
  9607. var handlers = wrapAll$1([
  9608. {
  9609. key: touchstart(),
  9610. value: handleTouchstart
  9611. },
  9612. {
  9613. key: touchmove(),
  9614. value: handleTouchmove
  9615. },
  9616. {
  9617. key: touchend(),
  9618. value: handleTouchend
  9619. }
  9620. ]);
  9621. var fireIfReady = function (event, type) {
  9622. return readOptFrom$1(handlers, type).bind(function (handler) {
  9623. return handler(event);
  9624. });
  9625. };
  9626. return { fireIfReady: fireIfReady };
  9627. };
  9628. var monitor$1 = function (editorApi) {
  9629. var tapEvent = monitor({
  9630. triggerEvent: function (type, evt) {
  9631. editorApi.onTapContent(evt);
  9632. }
  9633. });
  9634. var onTouchend = function () {
  9635. return bind$3(editorApi.body(), 'touchend', function (evt) {
  9636. tapEvent.fireIfReady(evt, 'touchend');
  9637. });
  9638. };
  9639. var onTouchmove = function () {
  9640. return bind$3(editorApi.body(), 'touchmove', function (evt) {
  9641. tapEvent.fireIfReady(evt, 'touchmove');
  9642. });
  9643. };
  9644. var fireTouchstart = function (evt) {
  9645. tapEvent.fireIfReady(evt, 'touchstart');
  9646. };
  9647. return {
  9648. fireTouchstart: fireTouchstart,
  9649. onTouchend: onTouchend,
  9650. onTouchmove: onTouchmove
  9651. };
  9652. };
  9653. var TappingEvent = { monitor: monitor$1 };
  9654. var isAndroid6 = detect$3().os.version.major >= 6;
  9655. var initEvents = function (editorApi, toolstrip, alloy) {
  9656. var tapping = TappingEvent.monitor(editorApi);
  9657. var outerDoc = owner(toolstrip);
  9658. var isRanged = function (sel) {
  9659. return !eq(sel.start(), sel.finish()) || sel.soffset() !== sel.foffset();
  9660. };
  9661. var hasRangeInUi = function () {
  9662. return active(outerDoc).filter(function (input) {
  9663. return name(input) === 'input';
  9664. }).exists(function (input) {
  9665. return input.dom().selectionStart !== input.dom().selectionEnd;
  9666. });
  9667. };
  9668. var updateMargin = function () {
  9669. var rangeInContent = editorApi.doc().dom().hasFocus() && editorApi.getSelection().exists(isRanged);
  9670. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  9671. };
  9672. var listeners = [
  9673. bind$3(editorApi.body(), 'touchstart', function (evt) {
  9674. editorApi.onTouchContent();
  9675. tapping.fireTouchstart(evt);
  9676. }),
  9677. tapping.onTouchmove(),
  9678. tapping.onTouchend(),
  9679. bind$3(toolstrip, 'touchstart', function (evt) {
  9680. editorApi.onTouchToolstrip();
  9681. }),
  9682. editorApi.onToReading(function () {
  9683. blur(editorApi.body());
  9684. }),
  9685. editorApi.onToEditing(noop),
  9686. editorApi.onScrollToCursor(function (tinyEvent) {
  9687. tinyEvent.preventDefault();
  9688. editorApi.getCursorBox().each(function (bounds) {
  9689. var cWin = editorApi.win();
  9690. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  9691. var cScrollBy = isOutside ? bounds.bottom() - cWin.innerHeight + 50 : 0;
  9692. if (cScrollBy !== 0) {
  9693. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  9694. }
  9695. });
  9696. })
  9697. ].concat(isAndroid6 === true ? [] : [
  9698. bind$3(Element.fromDom(editorApi.win()), 'blur', function () {
  9699. alloy.getByDom(toolstrip).each(Toggling.off);
  9700. }),
  9701. bind$3(outerDoc, 'select', updateMargin),
  9702. bind$3(editorApi.doc(), 'selectionchange', updateMargin)
  9703. ]);
  9704. var destroy = function () {
  9705. each$1(listeners, function (l) {
  9706. l.unbind();
  9707. });
  9708. };
  9709. return { destroy: destroy };
  9710. };
  9711. var AndroidEvents = { initEvents: initEvents };
  9712. var safeParse = function (element, attribute) {
  9713. var parsed = parseInt(get(element, attribute), 10);
  9714. return isNaN(parsed) ? 0 : parsed;
  9715. };
  9716. var DataAttributes = { safeParse: safeParse };
  9717. function NodeValue (is, name) {
  9718. var get = function (element) {
  9719. if (!is(element)) {
  9720. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9721. }
  9722. return getOption(element).getOr('');
  9723. };
  9724. var getOption = function (element) {
  9725. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  9726. };
  9727. var set = function (element, value) {
  9728. if (!is(element)) {
  9729. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9730. }
  9731. element.dom().nodeValue = value;
  9732. };
  9733. return {
  9734. get: get,
  9735. getOption: getOption,
  9736. set: set
  9737. };
  9738. }
  9739. var api$3 = NodeValue(isText, 'text');
  9740. var get$b = function (element) {
  9741. return api$3.get(element);
  9742. };
  9743. var getOption = function (element) {
  9744. return api$3.getOption(element);
  9745. };
  9746. var getEnd = function (element) {
  9747. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  9748. return children(element).length;
  9749. }, function (v) {
  9750. return v.length;
  9751. });
  9752. };
  9753. var NBSP = '\xA0';
  9754. var isTextNodeWithCursorPosition = function (el) {
  9755. return getOption(el).filter(function (text) {
  9756. return text.trim().length !== 0 || text.indexOf(NBSP) > -1;
  9757. }).isSome();
  9758. };
  9759. var elementsWithCursorPosition = [
  9760. 'img',
  9761. 'br'
  9762. ];
  9763. var isCursorPosition = function (elem) {
  9764. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  9765. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  9766. };
  9767. var create$3 = Immutable('start', 'soffset', 'finish', 'foffset');
  9768. var SimRange = { create: create$3 };
  9769. var adt$4 = Adt.generate([
  9770. { before: ['element'] },
  9771. {
  9772. on: [
  9773. 'element',
  9774. 'offset'
  9775. ]
  9776. },
  9777. { after: ['element'] }
  9778. ]);
  9779. var cata = function (subject, onBefore, onOn, onAfter) {
  9780. return subject.fold(onBefore, onOn, onAfter);
  9781. };
  9782. var getStart = function (situ) {
  9783. return situ.fold(identity, identity, identity);
  9784. };
  9785. var before$1 = adt$4.before;
  9786. var on$1 = adt$4.on;
  9787. var after$1 = adt$4.after;
  9788. var Situ = {
  9789. before: before$1,
  9790. on: on$1,
  9791. after: after$1,
  9792. cata: cata,
  9793. getStart: getStart
  9794. };
  9795. var adt$5 = Adt.generate([
  9796. { domRange: ['rng'] },
  9797. {
  9798. relative: [
  9799. 'startSitu',
  9800. 'finishSitu'
  9801. ]
  9802. },
  9803. {
  9804. exact: [
  9805. 'start',
  9806. 'soffset',
  9807. 'finish',
  9808. 'foffset'
  9809. ]
  9810. }
  9811. ]);
  9812. var exactFromRange = function (simRange) {
  9813. return adt$5.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  9814. };
  9815. var getStart$1 = function (selection) {
  9816. return selection.match({
  9817. domRange: function (rng) {
  9818. return Element.fromDom(rng.startContainer);
  9819. },
  9820. relative: function (startSitu, finishSitu) {
  9821. return Situ.getStart(startSitu);
  9822. },
  9823. exact: function (start, soffset, finish, foffset) {
  9824. return start;
  9825. }
  9826. });
  9827. };
  9828. var domRange = adt$5.domRange;
  9829. var relative = adt$5.relative;
  9830. var exact = adt$5.exact;
  9831. var getWin = function (selection) {
  9832. var start = getStart$1(selection);
  9833. return defaultView(start);
  9834. };
  9835. var range$1 = SimRange.create;
  9836. var Selection = {
  9837. domRange: domRange,
  9838. relative: relative,
  9839. exact: exact,
  9840. exactFromRange: exactFromRange,
  9841. getWin: getWin,
  9842. range: range$1
  9843. };
  9844. var setStart = function (rng, situ) {
  9845. situ.fold(function (e) {
  9846. rng.setStartBefore(e.dom());
  9847. }, function (e, o) {
  9848. rng.setStart(e.dom(), o);
  9849. }, function (e) {
  9850. rng.setStartAfter(e.dom());
  9851. });
  9852. };
  9853. var setFinish = function (rng, situ) {
  9854. situ.fold(function (e) {
  9855. rng.setEndBefore(e.dom());
  9856. }, function (e, o) {
  9857. rng.setEnd(e.dom(), o);
  9858. }, function (e) {
  9859. rng.setEndAfter(e.dom());
  9860. });
  9861. };
  9862. var relativeToNative = function (win, startSitu, finishSitu) {
  9863. var range = win.document.createRange();
  9864. setStart(range, startSitu);
  9865. setFinish(range, finishSitu);
  9866. return range;
  9867. };
  9868. var exactToNative = function (win, start, soffset, finish, foffset) {
  9869. var rng = win.document.createRange();
  9870. rng.setStart(start.dom(), soffset);
  9871. rng.setEnd(finish.dom(), foffset);
  9872. return rng;
  9873. };
  9874. var toRect = function (rect) {
  9875. return {
  9876. left: constant(rect.left),
  9877. top: constant(rect.top),
  9878. right: constant(rect.right),
  9879. bottom: constant(rect.bottom),
  9880. width: constant(rect.width),
  9881. height: constant(rect.height)
  9882. };
  9883. };
  9884. var getFirstRect = function (rng) {
  9885. var rects = rng.getClientRects();
  9886. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9887. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  9888. };
  9889. var adt$6 = Adt.generate([
  9890. {
  9891. ltr: [
  9892. 'start',
  9893. 'soffset',
  9894. 'finish',
  9895. 'foffset'
  9896. ]
  9897. },
  9898. {
  9899. rtl: [
  9900. 'start',
  9901. 'soffset',
  9902. 'finish',
  9903. 'foffset'
  9904. ]
  9905. }
  9906. ]);
  9907. var fromRange = function (win, type, range) {
  9908. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  9909. };
  9910. var getRanges = function (win, selection) {
  9911. return selection.match({
  9912. domRange: function (rng) {
  9913. return {
  9914. ltr: constant(rng),
  9915. rtl: Option.none
  9916. };
  9917. },
  9918. relative: function (startSitu, finishSitu) {
  9919. return {
  9920. ltr: cached(function () {
  9921. return relativeToNative(win, startSitu, finishSitu);
  9922. }),
  9923. rtl: cached(function () {
  9924. return Option.some(relativeToNative(win, finishSitu, startSitu));
  9925. })
  9926. };
  9927. },
  9928. exact: function (start, soffset, finish, foffset) {
  9929. return {
  9930. ltr: cached(function () {
  9931. return exactToNative(win, start, soffset, finish, foffset);
  9932. }),
  9933. rtl: cached(function () {
  9934. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  9935. })
  9936. };
  9937. }
  9938. });
  9939. };
  9940. var doDiagnose = function (win, ranges) {
  9941. var rng = ranges.ltr();
  9942. if (rng.collapsed) {
  9943. var reversed = ranges.rtl().filter(function (rev) {
  9944. return rev.collapsed === false;
  9945. });
  9946. return reversed.map(function (rev) {
  9947. return adt$6.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  9948. }).getOrThunk(function () {
  9949. return fromRange(win, adt$6.ltr, rng);
  9950. });
  9951. } else {
  9952. return fromRange(win, adt$6.ltr, rng);
  9953. }
  9954. };
  9955. var diagnose = function (win, selection) {
  9956. var ranges = getRanges(win, selection);
  9957. return doDiagnose(win, ranges);
  9958. };
  9959. var asLtrRange = function (win, selection) {
  9960. var diagnosis = diagnose(win, selection);
  9961. return diagnosis.match({
  9962. ltr: function (start, soffset, finish, foffset) {
  9963. var rng = win.document.createRange();
  9964. rng.setStart(start.dom(), soffset);
  9965. rng.setEnd(finish.dom(), foffset);
  9966. return rng;
  9967. },
  9968. rtl: function (start, soffset, finish, foffset) {
  9969. var rng = win.document.createRange();
  9970. rng.setStart(finish.dom(), foffset);
  9971. rng.setEnd(start.dom(), soffset);
  9972. return rng;
  9973. }
  9974. });
  9975. };
  9976. var searchForPoint = function (rectForOffset, x, y, maxX, length) {
  9977. if (length === 0) {
  9978. return 0;
  9979. } else if (x === maxX) {
  9980. return length - 1;
  9981. }
  9982. var xDelta = maxX;
  9983. for (var i = 1; i < length; i++) {
  9984. var rect = rectForOffset(i);
  9985. var curDeltaX = Math.abs(x - rect.left);
  9986. if (y <= rect.bottom) {
  9987. if (y < rect.top || curDeltaX > xDelta) {
  9988. return i - 1;
  9989. } else {
  9990. xDelta = curDeltaX;
  9991. }
  9992. }
  9993. }
  9994. return 0;
  9995. };
  9996. var inRect = function (rect, x, y) {
  9997. return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
  9998. };
  9999. var locateOffset = function (doc, textnode, x, y, rect) {
  10000. var rangeForOffset = function (o) {
  10001. var r = doc.dom().createRange();
  10002. r.setStart(textnode.dom(), o);
  10003. r.collapse(true);
  10004. return r;
  10005. };
  10006. var rectForOffset = function (o) {
  10007. var r = rangeForOffset(o);
  10008. return r.getBoundingClientRect();
  10009. };
  10010. var length = get$b(textnode).length;
  10011. var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
  10012. return rangeForOffset(offset);
  10013. };
  10014. var locate$1 = function (doc, node, x, y) {
  10015. var r = doc.dom().createRange();
  10016. r.selectNode(node.dom());
  10017. var rects = r.getClientRects();
  10018. var foundRect = findMap(rects, function (rect) {
  10019. return inRect(rect, x, y) ? Option.some(rect) : Option.none();
  10020. });
  10021. return foundRect.map(function (rect) {
  10022. return locateOffset(doc, node, x, y, rect);
  10023. });
  10024. };
  10025. var searchInChildren = function (doc, node, x, y) {
  10026. var r = doc.dom().createRange();
  10027. var nodes = children(node);
  10028. return findMap(nodes, function (n) {
  10029. r.selectNode(n.dom());
  10030. return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none();
  10031. });
  10032. };
  10033. var locateNode = function (doc, node, x, y) {
  10034. return isText(node) ? locate$1(doc, node, x, y) : searchInChildren(doc, node, x, y);
  10035. };
  10036. var locate$2 = function (doc, node, x, y) {
  10037. var r = doc.dom().createRange();
  10038. r.selectNode(node.dom());
  10039. var rect = r.getBoundingClientRect();
  10040. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  10041. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  10042. return locateNode(doc, node, boundedX, boundedY);
  10043. };
  10044. var first$1 = function (element) {
  10045. return descendant(element, isCursorPosition);
  10046. };
  10047. var last = function (element) {
  10048. return descendantRtl(element, isCursorPosition);
  10049. };
  10050. var descendantRtl = function (scope, predicate) {
  10051. var descend = function (element) {
  10052. var children$1 = children(element);
  10053. for (var i = children$1.length - 1; i >= 0; i--) {
  10054. var child = children$1[i];
  10055. if (predicate(child)) {
  10056. return Option.some(child);
  10057. }
  10058. var res = descend(child);
  10059. if (res.isSome()) {
  10060. return res;
  10061. }
  10062. }
  10063. return Option.none();
  10064. };
  10065. return descend(scope);
  10066. };
  10067. var COLLAPSE_TO_LEFT = true;
  10068. var COLLAPSE_TO_RIGHT = false;
  10069. var getCollapseDirection = function (rect, x) {
  10070. return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
  10071. };
  10072. var createCollapsedNode = function (doc, target, collapseDirection) {
  10073. var r = doc.dom().createRange();
  10074. r.selectNode(target.dom());
  10075. r.collapse(collapseDirection);
  10076. return r;
  10077. };
  10078. var locateInElement = function (doc, node, x) {
  10079. var cursorRange = doc.dom().createRange();
  10080. cursorRange.selectNode(node.dom());
  10081. var rect = cursorRange.getBoundingClientRect();
  10082. var collapseDirection = getCollapseDirection(rect, x);
  10083. var f = collapseDirection === COLLAPSE_TO_LEFT ? first$1 : last;
  10084. return f(node).map(function (target) {
  10085. return createCollapsedNode(doc, target, collapseDirection);
  10086. });
  10087. };
  10088. var locateInEmpty = function (doc, node, x) {
  10089. var rect = node.dom().getBoundingClientRect();
  10090. var collapseDirection = getCollapseDirection(rect, x);
  10091. return Option.some(createCollapsedNode(doc, node, collapseDirection));
  10092. };
  10093. var search$1 = function (doc, node, x) {
  10094. var f = children(node).length === 0 ? locateInEmpty : locateInElement;
  10095. return f(doc, node, x);
  10096. };
  10097. var caretPositionFromPoint = function (doc, x, y) {
  10098. return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) {
  10099. if (pos.offsetNode === null) {
  10100. return Option.none();
  10101. }
  10102. var r = doc.dom().createRange();
  10103. r.setStart(pos.offsetNode, pos.offset);
  10104. r.collapse();
  10105. return Option.some(r);
  10106. });
  10107. };
  10108. var caretRangeFromPoint = function (doc, x, y) {
  10109. return Option.from(doc.dom().caretRangeFromPoint(x, y));
  10110. };
  10111. var searchTextNodes = function (doc, node, x, y) {
  10112. var r = doc.dom().createRange();
  10113. r.selectNode(node.dom());
  10114. var rect = r.getBoundingClientRect();
  10115. var boundedX = Math.max(rect.left, Math.min(rect.right, x));
  10116. var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
  10117. return locate$2(doc, node, boundedX, boundedY);
  10118. };
  10119. var searchFromPoint = function (doc, x, y) {
  10120. return Element.fromPoint(doc, x, y).bind(function (elem) {
  10121. var fallback = function () {
  10122. return search$1(doc, elem, x);
  10123. };
  10124. return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
  10125. });
  10126. };
  10127. var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
  10128. var beforeSpecial = function (element, offset) {
  10129. var name$1 = name(element);
  10130. if ('input' === name$1) {
  10131. return Situ.after(element);
  10132. } else if (!contains([
  10133. 'br',
  10134. 'img'
  10135. ], name$1)) {
  10136. return Situ.on(element, offset);
  10137. } else {
  10138. return offset === 0 ? Situ.before(element) : Situ.after(element);
  10139. }
  10140. };
  10141. var preprocessExact = function (start, soffset, finish, foffset) {
  10142. var startSitu = beforeSpecial(start, soffset);
  10143. var finishSitu = beforeSpecial(finish, foffset);
  10144. return Selection.relative(startSitu, finishSitu);
  10145. };
  10146. var makeRange = function (start, soffset, finish, foffset) {
  10147. var doc = owner(start);
  10148. var rng = doc.dom().createRange();
  10149. rng.setStart(start.dom(), soffset);
  10150. rng.setEnd(finish.dom(), foffset);
  10151. return rng;
  10152. };
  10153. var after$2 = function (start, soffset, finish, foffset) {
  10154. var r = makeRange(start, soffset, finish, foffset);
  10155. var same = eq(start, finish) && soffset === foffset;
  10156. return r.collapsed && !same;
  10157. };
  10158. var doSetNativeRange = function (win, rng) {
  10159. Option.from(win.getSelection()).each(function (selection) {
  10160. selection.removeAllRanges();
  10161. selection.addRange(rng);
  10162. });
  10163. };
  10164. var doSetRange = function (win, start, soffset, finish, foffset) {
  10165. var rng = exactToNative(win, start, soffset, finish, foffset);
  10166. doSetNativeRange(win, rng);
  10167. };
  10168. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  10169. selection.collapse(start.dom(), soffset);
  10170. selection.extend(finish.dom(), foffset);
  10171. };
  10172. var setRangeFromRelative = function (win, relative) {
  10173. return diagnose(win, relative).match({
  10174. ltr: function (start, soffset, finish, foffset) {
  10175. doSetRange(win, start, soffset, finish, foffset);
  10176. },
  10177. rtl: function (start, soffset, finish, foffset) {
  10178. var selection = win.getSelection();
  10179. if (selection.setBaseAndExtent) {
  10180. selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
  10181. } else if (selection.extend) {
  10182. try {
  10183. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  10184. } catch (e) {
  10185. doSetRange(win, finish, foffset, start, soffset);
  10186. }
  10187. } else {
  10188. doSetRange(win, finish, foffset, start, soffset);
  10189. }
  10190. }
  10191. });
  10192. };
  10193. var setExact = function (win, start, soffset, finish, foffset) {
  10194. var relative = preprocessExact(start, soffset, finish, foffset);
  10195. setRangeFromRelative(win, relative);
  10196. };
  10197. var readRange = function (selection) {
  10198. if (selection.rangeCount > 0) {
  10199. var firstRng = selection.getRangeAt(0);
  10200. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  10201. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  10202. } else {
  10203. return Option.none();
  10204. }
  10205. };
  10206. var doGetExact = function (selection) {
  10207. var anchor = Element.fromDom(selection.anchorNode);
  10208. var focus = Element.fromDom(selection.focusNode);
  10209. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  10210. };
  10211. var getExact = function (win) {
  10212. return Option.from(win.getSelection()).filter(function (sel) {
  10213. return sel.rangeCount > 0;
  10214. }).bind(doGetExact);
  10215. };
  10216. var get$c = function (win) {
  10217. return getExact(win).map(function (range) {
  10218. return Selection.exact(range.start(), range.soffset(), range.finish(), range.foffset());
  10219. });
  10220. };
  10221. var getFirstRect$1 = function (win, selection) {
  10222. var rng = asLtrRange(win, selection);
  10223. return getFirstRect(rng);
  10224. };
  10225. var clear$1 = function (win) {
  10226. var selection = win.getSelection();
  10227. selection.removeAllRanges();
  10228. };
  10229. var COLLAPSED_WIDTH = 2;
  10230. var collapsedRect = function (rect) {
  10231. return {
  10232. left: rect.left,
  10233. top: rect.top,
  10234. right: rect.right,
  10235. bottom: rect.bottom,
  10236. width: constant(COLLAPSED_WIDTH),
  10237. height: rect.height
  10238. };
  10239. };
  10240. var toRect$1 = function (rawRect) {
  10241. return {
  10242. left: constant(rawRect.left),
  10243. top: constant(rawRect.top),
  10244. right: constant(rawRect.right),
  10245. bottom: constant(rawRect.bottom),
  10246. width: constant(rawRect.width),
  10247. height: constant(rawRect.height)
  10248. };
  10249. };
  10250. var getRectsFromRange = function (range) {
  10251. if (!range.collapsed) {
  10252. return map$1(range.getClientRects(), toRect$1);
  10253. } else {
  10254. var start_1 = Element.fromDom(range.startContainer);
  10255. return parent(start_1).bind(function (parent) {
  10256. var selection = Selection.exact(start_1, range.startOffset, parent, getEnd(parent));
  10257. var optRect = getFirstRect$1(range.startContainer.ownerDocument.defaultView, selection);
  10258. return optRect.map(collapsedRect).map(pure);
  10259. }).getOr([]);
  10260. }
  10261. };
  10262. var getRectangles = function (cWin) {
  10263. var sel = cWin.getSelection();
  10264. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  10265. };
  10266. var Rectangles = { getRectangles: getRectangles };
  10267. var autocompleteHack = function () {
  10268. return function (f) {
  10269. global$4.setTimeout(function () {
  10270. f();
  10271. }, 0);
  10272. };
  10273. };
  10274. var resume = function (cWin) {
  10275. cWin.focus();
  10276. var iBody = Element.fromDom(cWin.document.body);
  10277. var inInput = active().exists(function (elem) {
  10278. return contains([
  10279. 'input',
  10280. 'textarea'
  10281. ], name(elem));
  10282. });
  10283. var transaction = inInput ? autocompleteHack() : apply;
  10284. transaction(function () {
  10285. active().each(blur);
  10286. focus$1(iBody);
  10287. });
  10288. };
  10289. var ResumeEditing = { resume: resume };
  10290. var EXTRA_SPACING = 50;
  10291. var data = 'data-' + Styles.resolve('last-outer-height');
  10292. var setLastHeight = function (cBody, value) {
  10293. set(cBody, data, value);
  10294. };
  10295. var getLastHeight = function (cBody) {
  10296. return DataAttributes.safeParse(cBody, data);
  10297. };
  10298. var getBoundsFrom = function (rect) {
  10299. return {
  10300. top: constant(rect.top()),
  10301. bottom: constant(rect.top() + rect.height())
  10302. };
  10303. };
  10304. var getBounds$1 = function (cWin) {
  10305. var rects = Rectangles.getRectangles(cWin);
  10306. return rects.length > 0 ? Option.some(rects[0]).map(getBoundsFrom) : Option.none();
  10307. };
  10308. var findDelta = function (outerWindow, cBody) {
  10309. var last = getLastHeight(cBody);
  10310. var current = outerWindow.innerHeight;
  10311. return last > current ? Option.some(last - current) : Option.none();
  10312. };
  10313. var calculate = function (cWin, bounds, delta) {
  10314. var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
  10315. return isOutside ? Math.min(delta, bounds.bottom() - cWin.innerHeight + EXTRA_SPACING) : 0;
  10316. };
  10317. var setup$1 = function (outerWindow, cWin) {
  10318. var cBody = Element.fromDom(cWin.document.body);
  10319. var toEditing = function () {
  10320. ResumeEditing.resume(cWin);
  10321. };
  10322. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  10323. findDelta(outerWindow, cBody).each(function (delta) {
  10324. getBounds$1(cWin).each(function (bounds) {
  10325. var cScrollBy = calculate(cWin, bounds, delta);
  10326. if (cScrollBy !== 0) {
  10327. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10328. }
  10329. });
  10330. });
  10331. setLastHeight(cBody, outerWindow.innerHeight);
  10332. });
  10333. setLastHeight(cBody, outerWindow.innerHeight);
  10334. var destroy = function () {
  10335. onResize.unbind();
  10336. };
  10337. return {
  10338. toEditing: toEditing,
  10339. destroy: destroy
  10340. };
  10341. };
  10342. var AndroidSetup = { setup: setup$1 };
  10343. var getBodyFromFrame = function (frame) {
  10344. return Option.some(Element.fromDom(frame.dom().contentWindow.document.body));
  10345. };
  10346. var getDocFromFrame = function (frame) {
  10347. return Option.some(Element.fromDom(frame.dom().contentWindow.document));
  10348. };
  10349. var getWinFromFrame = function (frame) {
  10350. return Option.from(frame.dom().contentWindow);
  10351. };
  10352. var getSelectionFromFrame = function (frame) {
  10353. var optWin = getWinFromFrame(frame);
  10354. return optWin.bind(getExact);
  10355. };
  10356. var getFrame = function (editor) {
  10357. return editor.getFrame();
  10358. };
  10359. var getOrDerive = function (name, f) {
  10360. return function (editor) {
  10361. var g = editor[name].getOrThunk(function () {
  10362. var frame = getFrame(editor);
  10363. return function () {
  10364. return f(frame);
  10365. };
  10366. });
  10367. return g();
  10368. };
  10369. };
  10370. var getOrListen = function (editor, doc, name, type) {
  10371. return editor[name].getOrThunk(function () {
  10372. return function (handler) {
  10373. return bind$3(doc, type, handler);
  10374. };
  10375. });
  10376. };
  10377. var toRect$2 = function (rect) {
  10378. return {
  10379. left: constant(rect.left),
  10380. top: constant(rect.top),
  10381. right: constant(rect.right),
  10382. bottom: constant(rect.bottom),
  10383. width: constant(rect.width),
  10384. height: constant(rect.height)
  10385. };
  10386. };
  10387. var getActiveApi = function (editor) {
  10388. var frame = getFrame(editor);
  10389. var tryFallbackBox = function (win) {
  10390. var isCollapsed = function (sel) {
  10391. return eq(sel.start(), sel.finish()) && sel.soffset() === sel.foffset();
  10392. };
  10393. var toStartRect = function (sel) {
  10394. var rect = sel.start().dom().getBoundingClientRect();
  10395. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect$2) : Option.none();
  10396. };
  10397. return getExact(win).filter(isCollapsed).bind(toStartRect);
  10398. };
  10399. return getBodyFromFrame(frame).bind(function (body) {
  10400. return getDocFromFrame(frame).bind(function (doc) {
  10401. return getWinFromFrame(frame).map(function (win) {
  10402. var html = Element.fromDom(doc.dom().documentElement);
  10403. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  10404. return function () {
  10405. return get$c(win).bind(function (sel) {
  10406. return getFirstRect$1(win, sel).orThunk(function () {
  10407. return tryFallbackBox(win);
  10408. });
  10409. });
  10410. };
  10411. });
  10412. var setSelection = editor.setSelection.getOrThunk(function () {
  10413. return function (start, soffset, finish, foffset) {
  10414. setExact(win, start, soffset, finish, foffset);
  10415. };
  10416. });
  10417. var clearSelection = editor.clearSelection.getOrThunk(function () {
  10418. return function () {
  10419. clear$1(win);
  10420. };
  10421. });
  10422. return {
  10423. body: constant(body),
  10424. doc: constant(doc),
  10425. win: constant(win),
  10426. html: constant(html),
  10427. getSelection: curry(getSelectionFromFrame, frame),
  10428. setSelection: setSelection,
  10429. clearSelection: clearSelection,
  10430. frame: constant(frame),
  10431. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  10432. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  10433. onDomChanged: editor.onDomChanged,
  10434. onScrollToCursor: editor.onScrollToCursor,
  10435. onScrollToElement: editor.onScrollToElement,
  10436. onToReading: editor.onToReading,
  10437. onToEditing: editor.onToEditing,
  10438. onToolbarScrollStart: editor.onToolbarScrollStart,
  10439. onTouchContent: editor.onTouchContent,
  10440. onTapContent: editor.onTapContent,
  10441. onTouchToolstrip: editor.onTouchToolstrip,
  10442. getCursorBox: getCursorBox
  10443. };
  10444. });
  10445. });
  10446. });
  10447. };
  10448. var PlatformEditor = {
  10449. getBody: getOrDerive('getBody', getBodyFromFrame),
  10450. getDoc: getOrDerive('getDoc', getDocFromFrame),
  10451. getWin: getOrDerive('getWin', getWinFromFrame),
  10452. getSelection: getOrDerive('getSelection', getSelectionFromFrame),
  10453. getFrame: getFrame,
  10454. getActiveApi: getActiveApi
  10455. };
  10456. var attr = 'data-ephox-mobile-fullscreen-style';
  10457. var siblingStyles = 'display:none!important;';
  10458. var ancestorPosition = 'position:absolute!important;';
  10459. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  10460. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  10461. var isAndroid = detect$3().os.isAndroid();
  10462. var matchColor = function (editorBody) {
  10463. var color = get$3(editorBody, 'background-color');
  10464. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  10465. };
  10466. var clobberStyles = function (container, editorBody) {
  10467. var gatherSibilings = function (element) {
  10468. var siblings = siblings$2(element, '*');
  10469. return siblings;
  10470. };
  10471. var clobber = function (clobberStyle) {
  10472. return function (element) {
  10473. var styles = get(element, 'style');
  10474. var backup = styles === undefined ? 'no-styles' : styles.trim();
  10475. if (backup === clobberStyle) {
  10476. return;
  10477. } else {
  10478. set(element, attr, backup);
  10479. set(element, 'style', clobberStyle);
  10480. }
  10481. };
  10482. };
  10483. var ancestors = ancestors$1(container, '*');
  10484. var siblings = bind(ancestors, gatherSibilings);
  10485. var bgColor = matchColor(editorBody);
  10486. each$1(siblings, clobber(siblingStyles));
  10487. each$1(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor));
  10488. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  10489. clobber(containerStyles + ancestorStyles + bgColor)(container);
  10490. };
  10491. var restoreStyles = function () {
  10492. var clobberedEls = all$2('[' + attr + ']');
  10493. each$1(clobberedEls, function (element) {
  10494. var restore = get(element, attr);
  10495. if (restore !== 'no-styles') {
  10496. set(element, 'style', restore);
  10497. } else {
  10498. remove$1(element, 'style');
  10499. }
  10500. remove$1(element, attr);
  10501. });
  10502. };
  10503. var Thor = {
  10504. clobberStyles: clobberStyles,
  10505. restoreStyles: restoreStyles
  10506. };
  10507. var tag = function () {
  10508. var head = first('head').getOrDie();
  10509. var nu = function () {
  10510. var meta = Element.fromTag('meta');
  10511. set(meta, 'name', 'viewport');
  10512. append(head, meta);
  10513. return meta;
  10514. };
  10515. var element = first('meta[name="viewport"]').getOrThunk(nu);
  10516. var backup = get(element, 'content');
  10517. var maximize = function () {
  10518. set(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  10519. };
  10520. var restore = function () {
  10521. if (backup !== undefined && backup !== null && backup.length > 0) {
  10522. set(element, 'content', backup);
  10523. } else {
  10524. set(element, 'content', 'user-scalable=yes');
  10525. }
  10526. };
  10527. return {
  10528. maximize: maximize,
  10529. restore: restore
  10530. };
  10531. };
  10532. var MetaViewport = { tag: tag };
  10533. var create$4 = function (platform, mask) {
  10534. var meta = MetaViewport.tag();
  10535. var androidApi = api$2();
  10536. var androidEvents = api$2();
  10537. var enter = function () {
  10538. mask.hide();
  10539. add$2(platform.container, Styles.resolve('fullscreen-maximized'));
  10540. add$2(platform.container, Styles.resolve('android-maximized'));
  10541. meta.maximize();
  10542. add$2(platform.body, Styles.resolve('android-scroll-reload'));
  10543. androidApi.set(AndroidSetup.setup(platform.win, PlatformEditor.getWin(platform.editor).getOrDie('no')));
  10544. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  10545. Thor.clobberStyles(platform.container, editorApi.body());
  10546. androidEvents.set(AndroidEvents.initEvents(editorApi, platform.toolstrip, platform.alloy));
  10547. });
  10548. };
  10549. var exit = function () {
  10550. meta.restore();
  10551. mask.show();
  10552. remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
  10553. remove$4(platform.container, Styles.resolve('android-maximized'));
  10554. Thor.restoreStyles();
  10555. remove$4(platform.body, Styles.resolve('android-scroll-reload'));
  10556. androidEvents.clear();
  10557. androidApi.clear();
  10558. };
  10559. return {
  10560. enter: enter,
  10561. exit: exit
  10562. };
  10563. };
  10564. var AndroidMode = { create: create$4 };
  10565. var first$2 = function (fn, rate) {
  10566. var timer = null;
  10567. var cancel = function () {
  10568. if (timer !== null) {
  10569. domGlobals.clearTimeout(timer);
  10570. timer = null;
  10571. }
  10572. };
  10573. var throttle = function () {
  10574. var args = [];
  10575. for (var _i = 0; _i < arguments.length; _i++) {
  10576. args[_i] = arguments[_i];
  10577. }
  10578. if (timer === null) {
  10579. timer = domGlobals.setTimeout(function () {
  10580. fn.apply(null, args);
  10581. timer = null;
  10582. }, rate);
  10583. }
  10584. };
  10585. return {
  10586. cancel: cancel,
  10587. throttle: throttle
  10588. };
  10589. };
  10590. var last$1 = function (fn, rate) {
  10591. var timer = null;
  10592. var cancel = function () {
  10593. if (timer !== null) {
  10594. domGlobals.clearTimeout(timer);
  10595. timer = null;
  10596. }
  10597. };
  10598. var throttle = function () {
  10599. var args = [];
  10600. for (var _i = 0; _i < arguments.length; _i++) {
  10601. args[_i] = arguments[_i];
  10602. }
  10603. if (timer !== null) {
  10604. domGlobals.clearTimeout(timer);
  10605. }
  10606. timer = domGlobals.setTimeout(function () {
  10607. fn.apply(null, args);
  10608. timer = null;
  10609. }, rate);
  10610. };
  10611. return {
  10612. cancel: cancel,
  10613. throttle: throttle
  10614. };
  10615. };
  10616. var sketch$9 = function (onView, translate) {
  10617. var memIcon = record(Container.sketch({
  10618. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10619. containerBehaviours: derive$1([Toggling.config({
  10620. toggleClass: Styles.resolve('mask-tap-icon-selected'),
  10621. toggleOnExecute: false
  10622. })])
  10623. }));
  10624. var onViewThrottle = first$2(onView, 200);
  10625. return Container.sketch({
  10626. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10627. components: [Container.sketch({
  10628. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10629. components: [Button.sketch({
  10630. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10631. components: [memIcon.asSpec()],
  10632. action: function (button) {
  10633. onViewThrottle.throttle();
  10634. },
  10635. buttonBehaviours: derive$1([Toggling.config({ toggleClass: Styles.resolve('mask-tap-icon-selected') })])
  10636. })]
  10637. })]
  10638. });
  10639. };
  10640. var TapToEditMask = { sketch: sketch$9 };
  10641. var MobileSchema = objOf([
  10642. strictObjOf('editor', [
  10643. strict$1('getFrame'),
  10644. option('getBody'),
  10645. option('getDoc'),
  10646. option('getWin'),
  10647. option('getSelection'),
  10648. option('setSelection'),
  10649. option('clearSelection'),
  10650. option('cursorSaver'),
  10651. option('onKeyup'),
  10652. option('onNodeChanged'),
  10653. option('getCursorBox'),
  10654. strict$1('onDomChanged'),
  10655. defaulted$1('onTouchContent', noop),
  10656. defaulted$1('onTapContent', noop),
  10657. defaulted$1('onTouchToolstrip', noop),
  10658. defaulted$1('onScrollToCursor', constant({ unbind: noop })),
  10659. defaulted$1('onScrollToElement', constant({ unbind: noop })),
  10660. defaulted$1('onToEditing', constant({ unbind: noop })),
  10661. defaulted$1('onToReading', constant({ unbind: noop })),
  10662. defaulted$1('onToolbarScrollStart', identity)
  10663. ]),
  10664. strict$1('socket'),
  10665. strict$1('toolstrip'),
  10666. strict$1('dropup'),
  10667. strict$1('toolbar'),
  10668. strict$1('container'),
  10669. strict$1('alloy'),
  10670. state$1('win', function (spec) {
  10671. return owner(spec.socket).dom().defaultView;
  10672. }),
  10673. state$1('body', function (spec) {
  10674. return Element.fromDom(spec.socket.dom().ownerDocument.body);
  10675. }),
  10676. defaulted$1('translate', identity),
  10677. defaulted$1('setReadOnly', noop),
  10678. defaulted$1('readOnlyOnInit', constant(true))
  10679. ]);
  10680. var produce = function (raw) {
  10681. var mobile = asRawOrDie('Getting AndroidWebapp schema', MobileSchema, raw);
  10682. set$3(mobile.toolstrip, 'width', '100%');
  10683. var onTap = function () {
  10684. mobile.setReadOnly(mobile.readOnlyOnInit());
  10685. mode.enter();
  10686. };
  10687. var mask = build$1(TapToEditMask.sketch(onTap, mobile.translate));
  10688. mobile.alloy.add(mask);
  10689. var maskApi = {
  10690. show: function () {
  10691. mobile.alloy.add(mask);
  10692. },
  10693. hide: function () {
  10694. mobile.alloy.remove(mask);
  10695. }
  10696. };
  10697. append(mobile.container, mask.element());
  10698. var mode = AndroidMode.create(mobile, maskApi);
  10699. return {
  10700. setReadOnly: mobile.setReadOnly,
  10701. refreshStructure: noop,
  10702. enter: mode.enter,
  10703. exit: mode.exit,
  10704. destroy: noop
  10705. };
  10706. };
  10707. var AndroidWebapp = { produce: produce };
  10708. var schema$e = constant([
  10709. strict$1('dom'),
  10710. defaulted$1('shell', true),
  10711. field$1('toolbarBehaviours', [Replacing])
  10712. ]);
  10713. var enhanceGroups = function (detail) {
  10714. return { behaviours: derive$1([Replacing.config({})]) };
  10715. };
  10716. var parts$2 = constant([optional({
  10717. name: 'groups',
  10718. overrides: enhanceGroups
  10719. })]);
  10720. var factory$4 = function (detail, components, spec, _externals) {
  10721. var setGroups = function (toolbar, groups) {
  10722. getGroupContainer(toolbar).fold(function () {
  10723. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10724. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10725. }, function (container) {
  10726. Replacing.set(container, groups);
  10727. });
  10728. };
  10729. var getGroupContainer = function (component) {
  10730. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  10731. };
  10732. var extra = detail.shell ? {
  10733. behaviours: [Replacing.config({})],
  10734. components: []
  10735. } : {
  10736. behaviours: [],
  10737. components: components
  10738. };
  10739. return {
  10740. uid: detail.uid,
  10741. dom: detail.dom,
  10742. components: extra.components,
  10743. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10744. apis: { setGroups: setGroups },
  10745. domModification: { attributes: { role: 'group' } }
  10746. };
  10747. };
  10748. var Toolbar = composite$1({
  10749. name: 'Toolbar',
  10750. configFields: schema$e(),
  10751. partFields: parts$2(),
  10752. factory: factory$4,
  10753. apis: {
  10754. setGroups: function (apis, toolbar, groups) {
  10755. apis.setGroups(toolbar, groups);
  10756. }
  10757. }
  10758. });
  10759. var schema$f = constant([
  10760. strict$1('items'),
  10761. markers(['itemSelector']),
  10762. field$1('tgroupBehaviours', [Keying])
  10763. ]);
  10764. var parts$3 = constant([group({
  10765. name: 'items',
  10766. unit: 'item'
  10767. })]);
  10768. var factory$5 = function (detail, components, spec, _externals) {
  10769. return {
  10770. uid: detail.uid,
  10771. dom: detail.dom,
  10772. components: components,
  10773. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10774. mode: 'flow',
  10775. selector: detail.markers.itemSelector
  10776. })]),
  10777. domModification: { attributes: { role: 'toolbar' } }
  10778. };
  10779. };
  10780. var ToolbarGroup = composite$1({
  10781. name: 'ToolbarGroup',
  10782. configFields: schema$f(),
  10783. partFields: parts$3(),
  10784. factory: factory$5
  10785. });
  10786. var dataHorizontal = 'data-' + Styles.resolve('horizontal-scroll');
  10787. var canScrollVertically = function (container) {
  10788. container.dom().scrollTop = 1;
  10789. var result = container.dom().scrollTop !== 0;
  10790. container.dom().scrollTop = 0;
  10791. return result;
  10792. };
  10793. var canScrollHorizontally = function (container) {
  10794. container.dom().scrollLeft = 1;
  10795. var result = container.dom().scrollLeft !== 0;
  10796. container.dom().scrollLeft = 0;
  10797. return result;
  10798. };
  10799. var hasVerticalScroll = function (container) {
  10800. return container.dom().scrollTop > 0 || canScrollVertically(container);
  10801. };
  10802. var hasHorizontalScroll = function (container) {
  10803. return container.dom().scrollLeft > 0 || canScrollHorizontally(container);
  10804. };
  10805. var markAsHorizontal = function (container) {
  10806. set(container, dataHorizontal, 'true');
  10807. };
  10808. var hasScroll = function (container) {
  10809. return get(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10810. };
  10811. var exclusive = function (scope, selector) {
  10812. return bind$3(scope, 'touchmove', function (event) {
  10813. closest$2(event.target(), selector).filter(hasScroll).fold(function () {
  10814. event.raw().preventDefault();
  10815. }, noop);
  10816. });
  10817. };
  10818. var Scrollables = {
  10819. exclusive: exclusive,
  10820. markAsHorizontal: markAsHorizontal
  10821. };
  10822. function ScrollingToolbar () {
  10823. var makeGroup = function (gSpec) {
  10824. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10825. return {
  10826. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10827. tgroupBehaviours: derive$1([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, simulatedEvent) {
  10828. set$3(component.element(), 'overflow-x', 'auto');
  10829. Scrollables.markAsHorizontal(component.element());
  10830. Scrollable.register(component.element());
  10831. })] : [])]),
  10832. components: [Container.sketch({ components: [ToolbarGroup.parts().items({})] })],
  10833. markers: { itemSelector: '.' + Styles.resolve('toolbar-group-item') },
  10834. items: gSpec.items
  10835. };
  10836. };
  10837. var toolbar = build$1(Toolbar.sketch({
  10838. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10839. components: [Toolbar.parts().groups({})],
  10840. toolbarBehaviours: derive$1([
  10841. Toggling.config({
  10842. toggleClass: Styles.resolve('context-toolbar'),
  10843. toggleOnExecute: false,
  10844. aria: { mode: 'none' }
  10845. }),
  10846. Keying.config({ mode: 'cyclic' })
  10847. ]),
  10848. shell: true
  10849. }));
  10850. var wrapper = build$1(Container.sketch({
  10851. dom: { classes: [Styles.resolve('toolstrip')] },
  10852. components: [premade$1(toolbar)],
  10853. containerBehaviours: derive$1([Toggling.config({
  10854. toggleClass: Styles.resolve('android-selection-context-toolbar'),
  10855. toggleOnExecute: false
  10856. })])
  10857. }));
  10858. var resetGroups = function () {
  10859. Toolbar.setGroups(toolbar, initGroups.get());
  10860. Toggling.off(toolbar);
  10861. };
  10862. var initGroups = Cell([]);
  10863. var setGroups = function (gs) {
  10864. initGroups.set(gs);
  10865. resetGroups();
  10866. };
  10867. var createGroups = function (gs) {
  10868. return map$1(gs, compose(ToolbarGroup.sketch, makeGroup));
  10869. };
  10870. var refresh = function () {
  10871. };
  10872. var setContextToolbar = function (gs) {
  10873. Toggling.on(toolbar);
  10874. Toolbar.setGroups(toolbar, gs);
  10875. };
  10876. var restoreToolbar = function () {
  10877. if (Toggling.isOn(toolbar)) {
  10878. resetGroups();
  10879. }
  10880. };
  10881. var focus = function () {
  10882. Keying.focusIn(toolbar);
  10883. };
  10884. return {
  10885. wrapper: constant(wrapper),
  10886. toolbar: constant(toolbar),
  10887. createGroups: createGroups,
  10888. setGroups: setGroups,
  10889. setContextToolbar: setContextToolbar,
  10890. restoreToolbar: restoreToolbar,
  10891. refresh: refresh,
  10892. focus: focus
  10893. };
  10894. }
  10895. var makeEditSwitch = function (webapp) {
  10896. return build$1(Button.sketch({
  10897. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10898. action: function () {
  10899. webapp.run(function (w) {
  10900. w.setReadOnly(false);
  10901. });
  10902. }
  10903. }));
  10904. };
  10905. var makeSocket = function () {
  10906. return build$1(Container.sketch({
  10907. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10908. components: [],
  10909. containerBehaviours: derive$1([Replacing.config({})])
  10910. }));
  10911. };
  10912. var showEdit = function (socket, switchToEdit) {
  10913. Replacing.append(socket, premade$1(switchToEdit));
  10914. };
  10915. var hideEdit = function (socket, switchToEdit) {
  10916. Replacing.remove(socket, switchToEdit);
  10917. };
  10918. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10919. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10920. swap(root);
  10921. var f = readOnly ? showEdit : hideEdit;
  10922. f(socket, switchToEdit);
  10923. };
  10924. var CommonRealm = {
  10925. makeEditSwitch: makeEditSwitch,
  10926. makeSocket: makeSocket,
  10927. updateMode: updateMode
  10928. };
  10929. var getAnimationRoot = function (component, slideConfig) {
  10930. return slideConfig.getAnimationRoot.fold(function () {
  10931. return component.element();
  10932. }, function (get) {
  10933. return get(component);
  10934. });
  10935. };
  10936. var getDimensionProperty = function (slideConfig) {
  10937. return slideConfig.dimension.property;
  10938. };
  10939. var getDimension = function (slideConfig, elem) {
  10940. return slideConfig.dimension.getDimension(elem);
  10941. };
  10942. var disableTransitions = function (component, slideConfig) {
  10943. var root = getAnimationRoot(component, slideConfig);
  10944. remove$6(root, [
  10945. slideConfig.shrinkingClass,
  10946. slideConfig.growingClass
  10947. ]);
  10948. };
  10949. var setShrunk = function (component, slideConfig) {
  10950. remove$4(component.element(), slideConfig.openClass);
  10951. add$2(component.element(), slideConfig.closedClass);
  10952. set$3(component.element(), getDimensionProperty(slideConfig), '0px');
  10953. reflow(component.element());
  10954. };
  10955. var setGrown = function (component, slideConfig) {
  10956. remove$4(component.element(), slideConfig.closedClass);
  10957. add$2(component.element(), slideConfig.openClass);
  10958. remove$5(component.element(), getDimensionProperty(slideConfig));
  10959. };
  10960. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10961. slideState.setCollapsed();
  10962. set$3(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  10963. reflow(component.element());
  10964. disableTransitions(component, slideConfig);
  10965. setShrunk(component, slideConfig);
  10966. slideConfig.onStartShrink(component);
  10967. slideConfig.onShrunk(component);
  10968. };
  10969. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10970. var size = calculatedSize.getOrThunk(function () {
  10971. return getDimension(slideConfig, component.element());
  10972. });
  10973. slideState.setCollapsed();
  10974. set$3(component.element(), getDimensionProperty(slideConfig), size);
  10975. reflow(component.element());
  10976. var root = getAnimationRoot(component, slideConfig);
  10977. remove$4(root, slideConfig.growingClass);
  10978. add$2(root, slideConfig.shrinkingClass);
  10979. setShrunk(component, slideConfig);
  10980. slideConfig.onStartShrink(component);
  10981. };
  10982. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10983. var size = getDimension(slideConfig, component.element());
  10984. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10985. shrinker(component, slideConfig, slideState, Option.some(size));
  10986. };
  10987. var doStartGrow = function (component, slideConfig, slideState) {
  10988. var root = getAnimationRoot(component, slideConfig);
  10989. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  10990. var beforeSize = getDimension(slideConfig, component.element());
  10991. setGrown(component, slideConfig);
  10992. var fullSize = getDimension(slideConfig, component.element());
  10993. var startPartialGrow = function () {
  10994. set$3(component.element(), getDimensionProperty(slideConfig), beforeSize);
  10995. reflow(component.element());
  10996. };
  10997. var startCompleteGrow = function () {
  10998. setShrunk(component, slideConfig);
  10999. };
  11000. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  11001. setStartSize();
  11002. remove$4(root, slideConfig.shrinkingClass);
  11003. add$2(root, slideConfig.growingClass);
  11004. setGrown(component, slideConfig);
  11005. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  11006. slideState.setExpanded();
  11007. slideConfig.onStartGrow(component);
  11008. };
  11009. var refresh = function (component, slideConfig, slideState) {
  11010. if (slideState.isExpanded()) {
  11011. remove$5(component.element(), getDimensionProperty(slideConfig));
  11012. var fullSize = getDimension(slideConfig, component.element());
  11013. set$3(component.element(), getDimensionProperty(slideConfig), fullSize);
  11014. }
  11015. };
  11016. var grow = function (component, slideConfig, slideState) {
  11017. if (!slideState.isExpanded()) {
  11018. doStartGrow(component, slideConfig, slideState);
  11019. }
  11020. };
  11021. var shrink = function (component, slideConfig, slideState) {
  11022. if (slideState.isExpanded()) {
  11023. doStartSmartShrink(component, slideConfig, slideState);
  11024. }
  11025. };
  11026. var immediateShrink = function (component, slideConfig, slideState) {
  11027. if (slideState.isExpanded()) {
  11028. doImmediateShrink(component, slideConfig, slideState);
  11029. }
  11030. };
  11031. var hasGrown = function (component, slideConfig, slideState) {
  11032. return slideState.isExpanded();
  11033. };
  11034. var hasShrunk = function (component, slideConfig, slideState) {
  11035. return slideState.isCollapsed();
  11036. };
  11037. var isGrowing = function (component, slideConfig, slideState) {
  11038. var root = getAnimationRoot(component, slideConfig);
  11039. return has$2(root, slideConfig.growingClass) === true;
  11040. };
  11041. var isShrinking = function (component, slideConfig, slideState) {
  11042. var root = getAnimationRoot(component, slideConfig);
  11043. return has$2(root, slideConfig.shrinkingClass) === true;
  11044. };
  11045. var isTransitioning = function (component, slideConfig, slideState) {
  11046. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  11047. };
  11048. var toggleGrow = function (component, slideConfig, slideState) {
  11049. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  11050. f(component, slideConfig, slideState);
  11051. };
  11052. var SlidingApis = /*#__PURE__*/Object.freeze({
  11053. refresh: refresh,
  11054. grow: grow,
  11055. shrink: shrink,
  11056. immediateShrink: immediateShrink,
  11057. hasGrown: hasGrown,
  11058. hasShrunk: hasShrunk,
  11059. isGrowing: isGrowing,
  11060. isShrinking: isShrinking,
  11061. isTransitioning: isTransitioning,
  11062. toggleGrow: toggleGrow,
  11063. disableTransitions: disableTransitions
  11064. });
  11065. var exhibit$5 = function (base, slideConfig) {
  11066. var expanded = slideConfig.expanded;
  11067. return expanded ? nu$5({
  11068. classes: [slideConfig.openClass],
  11069. styles: {}
  11070. }) : nu$5({
  11071. classes: [slideConfig.closedClass],
  11072. styles: wrap$1(slideConfig.dimension.property, '0px')
  11073. });
  11074. };
  11075. var events$a = function (slideConfig, slideState) {
  11076. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  11077. var raw = simulatedEvent.event().raw();
  11078. if (raw.propertyName === slideConfig.dimension.property) {
  11079. disableTransitions(component, slideConfig);
  11080. if (slideState.isExpanded()) {
  11081. remove$5(component.element(), slideConfig.dimension.property);
  11082. }
  11083. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  11084. notify(component);
  11085. }
  11086. })]);
  11087. };
  11088. var ActiveSliding = /*#__PURE__*/Object.freeze({
  11089. exhibit: exhibit$5,
  11090. events: events$a
  11091. });
  11092. var SlidingSchema = [
  11093. strict$1('closedClass'),
  11094. strict$1('openClass'),
  11095. strict$1('shrinkingClass'),
  11096. strict$1('growingClass'),
  11097. option('getAnimationRoot'),
  11098. onHandler('onShrunk'),
  11099. onHandler('onStartShrink'),
  11100. onHandler('onGrown'),
  11101. onHandler('onStartGrow'),
  11102. defaulted$1('expanded', false),
  11103. strictOf('dimension', choose$1('property', {
  11104. width: [
  11105. output('property', 'width'),
  11106. output('getDimension', function (elem) {
  11107. return get$6(elem) + 'px';
  11108. })
  11109. ],
  11110. height: [
  11111. output('property', 'height'),
  11112. output('getDimension', function (elem) {
  11113. return get$4(elem) + 'px';
  11114. })
  11115. ]
  11116. }))
  11117. ];
  11118. var init$4 = function (spec) {
  11119. var state = Cell(spec.expanded);
  11120. var readState = function () {
  11121. return 'expanded: ' + state.get();
  11122. };
  11123. return nu$6({
  11124. isExpanded: function () {
  11125. return state.get() === true;
  11126. },
  11127. isCollapsed: function () {
  11128. return state.get() === false;
  11129. },
  11130. setCollapsed: curry(state.set, false),
  11131. setExpanded: curry(state.set, true),
  11132. readState: readState
  11133. });
  11134. };
  11135. var SlidingState = /*#__PURE__*/Object.freeze({
  11136. init: init$4
  11137. });
  11138. var Sliding = create$1({
  11139. fields: SlidingSchema,
  11140. name: 'sliding',
  11141. active: ActiveSliding,
  11142. apis: SlidingApis,
  11143. state: SlidingState
  11144. });
  11145. var build$2 = function (refresh, scrollIntoView) {
  11146. var dropup = build$1(Container.sketch({
  11147. dom: {
  11148. tag: 'div',
  11149. classes: [Styles.resolve('dropup')]
  11150. },
  11151. components: [],
  11152. containerBehaviours: derive$1([
  11153. Replacing.config({}),
  11154. Sliding.config({
  11155. closedClass: Styles.resolve('dropup-closed'),
  11156. openClass: Styles.resolve('dropup-open'),
  11157. shrinkingClass: Styles.resolve('dropup-shrinking'),
  11158. growingClass: Styles.resolve('dropup-growing'),
  11159. dimension: { property: 'height' },
  11160. onShrunk: function (component) {
  11161. refresh();
  11162. scrollIntoView();
  11163. Replacing.set(component, []);
  11164. },
  11165. onGrown: function (component) {
  11166. refresh();
  11167. scrollIntoView();
  11168. }
  11169. }),
  11170. Receivers.orientation(function (component, data) {
  11171. disappear(noop);
  11172. })
  11173. ])
  11174. }));
  11175. var appear = function (menu, update, component) {
  11176. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  11177. domGlobals.window.requestAnimationFrame(function () {
  11178. update(component);
  11179. Replacing.set(dropup, [menu()]);
  11180. Sliding.grow(dropup);
  11181. });
  11182. }
  11183. };
  11184. var disappear = function (onReadyToShrink) {
  11185. domGlobals.window.requestAnimationFrame(function () {
  11186. onReadyToShrink();
  11187. Sliding.shrink(dropup);
  11188. });
  11189. };
  11190. return {
  11191. appear: appear,
  11192. disappear: disappear,
  11193. component: constant(dropup),
  11194. element: dropup.element
  11195. };
  11196. };
  11197. var closest$3 = function (scope, selector, isRoot) {
  11198. return closest$2(scope, selector, isRoot).isSome();
  11199. };
  11200. var isDangerous = function (event) {
  11201. var keyEv = event.raw();
  11202. return keyEv.which === BACKSPACE()[0] && !contains([
  11203. 'input',
  11204. 'textarea'
  11205. ], name(event.target())) && !closest$3(event.target(), '[contenteditable="true"]');
  11206. };
  11207. var isFirefox = detect$3().browser.isFirefox();
  11208. var settingsSchema = objOfOnly([
  11209. strictFunction('triggerEvent'),
  11210. defaulted$1('stopBackspace', true)
  11211. ]);
  11212. var bindFocus = function (container, handler) {
  11213. if (isFirefox) {
  11214. return capture$1(container, 'focus', handler);
  11215. } else {
  11216. return bind$3(container, 'focusin', handler);
  11217. }
  11218. };
  11219. var bindBlur = function (container, handler) {
  11220. if (isFirefox) {
  11221. return capture$1(container, 'blur', handler);
  11222. } else {
  11223. return bind$3(container, 'focusout', handler);
  11224. }
  11225. };
  11226. var setup$2 = function (container, rawSettings) {
  11227. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  11228. var pointerEvents = detect$3().deviceType.isTouch() ? [
  11229. 'touchstart',
  11230. 'touchmove',
  11231. 'touchend',
  11232. 'gesturestart'
  11233. ] : [
  11234. 'mousedown',
  11235. 'mouseup',
  11236. 'mouseover',
  11237. 'mousemove',
  11238. 'mouseout',
  11239. 'click'
  11240. ];
  11241. var tapEvent = monitor(settings);
  11242. var simpleEvents = map$1(pointerEvents.concat([
  11243. 'selectstart',
  11244. 'input',
  11245. 'contextmenu',
  11246. 'change',
  11247. 'transitionend',
  11248. 'drag',
  11249. 'dragstart',
  11250. 'dragend',
  11251. 'dragenter',
  11252. 'dragleave',
  11253. 'dragover',
  11254. 'drop',
  11255. 'keyup'
  11256. ]), function (type) {
  11257. return bind$3(container, type, function (event) {
  11258. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  11259. if (tapStopped) {
  11260. event.kill();
  11261. }
  11262. });
  11263. var stopped = settings.triggerEvent(type, event);
  11264. if (stopped) {
  11265. event.kill();
  11266. }
  11267. });
  11268. });
  11269. var pasteTimeout = Cell(Option.none());
  11270. var onPaste = bind$3(container, 'paste', function (event) {
  11271. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11272. if (tapStopped) {
  11273. event.kill();
  11274. }
  11275. });
  11276. var stopped = settings.triggerEvent('paste', event);
  11277. if (stopped) {
  11278. event.kill();
  11279. }
  11280. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11281. settings.triggerEvent(postPaste(), event);
  11282. }, 0)));
  11283. });
  11284. var onKeydown = bind$3(container, 'keydown', function (event) {
  11285. var stopped = settings.triggerEvent('keydown', event);
  11286. if (stopped) {
  11287. event.kill();
  11288. } else if (settings.stopBackspace === true && isDangerous(event)) {
  11289. event.prevent();
  11290. }
  11291. });
  11292. var onFocusIn = bindFocus(container, function (event) {
  11293. var stopped = settings.triggerEvent('focusin', event);
  11294. if (stopped) {
  11295. event.kill();
  11296. }
  11297. });
  11298. var focusoutTimeout = Cell(Option.none());
  11299. var onFocusOut = bindBlur(container, function (event) {
  11300. var stopped = settings.triggerEvent('focusout', event);
  11301. if (stopped) {
  11302. event.kill();
  11303. }
  11304. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11305. settings.triggerEvent(postBlur(), event);
  11306. }, 0)));
  11307. });
  11308. var unbind = function () {
  11309. each$1(simpleEvents, function (e) {
  11310. e.unbind();
  11311. });
  11312. onKeydown.unbind();
  11313. onFocusIn.unbind();
  11314. onFocusOut.unbind();
  11315. onPaste.unbind();
  11316. pasteTimeout.get().each(domGlobals.clearTimeout);
  11317. focusoutTimeout.get().each(domGlobals.clearTimeout);
  11318. };
  11319. return { unbind: unbind };
  11320. };
  11321. var derive$2 = function (rawEvent, rawTarget) {
  11322. var source = readOptFrom$1(rawEvent, 'target').map(function (getTarget) {
  11323. return getTarget();
  11324. }).getOr(rawTarget);
  11325. return Cell(source);
  11326. };
  11327. var fromSource = function (event, source) {
  11328. var stopper = Cell(false);
  11329. var cutter = Cell(false);
  11330. var stop = function () {
  11331. stopper.set(true);
  11332. };
  11333. var cut = function () {
  11334. cutter.set(true);
  11335. };
  11336. return {
  11337. stop: stop,
  11338. cut: cut,
  11339. isStopped: stopper.get,
  11340. isCut: cutter.get,
  11341. event: constant(event),
  11342. setSource: source.set,
  11343. getSource: source.get
  11344. };
  11345. };
  11346. var fromExternal = function (event) {
  11347. var stopper = Cell(false);
  11348. var stop = function () {
  11349. stopper.set(true);
  11350. };
  11351. return {
  11352. stop: stop,
  11353. cut: noop,
  11354. isStopped: stopper.get,
  11355. isCut: constant(false),
  11356. event: constant(event),
  11357. setSource: die('Cannot set source of a broadcasted event'),
  11358. getSource: die('Cannot get source of a broadcasted event')
  11359. };
  11360. };
  11361. var adt$7 = Adt.generate([
  11362. { stopped: [] },
  11363. { resume: ['element'] },
  11364. { complete: [] }
  11365. ]);
  11366. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11367. var handler = lookup(eventType, target);
  11368. var simulatedEvent = fromSource(rawEvent, source);
  11369. return handler.fold(function () {
  11370. logger.logEventNoHandlers(eventType, target);
  11371. return adt$7.complete();
  11372. }, function (handlerInfo) {
  11373. var descHandler = handlerInfo.descHandler();
  11374. var eventHandler = getCurried(descHandler);
  11375. eventHandler(simulatedEvent);
  11376. if (simulatedEvent.isStopped()) {
  11377. logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose());
  11378. return adt$7.stopped();
  11379. } else if (simulatedEvent.isCut()) {
  11380. logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose());
  11381. return adt$7.complete();
  11382. } else {
  11383. return parent(handlerInfo.element()).fold(function () {
  11384. logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose());
  11385. return adt$7.complete();
  11386. }, function (parent) {
  11387. logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose());
  11388. return adt$7.resume(parent);
  11389. });
  11390. }
  11391. });
  11392. };
  11393. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11394. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  11395. return true;
  11396. }, function (parent) {
  11397. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11398. }, function () {
  11399. return false;
  11400. });
  11401. };
  11402. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11403. var source = derive$2(rawEvent, target);
  11404. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11405. };
  11406. var broadcast = function (listeners, rawEvent, logger) {
  11407. var simulatedEvent = fromExternal(rawEvent);
  11408. each$1(listeners, function (listener) {
  11409. var descHandler = listener.descHandler();
  11410. var handler = getCurried(descHandler);
  11411. handler(simulatedEvent);
  11412. });
  11413. return simulatedEvent.isStopped();
  11414. };
  11415. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11416. var rawTarget = rawEvent.target();
  11417. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  11418. };
  11419. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11420. var source = derive$2(rawEvent, rawTarget);
  11421. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11422. };
  11423. var eventHandler = Immutable('element', 'descHandler');
  11424. var broadcastHandler = function (id, handler) {
  11425. return {
  11426. id: constant(id),
  11427. descHandler: constant(handler)
  11428. };
  11429. };
  11430. function EventRegistry () {
  11431. var registry = {};
  11432. var registerId = function (extraArgs, id, events) {
  11433. each(events, function (v, k) {
  11434. var handlers = registry[k] !== undefined ? registry[k] : {};
  11435. handlers[id] = curryArgs(v, extraArgs);
  11436. registry[k] = handlers;
  11437. });
  11438. };
  11439. var findHandler = function (handlers, elem) {
  11440. return read$2(elem).fold(function () {
  11441. return Option.none();
  11442. }, function (id) {
  11443. var reader = readOpt$1(id);
  11444. return handlers.bind(reader).map(function (descHandler) {
  11445. return eventHandler(elem, descHandler);
  11446. });
  11447. });
  11448. };
  11449. var filterByType = function (type) {
  11450. return readOptFrom$1(registry, type).map(function (handlers) {
  11451. return mapToArray(handlers, function (f, id) {
  11452. return broadcastHandler(id, f);
  11453. });
  11454. }).getOr([]);
  11455. };
  11456. var find = function (isAboveRoot, type, target) {
  11457. var readType = readOpt$1(type);
  11458. var handlers = readType(registry);
  11459. return closest$1(target, function (elem) {
  11460. return findHandler(handlers, elem);
  11461. }, isAboveRoot);
  11462. };
  11463. var unregisterId = function (id) {
  11464. each(registry, function (handlersById, eventName) {
  11465. if (handlersById.hasOwnProperty(id)) {
  11466. delete handlersById[id];
  11467. }
  11468. });
  11469. };
  11470. return {
  11471. registerId: registerId,
  11472. unregisterId: unregisterId,
  11473. filterByType: filterByType,
  11474. find: find
  11475. };
  11476. }
  11477. function Registry () {
  11478. var events = EventRegistry();
  11479. var components = {};
  11480. var readOrTag = function (component) {
  11481. var elem = component.element();
  11482. return read$2(elem).fold(function () {
  11483. return write('uid-', component.element());
  11484. }, function (uid) {
  11485. return uid;
  11486. });
  11487. };
  11488. var failOnDuplicate = function (component, tagId) {
  11489. var conflict = components[tagId];
  11490. if (conflict === component) {
  11491. unregister(component);
  11492. } else {
  11493. 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');
  11494. }
  11495. };
  11496. var register = function (component) {
  11497. var tagId = readOrTag(component);
  11498. if (hasKey$1(components, tagId)) {
  11499. failOnDuplicate(component, tagId);
  11500. }
  11501. var extraArgs = [component];
  11502. events.registerId(extraArgs, tagId, component.events());
  11503. components[tagId] = component;
  11504. };
  11505. var unregister = function (component) {
  11506. read$2(component.element()).each(function (tagId) {
  11507. delete components[tagId];
  11508. events.unregisterId(tagId);
  11509. });
  11510. };
  11511. var filter = function (type) {
  11512. return events.filterByType(type);
  11513. };
  11514. var find = function (isAboveRoot, type, target) {
  11515. return events.find(isAboveRoot, type, target);
  11516. };
  11517. var getById = function (id) {
  11518. return readOpt$1(id)(components);
  11519. };
  11520. return {
  11521. find: find,
  11522. filter: filter,
  11523. register: register,
  11524. unregister: unregister,
  11525. getById: getById
  11526. };
  11527. }
  11528. var takeover = function (root) {
  11529. var isAboveRoot = function (el) {
  11530. return parent(root.element()).fold(function () {
  11531. return true;
  11532. }, function (parent) {
  11533. return eq(el, parent);
  11534. });
  11535. };
  11536. var registry = Registry();
  11537. var lookup = function (eventName, target) {
  11538. return registry.find(isAboveRoot, eventName, target);
  11539. };
  11540. var domEvents = setup$2(root.element(), {
  11541. triggerEvent: function (eventName, event) {
  11542. return monitorEvent(eventName, event.target(), function (logger) {
  11543. return triggerUntilStopped(lookup, eventName, event, logger);
  11544. });
  11545. }
  11546. });
  11547. var systemApi = {
  11548. debugInfo: constant('real'),
  11549. triggerEvent: function (eventName, target, data) {
  11550. monitorEvent(eventName, target, function (logger) {
  11551. triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11552. });
  11553. },
  11554. triggerFocus: function (target, originator) {
  11555. read$2(target).fold(function () {
  11556. focus$1(target);
  11557. }, function (_alloyId) {
  11558. monitorEvent(focus(), target, function (logger) {
  11559. triggerHandler(lookup, focus(), {
  11560. originator: constant(originator),
  11561. kill: noop,
  11562. prevent: noop,
  11563. target: constant(target)
  11564. }, target, logger);
  11565. });
  11566. });
  11567. },
  11568. triggerEscape: function (comp, simulatedEvent) {
  11569. systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
  11570. },
  11571. getByUid: function (uid) {
  11572. return getByUid(uid);
  11573. },
  11574. getByDom: function (elem) {
  11575. return getByDom(elem);
  11576. },
  11577. build: build$1,
  11578. addToGui: function (c) {
  11579. add(c);
  11580. },
  11581. removeFromGui: function (c) {
  11582. remove$1(c);
  11583. },
  11584. addToWorld: function (c) {
  11585. addToWorld(c);
  11586. },
  11587. removeFromWorld: function (c) {
  11588. removeFromWorld(c);
  11589. },
  11590. broadcast: function (message) {
  11591. broadcast$1(message);
  11592. },
  11593. broadcastOn: function (channels, message) {
  11594. broadcastOn(channels, message);
  11595. },
  11596. broadcastEvent: function (eventName, event) {
  11597. broadcastEvent(eventName, event);
  11598. },
  11599. isConnected: constant(true)
  11600. };
  11601. var addToWorld = function (component) {
  11602. component.connect(systemApi);
  11603. if (!isText(component.element())) {
  11604. registry.register(component);
  11605. each$1(component.components(), addToWorld);
  11606. systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
  11607. }
  11608. };
  11609. var removeFromWorld = function (component) {
  11610. if (!isText(component.element())) {
  11611. each$1(component.components(), removeFromWorld);
  11612. registry.unregister(component);
  11613. }
  11614. component.disconnect();
  11615. };
  11616. var add = function (component) {
  11617. attach$1(root, component);
  11618. };
  11619. var remove$1 = function (component) {
  11620. detach(component);
  11621. };
  11622. var destroy = function () {
  11623. domEvents.unbind();
  11624. remove(root.element());
  11625. };
  11626. var broadcastData = function (data) {
  11627. var receivers = registry.filter(receive());
  11628. each$1(receivers, function (receiver) {
  11629. var descHandler = receiver.descHandler();
  11630. var handler = getCurried(descHandler);
  11631. handler(data);
  11632. });
  11633. };
  11634. var broadcast$1 = function (message) {
  11635. broadcastData({
  11636. universal: constant(true),
  11637. data: constant(message)
  11638. });
  11639. };
  11640. var broadcastOn = function (channels, message) {
  11641. broadcastData({
  11642. universal: constant(false),
  11643. channels: constant(channels),
  11644. data: constant(message)
  11645. });
  11646. };
  11647. var broadcastEvent = function (eventName, event) {
  11648. var listeners = registry.filter(eventName);
  11649. return broadcast(listeners, event);
  11650. };
  11651. var getByUid = function (uid) {
  11652. return registry.getById(uid).fold(function () {
  11653. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11654. }, Result.value);
  11655. };
  11656. var getByDom = function (elem) {
  11657. var uid = read$2(elem).getOr('not found');
  11658. return getByUid(uid);
  11659. };
  11660. addToWorld(root);
  11661. return {
  11662. root: constant(root),
  11663. element: root.element,
  11664. destroy: destroy,
  11665. add: add,
  11666. remove: remove$1,
  11667. getByUid: getByUid,
  11668. getByDom: getByDom,
  11669. addToWorld: addToWorld,
  11670. removeFromWorld: removeFromWorld,
  11671. broadcast: broadcast$1,
  11672. broadcastOn: broadcastOn,
  11673. broadcastEvent: broadcastEvent
  11674. };
  11675. };
  11676. var READ_ONLY_MODE_CLASS = constant(Styles.resolve('readonly-mode'));
  11677. var EDIT_MODE_CLASS = constant(Styles.resolve('edit-mode'));
  11678. function OuterContainer (spec) {
  11679. var root = build$1(Container.sketch({
  11680. dom: { classes: [Styles.resolve('outer-container')].concat(spec.classes) },
  11681. containerBehaviours: derive$1([Swapping.config({
  11682. alpha: READ_ONLY_MODE_CLASS(),
  11683. omega: EDIT_MODE_CLASS()
  11684. })])
  11685. }));
  11686. return takeover(root);
  11687. }
  11688. function AndroidRealm (scrollIntoView) {
  11689. var alloy = OuterContainer({ classes: [Styles.resolve('android-container')] });
  11690. var toolbar = ScrollingToolbar();
  11691. var webapp = api$2();
  11692. var switchToEdit = CommonRealm.makeEditSwitch(webapp);
  11693. var socket = CommonRealm.makeSocket();
  11694. var dropup = build$2(noop, scrollIntoView);
  11695. alloy.add(toolbar.wrapper());
  11696. alloy.add(socket);
  11697. alloy.add(dropup.component());
  11698. var setToolbarGroups = function (rawGroups) {
  11699. var groups = toolbar.createGroups(rawGroups);
  11700. toolbar.setGroups(groups);
  11701. };
  11702. var setContextToolbar = function (rawGroups) {
  11703. var groups = toolbar.createGroups(rawGroups);
  11704. toolbar.setContextToolbar(groups);
  11705. };
  11706. var focusToolbar = function () {
  11707. toolbar.focus();
  11708. };
  11709. var restoreToolbar = function () {
  11710. toolbar.restoreToolbar();
  11711. };
  11712. var init = function (spec) {
  11713. webapp.set(AndroidWebapp.produce(spec));
  11714. };
  11715. var exit = function () {
  11716. webapp.run(function (w) {
  11717. w.exit();
  11718. Replacing.remove(socket, switchToEdit);
  11719. });
  11720. };
  11721. var updateMode = function (readOnly) {
  11722. CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
  11723. };
  11724. return {
  11725. system: constant(alloy),
  11726. element: alloy.element,
  11727. init: init,
  11728. exit: exit,
  11729. setToolbarGroups: setToolbarGroups,
  11730. setContextToolbar: setContextToolbar,
  11731. focusToolbar: focusToolbar,
  11732. restoreToolbar: restoreToolbar,
  11733. updateMode: updateMode,
  11734. socket: constant(socket),
  11735. dropup: constant(dropup)
  11736. };
  11737. }
  11738. var input$1 = function (parent, operation) {
  11739. var input = Element.fromTag('input');
  11740. setAll$1(input, {
  11741. opacity: '0',
  11742. position: 'absolute',
  11743. top: '-1000px',
  11744. left: '-1000px'
  11745. });
  11746. append(parent, input);
  11747. focus$1(input);
  11748. operation(input);
  11749. remove(input);
  11750. };
  11751. var CaptureBin = { input: input$1 };
  11752. var refreshInput = function (input) {
  11753. var start = input.dom().selectionStart;
  11754. var end = input.dom().selectionEnd;
  11755. var dir = input.dom().selectionDirection;
  11756. global$4.setTimeout(function () {
  11757. input.dom().setSelectionRange(start, end, dir);
  11758. focus$1(input);
  11759. }, 50);
  11760. };
  11761. var refresh$1 = function (winScope) {
  11762. var sel = winScope.getSelection();
  11763. if (sel.rangeCount > 0) {
  11764. var br = sel.getRangeAt(0);
  11765. var r = winScope.document.createRange();
  11766. r.setStart(br.startContainer, br.startOffset);
  11767. r.setEnd(br.endContainer, br.endOffset);
  11768. sel.removeAllRanges();
  11769. sel.addRange(r);
  11770. }
  11771. };
  11772. var CursorRefresh = {
  11773. refreshInput: refreshInput,
  11774. refresh: refresh$1
  11775. };
  11776. var resume$1 = function (cWin, frame) {
  11777. active().each(function (active) {
  11778. if (!eq(active, frame)) {
  11779. blur(active);
  11780. }
  11781. });
  11782. cWin.focus();
  11783. focus$1(Element.fromDom(cWin.document.body));
  11784. CursorRefresh.refresh(cWin);
  11785. };
  11786. var ResumeEditing$1 = { resume: resume$1 };
  11787. var stubborn = function (outerBody, cWin, page, frame) {
  11788. var toEditing = function () {
  11789. ResumeEditing$1.resume(cWin, frame);
  11790. };
  11791. var toReading = function () {
  11792. CaptureBin.input(outerBody, blur);
  11793. };
  11794. var captureInput = bind$3(page, 'keydown', function (evt) {
  11795. if (!contains([
  11796. 'input',
  11797. 'textarea'
  11798. ], name(evt.target()))) {
  11799. toEditing();
  11800. }
  11801. });
  11802. var onToolbarTouch = function () {
  11803. };
  11804. var destroy = function () {
  11805. captureInput.unbind();
  11806. };
  11807. return {
  11808. toReading: toReading,
  11809. toEditing: toEditing,
  11810. onToolbarTouch: onToolbarTouch,
  11811. destroy: destroy
  11812. };
  11813. };
  11814. var timid = function (outerBody, cWin, page, frame) {
  11815. var dismissKeyboard = function () {
  11816. blur(frame);
  11817. };
  11818. var onToolbarTouch = function () {
  11819. dismissKeyboard();
  11820. };
  11821. var toReading = function () {
  11822. dismissKeyboard();
  11823. };
  11824. var toEditing = function () {
  11825. ResumeEditing$1.resume(cWin, frame);
  11826. };
  11827. return {
  11828. toReading: toReading,
  11829. toEditing: toEditing,
  11830. onToolbarTouch: onToolbarTouch,
  11831. destroy: noop
  11832. };
  11833. };
  11834. var IosKeyboard = {
  11835. stubborn: stubborn,
  11836. timid: timid
  11837. };
  11838. var initEvents$1 = function (editorApi, iosApi, toolstrip, socket, dropup) {
  11839. var saveSelectionFirst = function () {
  11840. iosApi.run(function (api) {
  11841. api.highlightSelection();
  11842. });
  11843. };
  11844. var refreshIosSelection = function () {
  11845. iosApi.run(function (api) {
  11846. api.refreshSelection();
  11847. });
  11848. };
  11849. var scrollToY = function (yTop, height) {
  11850. var y = yTop - socket.dom().scrollTop;
  11851. iosApi.run(function (api) {
  11852. api.scrollIntoView(y, y + height);
  11853. });
  11854. };
  11855. var scrollToElement = function (target) {
  11856. scrollToY(iosApi, socket);
  11857. };
  11858. var scrollToCursor = function () {
  11859. editorApi.getCursorBox().each(function (box) {
  11860. scrollToY(box.top(), box.height());
  11861. });
  11862. };
  11863. var clearSelection = function () {
  11864. iosApi.run(function (api) {
  11865. api.clearSelection();
  11866. });
  11867. };
  11868. var clearAndRefresh = function () {
  11869. clearSelection();
  11870. refreshThrottle.throttle();
  11871. };
  11872. var refreshView = function () {
  11873. scrollToCursor();
  11874. iosApi.run(function (api) {
  11875. api.syncHeight();
  11876. });
  11877. };
  11878. var reposition = function () {
  11879. var toolbarHeight = get$4(toolstrip);
  11880. iosApi.run(function (api) {
  11881. api.setViewportOffset(toolbarHeight);
  11882. });
  11883. refreshIosSelection();
  11884. refreshView();
  11885. };
  11886. var toEditing = function () {
  11887. iosApi.run(function (api) {
  11888. api.toEditing();
  11889. });
  11890. };
  11891. var toReading = function () {
  11892. iosApi.run(function (api) {
  11893. api.toReading();
  11894. });
  11895. };
  11896. var onToolbarTouch = function (event) {
  11897. iosApi.run(function (api) {
  11898. api.onToolbarTouch(event);
  11899. });
  11900. };
  11901. var tapping = TappingEvent.monitor(editorApi);
  11902. var refreshThrottle = last$1(refreshView, 300);
  11903. var listeners = [
  11904. editorApi.onKeyup(clearAndRefresh),
  11905. editorApi.onNodeChanged(refreshIosSelection),
  11906. editorApi.onDomChanged(refreshThrottle.throttle),
  11907. editorApi.onDomChanged(refreshIosSelection),
  11908. editorApi.onScrollToCursor(function (tinyEvent) {
  11909. tinyEvent.preventDefault();
  11910. refreshThrottle.throttle();
  11911. }),
  11912. editorApi.onScrollToElement(function (event) {
  11913. scrollToElement(event.element());
  11914. }),
  11915. editorApi.onToEditing(toEditing),
  11916. editorApi.onToReading(toReading),
  11917. bind$3(editorApi.doc(), 'touchend', function (touchEvent) {
  11918. if (eq(editorApi.html(), touchEvent.target()) || eq(editorApi.body(), touchEvent.target())) ;
  11919. }),
  11920. bind$3(toolstrip, 'transitionend', function (transitionEvent) {
  11921. if (transitionEvent.raw().propertyName === 'height') {
  11922. reposition();
  11923. }
  11924. }),
  11925. capture$1(toolstrip, 'touchstart', function (touchEvent) {
  11926. saveSelectionFirst();
  11927. onToolbarTouch(touchEvent);
  11928. editorApi.onTouchToolstrip();
  11929. }),
  11930. bind$3(editorApi.body(), 'touchstart', function (evt) {
  11931. clearSelection();
  11932. editorApi.onTouchContent();
  11933. tapping.fireTouchstart(evt);
  11934. }),
  11935. tapping.onTouchmove(),
  11936. tapping.onTouchend(),
  11937. bind$3(editorApi.body(), 'click', function (event) {
  11938. event.kill();
  11939. }),
  11940. bind$3(toolstrip, 'touchmove', function () {
  11941. editorApi.onToolbarScrollStart();
  11942. })
  11943. ];
  11944. var destroy = function () {
  11945. each$1(listeners, function (l) {
  11946. l.unbind();
  11947. });
  11948. };
  11949. return { destroy: destroy };
  11950. };
  11951. var IosEvents = { initEvents: initEvents$1 };
  11952. function FakeSelection (win, frame) {
  11953. var doc = win.document;
  11954. var container = Element.fromTag('div');
  11955. add$2(container, Styles.resolve('unfocused-selections'));
  11956. append(Element.fromDom(doc.documentElement), container);
  11957. var onTouch = bind$3(container, 'touchstart', function (event) {
  11958. event.prevent();
  11959. ResumeEditing$1.resume(win, frame);
  11960. clear();
  11961. });
  11962. var make = function (rectangle) {
  11963. var span = Element.fromTag('span');
  11964. add$3(span, [
  11965. Styles.resolve('layer-editor'),
  11966. Styles.resolve('unfocused-selection')
  11967. ]);
  11968. setAll$1(span, {
  11969. left: rectangle.left() + 'px',
  11970. top: rectangle.top() + 'px',
  11971. width: rectangle.width() + 'px',
  11972. height: rectangle.height() + 'px'
  11973. });
  11974. return span;
  11975. };
  11976. var update = function () {
  11977. clear();
  11978. var rectangles = Rectangles.getRectangles(win);
  11979. var spans = map$1(rectangles, make);
  11980. append$1(container, spans);
  11981. };
  11982. var clear = function () {
  11983. empty(container);
  11984. };
  11985. var destroy = function () {
  11986. onTouch.unbind();
  11987. remove(container);
  11988. };
  11989. var isActive = function () {
  11990. return children(container).length > 0;
  11991. };
  11992. return {
  11993. update: update,
  11994. isActive: isActive,
  11995. destroy: destroy,
  11996. clear: clear
  11997. };
  11998. }
  11999. var exports$1 = {}, module = { exports: exports$1 };
  12000. (function (define, exports, module, require) {
  12001. (function (f) {
  12002. if (typeof exports === 'object' && typeof module !== 'undefined') {
  12003. module.exports = f();
  12004. } else if (typeof define === 'function' && define.amd) {
  12005. define([], f);
  12006. } else {
  12007. var g;
  12008. if (typeof window !== 'undefined') {
  12009. g = window;
  12010. } else if (typeof global !== 'undefined') {
  12011. g = global;
  12012. } else if (typeof self !== 'undefined') {
  12013. g = self;
  12014. } else {
  12015. g = this;
  12016. }
  12017. g.EphoxContactWrapper = f();
  12018. }
  12019. }(function () {
  12020. return function () {
  12021. function r(e, n, t) {
  12022. function o(i, f) {
  12023. if (!n[i]) {
  12024. if (!e[i]) {
  12025. var c = 'function' == typeof require && require;
  12026. if (!f && c)
  12027. return c(i, !0);
  12028. if (u)
  12029. return u(i, !0);
  12030. var a = new Error('Cannot find module \'' + i + '\'');
  12031. throw a.code = 'MODULE_NOT_FOUND', a;
  12032. }
  12033. var p = n[i] = { exports: {} };
  12034. e[i][0].call(p.exports, function (r) {
  12035. var n = e[i][1][r];
  12036. return o(n || r);
  12037. }, p, p.exports, r, e, n, t);
  12038. }
  12039. return n[i].exports;
  12040. }
  12041. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  12042. o(t[i]);
  12043. return o;
  12044. }
  12045. return r;
  12046. }()({
  12047. 1: [
  12048. function (require, module, exports) {
  12049. var process = module.exports = {};
  12050. var cachedSetTimeout;
  12051. var cachedClearTimeout;
  12052. function defaultSetTimout() {
  12053. throw new Error('setTimeout has not been defined');
  12054. }
  12055. function defaultClearTimeout() {
  12056. throw new Error('clearTimeout has not been defined');
  12057. }
  12058. (function () {
  12059. try {
  12060. if (typeof setTimeout === 'function') {
  12061. cachedSetTimeout = setTimeout;
  12062. } else {
  12063. cachedSetTimeout = defaultSetTimout;
  12064. }
  12065. } catch (e) {
  12066. cachedSetTimeout = defaultSetTimout;
  12067. }
  12068. try {
  12069. if (typeof clearTimeout === 'function') {
  12070. cachedClearTimeout = clearTimeout;
  12071. } else {
  12072. cachedClearTimeout = defaultClearTimeout;
  12073. }
  12074. } catch (e) {
  12075. cachedClearTimeout = defaultClearTimeout;
  12076. }
  12077. }());
  12078. function runTimeout(fun) {
  12079. if (cachedSetTimeout === setTimeout) {
  12080. return setTimeout(fun, 0);
  12081. }
  12082. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12083. cachedSetTimeout = setTimeout;
  12084. return setTimeout(fun, 0);
  12085. }
  12086. try {
  12087. return cachedSetTimeout(fun, 0);
  12088. } catch (e) {
  12089. try {
  12090. return cachedSetTimeout.call(null, fun, 0);
  12091. } catch (e) {
  12092. return cachedSetTimeout.call(this, fun, 0);
  12093. }
  12094. }
  12095. }
  12096. function runClearTimeout(marker) {
  12097. if (cachedClearTimeout === clearTimeout) {
  12098. return clearTimeout(marker);
  12099. }
  12100. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12101. cachedClearTimeout = clearTimeout;
  12102. return clearTimeout(marker);
  12103. }
  12104. try {
  12105. return cachedClearTimeout(marker);
  12106. } catch (e) {
  12107. try {
  12108. return cachedClearTimeout.call(null, marker);
  12109. } catch (e) {
  12110. return cachedClearTimeout.call(this, marker);
  12111. }
  12112. }
  12113. }
  12114. var queue = [];
  12115. var draining = false;
  12116. var currentQueue;
  12117. var queueIndex = -1;
  12118. function cleanUpNextTick() {
  12119. if (!draining || !currentQueue) {
  12120. return;
  12121. }
  12122. draining = false;
  12123. if (currentQueue.length) {
  12124. queue = currentQueue.concat(queue);
  12125. } else {
  12126. queueIndex = -1;
  12127. }
  12128. if (queue.length) {
  12129. drainQueue();
  12130. }
  12131. }
  12132. function drainQueue() {
  12133. if (draining) {
  12134. return;
  12135. }
  12136. var timeout = runTimeout(cleanUpNextTick);
  12137. draining = true;
  12138. var len = queue.length;
  12139. while (len) {
  12140. currentQueue = queue;
  12141. queue = [];
  12142. while (++queueIndex < len) {
  12143. if (currentQueue) {
  12144. currentQueue[queueIndex].run();
  12145. }
  12146. }
  12147. queueIndex = -1;
  12148. len = queue.length;
  12149. }
  12150. currentQueue = null;
  12151. draining = false;
  12152. runClearTimeout(timeout);
  12153. }
  12154. process.nextTick = function (fun) {
  12155. var args = new Array(arguments.length - 1);
  12156. if (arguments.length > 1) {
  12157. for (var i = 1; i < arguments.length; i++) {
  12158. args[i - 1] = arguments[i];
  12159. }
  12160. }
  12161. queue.push(new Item(fun, args));
  12162. if (queue.length === 1 && !draining) {
  12163. runTimeout(drainQueue);
  12164. }
  12165. };
  12166. function Item(fun, array) {
  12167. this.fun = fun;
  12168. this.array = array;
  12169. }
  12170. Item.prototype.run = function () {
  12171. this.fun.apply(null, this.array);
  12172. };
  12173. process.title = 'browser';
  12174. process.browser = true;
  12175. process.env = {};
  12176. process.argv = [];
  12177. process.version = '';
  12178. process.versions = {};
  12179. function noop() {
  12180. }
  12181. process.on = noop;
  12182. process.addListener = noop;
  12183. process.once = noop;
  12184. process.off = noop;
  12185. process.removeListener = noop;
  12186. process.removeAllListeners = noop;
  12187. process.emit = noop;
  12188. process.prependListener = noop;
  12189. process.prependOnceListener = noop;
  12190. process.listeners = function (name) {
  12191. return [];
  12192. };
  12193. process.binding = function (name) {
  12194. throw new Error('process.binding is not supported');
  12195. };
  12196. process.cwd = function () {
  12197. return '/';
  12198. };
  12199. process.chdir = function (dir) {
  12200. throw new Error('process.chdir is not supported');
  12201. };
  12202. process.umask = function () {
  12203. return 0;
  12204. };
  12205. },
  12206. {}
  12207. ],
  12208. 2: [
  12209. function (require, module, exports) {
  12210. (function (setImmediate) {
  12211. (function (root) {
  12212. var setTimeoutFunc = setTimeout;
  12213. function noop() {
  12214. }
  12215. function bind(fn, thisArg) {
  12216. return function () {
  12217. fn.apply(thisArg, arguments);
  12218. };
  12219. }
  12220. function Promise(fn) {
  12221. if (typeof this !== 'object')
  12222. throw new TypeError('Promises must be constructed via new');
  12223. if (typeof fn !== 'function')
  12224. throw new TypeError('not a function');
  12225. this._state = 0;
  12226. this._handled = false;
  12227. this._value = undefined;
  12228. this._deferreds = [];
  12229. doResolve(fn, this);
  12230. }
  12231. function handle(self, deferred) {
  12232. while (self._state === 3) {
  12233. self = self._value;
  12234. }
  12235. if (self._state === 0) {
  12236. self._deferreds.push(deferred);
  12237. return;
  12238. }
  12239. self._handled = true;
  12240. Promise._immediateFn(function () {
  12241. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  12242. if (cb === null) {
  12243. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  12244. return;
  12245. }
  12246. var ret;
  12247. try {
  12248. ret = cb(self._value);
  12249. } catch (e) {
  12250. reject(deferred.promise, e);
  12251. return;
  12252. }
  12253. resolve(deferred.promise, ret);
  12254. });
  12255. }
  12256. function resolve(self, newValue) {
  12257. try {
  12258. if (newValue === self)
  12259. throw new TypeError('A promise cannot be resolved with itself.');
  12260. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  12261. var then = newValue.then;
  12262. if (newValue instanceof Promise) {
  12263. self._state = 3;
  12264. self._value = newValue;
  12265. finale(self);
  12266. return;
  12267. } else if (typeof then === 'function') {
  12268. doResolve(bind(then, newValue), self);
  12269. return;
  12270. }
  12271. }
  12272. self._state = 1;
  12273. self._value = newValue;
  12274. finale(self);
  12275. } catch (e) {
  12276. reject(self, e);
  12277. }
  12278. }
  12279. function reject(self, newValue) {
  12280. self._state = 2;
  12281. self._value = newValue;
  12282. finale(self);
  12283. }
  12284. function finale(self) {
  12285. if (self._state === 2 && self._deferreds.length === 0) {
  12286. Promise._immediateFn(function () {
  12287. if (!self._handled) {
  12288. Promise._unhandledRejectionFn(self._value);
  12289. }
  12290. });
  12291. }
  12292. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  12293. handle(self, self._deferreds[i]);
  12294. }
  12295. self._deferreds = null;
  12296. }
  12297. function Handler(onFulfilled, onRejected, promise) {
  12298. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  12299. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  12300. this.promise = promise;
  12301. }
  12302. function doResolve(fn, self) {
  12303. var done = false;
  12304. try {
  12305. fn(function (value) {
  12306. if (done)
  12307. return;
  12308. done = true;
  12309. resolve(self, value);
  12310. }, function (reason) {
  12311. if (done)
  12312. return;
  12313. done = true;
  12314. reject(self, reason);
  12315. });
  12316. } catch (ex) {
  12317. if (done)
  12318. return;
  12319. done = true;
  12320. reject(self, ex);
  12321. }
  12322. }
  12323. Promise.prototype['catch'] = function (onRejected) {
  12324. return this.then(null, onRejected);
  12325. };
  12326. Promise.prototype.then = function (onFulfilled, onRejected) {
  12327. var prom = new this.constructor(noop);
  12328. handle(this, new Handler(onFulfilled, onRejected, prom));
  12329. return prom;
  12330. };
  12331. Promise.all = function (arr) {
  12332. var args = Array.prototype.slice.call(arr);
  12333. return new Promise(function (resolve, reject) {
  12334. if (args.length === 0)
  12335. return resolve([]);
  12336. var remaining = args.length;
  12337. function res(i, val) {
  12338. try {
  12339. if (val && (typeof val === 'object' || typeof val === 'function')) {
  12340. var then = val.then;
  12341. if (typeof then === 'function') {
  12342. then.call(val, function (val) {
  12343. res(i, val);
  12344. }, reject);
  12345. return;
  12346. }
  12347. }
  12348. args[i] = val;
  12349. if (--remaining === 0) {
  12350. resolve(args);
  12351. }
  12352. } catch (ex) {
  12353. reject(ex);
  12354. }
  12355. }
  12356. for (var i = 0; i < args.length; i++) {
  12357. res(i, args[i]);
  12358. }
  12359. });
  12360. };
  12361. Promise.resolve = function (value) {
  12362. if (value && typeof value === 'object' && value.constructor === Promise) {
  12363. return value;
  12364. }
  12365. return new Promise(function (resolve) {
  12366. resolve(value);
  12367. });
  12368. };
  12369. Promise.reject = function (value) {
  12370. return new Promise(function (resolve, reject) {
  12371. reject(value);
  12372. });
  12373. };
  12374. Promise.race = function (values) {
  12375. return new Promise(function (resolve, reject) {
  12376. for (var i = 0, len = values.length; i < len; i++) {
  12377. values[i].then(resolve, reject);
  12378. }
  12379. });
  12380. };
  12381. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  12382. setImmediate(fn);
  12383. } : function (fn) {
  12384. setTimeoutFunc(fn, 0);
  12385. };
  12386. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  12387. if (typeof console !== 'undefined' && console) {
  12388. console.warn('Possible Unhandled Promise Rejection:', err);
  12389. }
  12390. };
  12391. Promise._setImmediateFn = function _setImmediateFn(fn) {
  12392. Promise._immediateFn = fn;
  12393. };
  12394. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  12395. Promise._unhandledRejectionFn = fn;
  12396. };
  12397. if (typeof module !== 'undefined' && module.exports) {
  12398. module.exports = Promise;
  12399. } else if (!root.Promise) {
  12400. root.Promise = Promise;
  12401. }
  12402. }(this));
  12403. }.call(this, require('timers').setImmediate));
  12404. },
  12405. { 'timers': 3 }
  12406. ],
  12407. 3: [
  12408. function (require, module, exports) {
  12409. (function (setImmediate, clearImmediate) {
  12410. var nextTick = require('process/browser.js').nextTick;
  12411. var apply = Function.prototype.apply;
  12412. var slice = Array.prototype.slice;
  12413. var immediateIds = {};
  12414. var nextImmediateId = 0;
  12415. exports.setTimeout = function () {
  12416. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  12417. };
  12418. exports.setInterval = function () {
  12419. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12420. };
  12421. exports.clearTimeout = exports.clearInterval = function (timeout) {
  12422. timeout.close();
  12423. };
  12424. function Timeout(id, clearFn) {
  12425. this._id = id;
  12426. this._clearFn = clearFn;
  12427. }
  12428. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  12429. };
  12430. Timeout.prototype.close = function () {
  12431. this._clearFn.call(window, this._id);
  12432. };
  12433. exports.enroll = function (item, msecs) {
  12434. clearTimeout(item._idleTimeoutId);
  12435. item._idleTimeout = msecs;
  12436. };
  12437. exports.unenroll = function (item) {
  12438. clearTimeout(item._idleTimeoutId);
  12439. item._idleTimeout = -1;
  12440. };
  12441. exports._unrefActive = exports.active = function (item) {
  12442. clearTimeout(item._idleTimeoutId);
  12443. var msecs = item._idleTimeout;
  12444. if (msecs >= 0) {
  12445. item._idleTimeoutId = setTimeout(function onTimeout() {
  12446. if (item._onTimeout)
  12447. item._onTimeout();
  12448. }, msecs);
  12449. }
  12450. };
  12451. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  12452. var id = nextImmediateId++;
  12453. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  12454. immediateIds[id] = true;
  12455. nextTick(function onNextTick() {
  12456. if (immediateIds[id]) {
  12457. if (args) {
  12458. fn.apply(null, args);
  12459. } else {
  12460. fn.call(null);
  12461. }
  12462. exports.clearImmediate(id);
  12463. }
  12464. });
  12465. return id;
  12466. };
  12467. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  12468. delete immediateIds[id];
  12469. };
  12470. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  12471. },
  12472. {
  12473. 'process/browser.js': 1,
  12474. 'timers': 3
  12475. }
  12476. ],
  12477. 4: [
  12478. function (require, module, exports) {
  12479. var promisePolyfill = require('promise-polyfill');
  12480. var Global = function () {
  12481. if (typeof window !== 'undefined') {
  12482. return window;
  12483. } else {
  12484. return Function('return this;')();
  12485. }
  12486. }();
  12487. module.exports = { boltExport: Global.Promise || promisePolyfill };
  12488. },
  12489. { 'promise-polyfill': 2 }
  12490. ]
  12491. }, {}, [4])(4);
  12492. }));
  12493. }(undefined, exports$1, module, undefined));
  12494. var Promise$1 = module.exports.boltExport;
  12495. var nu$7 = function (baseFn) {
  12496. var data = Option.none();
  12497. var callbacks = [];
  12498. var map = function (f) {
  12499. return nu$7(function (nCallback) {
  12500. get(function (data) {
  12501. nCallback(f(data));
  12502. });
  12503. });
  12504. };
  12505. var get = function (nCallback) {
  12506. if (isReady()) {
  12507. call(nCallback);
  12508. } else {
  12509. callbacks.push(nCallback);
  12510. }
  12511. };
  12512. var set = function (x) {
  12513. data = Option.some(x);
  12514. run(callbacks);
  12515. callbacks = [];
  12516. };
  12517. var isReady = function () {
  12518. return data.isSome();
  12519. };
  12520. var run = function (cbs) {
  12521. each$1(cbs, call);
  12522. };
  12523. var call = function (cb) {
  12524. data.each(function (x) {
  12525. domGlobals.setTimeout(function () {
  12526. cb(x);
  12527. }, 0);
  12528. });
  12529. };
  12530. baseFn(set);
  12531. return {
  12532. get: get,
  12533. map: map,
  12534. isReady: isReady
  12535. };
  12536. };
  12537. var pure$1 = function (a) {
  12538. return nu$7(function (callback) {
  12539. callback(a);
  12540. });
  12541. };
  12542. var LazyValue = {
  12543. nu: nu$7,
  12544. pure: pure$1
  12545. };
  12546. var errorReporter = function (err) {
  12547. domGlobals.setTimeout(function () {
  12548. throw err;
  12549. }, 0);
  12550. };
  12551. var make$4 = function (run) {
  12552. var get = function (callback) {
  12553. run().then(callback, errorReporter);
  12554. };
  12555. var map = function (fab) {
  12556. return make$4(function () {
  12557. return run().then(fab);
  12558. });
  12559. };
  12560. var bind = function (aFutureB) {
  12561. return make$4(function () {
  12562. return run().then(function (v) {
  12563. return aFutureB(v).toPromise();
  12564. });
  12565. });
  12566. };
  12567. var anonBind = function (futureB) {
  12568. return make$4(function () {
  12569. return run().then(function () {
  12570. return futureB.toPromise();
  12571. });
  12572. });
  12573. };
  12574. var toLazy = function () {
  12575. return LazyValue.nu(get);
  12576. };
  12577. var toCached = function () {
  12578. var cache = null;
  12579. return make$4(function () {
  12580. if (cache === null) {
  12581. cache = run();
  12582. }
  12583. return cache;
  12584. });
  12585. };
  12586. var toPromise = run;
  12587. return {
  12588. map: map,
  12589. bind: bind,
  12590. anonBind: anonBind,
  12591. toLazy: toLazy,
  12592. toCached: toCached,
  12593. toPromise: toPromise,
  12594. get: get
  12595. };
  12596. };
  12597. var nu$8 = function (baseFn) {
  12598. return make$4(function () {
  12599. return new Promise$1(baseFn);
  12600. });
  12601. };
  12602. var pure$2 = function (a) {
  12603. return make$4(function () {
  12604. return Promise$1.resolve(a);
  12605. });
  12606. };
  12607. var Future = {
  12608. nu: nu$8,
  12609. pure: pure$2
  12610. };
  12611. var adjust = function (value, destination, amount) {
  12612. if (Math.abs(value - destination) <= amount) {
  12613. return Option.none();
  12614. } else if (value < destination) {
  12615. return Option.some(value + amount);
  12616. } else {
  12617. return Option.some(value - amount);
  12618. }
  12619. };
  12620. var create$5 = function () {
  12621. var interval = null;
  12622. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  12623. var finished = false;
  12624. var finish = function (v) {
  12625. finished = true;
  12626. doFinish(v);
  12627. };
  12628. global$4.clearInterval(interval);
  12629. var abort = function (v) {
  12630. global$4.clearInterval(interval);
  12631. finish(v);
  12632. };
  12633. interval = global$4.setInterval(function () {
  12634. var value = getCurrent();
  12635. adjust(value, destination, amount).fold(function () {
  12636. global$4.clearInterval(interval);
  12637. finish(destination);
  12638. }, function (s) {
  12639. increment(s, abort);
  12640. if (!finished) {
  12641. var newValue = getCurrent();
  12642. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  12643. global$4.clearInterval(interval);
  12644. finish(destination);
  12645. }
  12646. }
  12647. });
  12648. }, rate);
  12649. };
  12650. return { animate: animate };
  12651. };
  12652. var SmoothAnimation = {
  12653. create: create$5,
  12654. adjust: adjust
  12655. };
  12656. var findDevice = function (deviceWidth, deviceHeight) {
  12657. var devices = [
  12658. {
  12659. width: 320,
  12660. height: 480,
  12661. keyboard: {
  12662. portrait: 300,
  12663. landscape: 240
  12664. }
  12665. },
  12666. {
  12667. width: 320,
  12668. height: 568,
  12669. keyboard: {
  12670. portrait: 300,
  12671. landscape: 240
  12672. }
  12673. },
  12674. {
  12675. width: 375,
  12676. height: 667,
  12677. keyboard: {
  12678. portrait: 305,
  12679. landscape: 240
  12680. }
  12681. },
  12682. {
  12683. width: 414,
  12684. height: 736,
  12685. keyboard: {
  12686. portrait: 320,
  12687. landscape: 240
  12688. }
  12689. },
  12690. {
  12691. width: 768,
  12692. height: 1024,
  12693. keyboard: {
  12694. portrait: 320,
  12695. landscape: 400
  12696. }
  12697. },
  12698. {
  12699. width: 1024,
  12700. height: 1366,
  12701. keyboard: {
  12702. portrait: 380,
  12703. landscape: 460
  12704. }
  12705. }
  12706. ];
  12707. return findMap(devices, function (device) {
  12708. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  12709. }).getOr({
  12710. portrait: deviceHeight / 5,
  12711. landscape: deviceWidth / 4
  12712. });
  12713. };
  12714. var softKeyboardLimits = function (outerWindow) {
  12715. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  12716. };
  12717. var accountableKeyboardHeight = function (outerWindow) {
  12718. var portrait = Orientation.get(outerWindow).isPortrait();
  12719. var limits = softKeyboardLimits(outerWindow);
  12720. var keyboard = portrait ? limits.portrait : limits.landscape;
  12721. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  12722. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  12723. };
  12724. var getGreenzone = function (socket, dropup) {
  12725. var outerWindow = owner(socket).dom().defaultView;
  12726. var viewportHeight = get$4(socket) + get$4(dropup);
  12727. var acc = accountableKeyboardHeight(outerWindow);
  12728. return viewportHeight - acc;
  12729. };
  12730. var updatePadding = function (contentBody, socket, dropup) {
  12731. var greenzoneHeight = getGreenzone(socket, dropup);
  12732. var deltaHeight = get$4(socket) + get$4(dropup) - greenzoneHeight;
  12733. set$3(contentBody, 'padding-bottom', deltaHeight + 'px');
  12734. };
  12735. var DeviceZones = {
  12736. getGreenzone: getGreenzone,
  12737. updatePadding: updatePadding
  12738. };
  12739. var fixture = Adt.generate([
  12740. {
  12741. fixed: [
  12742. 'element',
  12743. 'property',
  12744. 'offsetY'
  12745. ]
  12746. },
  12747. {
  12748. scroller: [
  12749. 'element',
  12750. 'offsetY'
  12751. ]
  12752. }
  12753. ]);
  12754. var yFixedData = 'data-' + Styles.resolve('position-y-fixed');
  12755. var yFixedProperty = 'data-' + Styles.resolve('y-property');
  12756. var yScrollingData = 'data-' + Styles.resolve('scrolling');
  12757. var windowSizeData = 'data-' + Styles.resolve('last-window-height');
  12758. var getYFixedData = function (element) {
  12759. return DataAttributes.safeParse(element, yFixedData);
  12760. };
  12761. var getYFixedProperty = function (element) {
  12762. return get(element, yFixedProperty);
  12763. };
  12764. var getLastWindowSize = function (element) {
  12765. return DataAttributes.safeParse(element, windowSizeData);
  12766. };
  12767. var classifyFixed = function (element, offsetY) {
  12768. var prop = getYFixedProperty(element);
  12769. return fixture.fixed(element, prop, offsetY);
  12770. };
  12771. var classifyScrolling = function (element, offsetY) {
  12772. return fixture.scroller(element, offsetY);
  12773. };
  12774. var classify = function (element) {
  12775. var offsetY = getYFixedData(element);
  12776. var classifier = get(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  12777. return classifier(element, offsetY);
  12778. };
  12779. var findFixtures = function (container) {
  12780. var candidates = descendants(container, '[' + yFixedData + ']');
  12781. return map$1(candidates, classify);
  12782. };
  12783. var takeoverToolbar = function (toolbar) {
  12784. var oldToolbarStyle = get(toolbar, 'style');
  12785. setAll$1(toolbar, {
  12786. position: 'absolute',
  12787. top: '0px'
  12788. });
  12789. set(toolbar, yFixedData, '0px');
  12790. set(toolbar, yFixedProperty, 'top');
  12791. var restore = function () {
  12792. set(toolbar, 'style', oldToolbarStyle || '');
  12793. remove$1(toolbar, yFixedData);
  12794. remove$1(toolbar, yFixedProperty);
  12795. };
  12796. return { restore: restore };
  12797. };
  12798. var takeoverViewport = function (toolbarHeight, height, viewport) {
  12799. var oldViewportStyle = get(viewport, 'style');
  12800. Scrollable.register(viewport);
  12801. setAll$1(viewport, {
  12802. position: 'absolute',
  12803. height: height + 'px',
  12804. width: '100%',
  12805. top: toolbarHeight + 'px'
  12806. });
  12807. set(viewport, yFixedData, toolbarHeight + 'px');
  12808. set(viewport, yScrollingData, 'true');
  12809. set(viewport, yFixedProperty, 'top');
  12810. var restore = function () {
  12811. Scrollable.deregister(viewport);
  12812. set(viewport, 'style', oldViewportStyle || '');
  12813. remove$1(viewport, yFixedData);
  12814. remove$1(viewport, yScrollingData);
  12815. remove$1(viewport, yFixedProperty);
  12816. };
  12817. return { restore: restore };
  12818. };
  12819. var takeoverDropup = function (dropup, toolbarHeight, viewportHeight) {
  12820. var oldDropupStyle = get(dropup, 'style');
  12821. setAll$1(dropup, {
  12822. position: 'absolute',
  12823. bottom: '0px'
  12824. });
  12825. set(dropup, yFixedData, '0px');
  12826. set(dropup, yFixedProperty, 'bottom');
  12827. var restore = function () {
  12828. set(dropup, 'style', oldDropupStyle || '');
  12829. remove$1(dropup, yFixedData);
  12830. remove$1(dropup, yFixedProperty);
  12831. };
  12832. return { restore: restore };
  12833. };
  12834. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12835. var outerWindow = owner(viewport).dom().defaultView;
  12836. var winH = outerWindow.innerHeight;
  12837. set(viewport, windowSizeData, winH + 'px');
  12838. return winH - toolbarHeight - dropupHeight;
  12839. };
  12840. var takeover$1 = function (viewport, contentBody, toolbar, dropup) {
  12841. var outerWindow = owner(viewport).dom().defaultView;
  12842. var toolbarSetup = takeoverToolbar(toolbar);
  12843. var toolbarHeight = get$4(toolbar);
  12844. var dropupHeight = get$4(dropup);
  12845. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12846. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12847. var dropupSetup = takeoverDropup(dropup);
  12848. var isActive = true;
  12849. var restore = function () {
  12850. isActive = false;
  12851. toolbarSetup.restore();
  12852. viewportSetup.restore();
  12853. dropupSetup.restore();
  12854. };
  12855. var isExpanding = function () {
  12856. var currentWinHeight = outerWindow.innerHeight;
  12857. var lastWinHeight = getLastWindowSize(viewport);
  12858. return currentWinHeight > lastWinHeight;
  12859. };
  12860. var refresh = function () {
  12861. if (isActive) {
  12862. var newToolbarHeight = get$4(toolbar);
  12863. var dropupHeight_1 = get$4(dropup);
  12864. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12865. set(viewport, yFixedData, newToolbarHeight + 'px');
  12866. set$3(viewport, 'height', newHeight + 'px');
  12867. DeviceZones.updatePadding(contentBody, viewport, dropup);
  12868. }
  12869. };
  12870. var setViewportOffset = function (newYOffset) {
  12871. var offsetPx = newYOffset + 'px';
  12872. set(viewport, yFixedData, offsetPx);
  12873. refresh();
  12874. };
  12875. DeviceZones.updatePadding(contentBody, viewport, dropup);
  12876. return {
  12877. setViewportOffset: setViewportOffset,
  12878. isExpanding: isExpanding,
  12879. isShrinking: not(isExpanding),
  12880. refresh: refresh,
  12881. restore: restore
  12882. };
  12883. };
  12884. var IosViewport = {
  12885. findFixtures: findFixtures,
  12886. takeover: takeover$1,
  12887. getYFixedData: getYFixedData
  12888. };
  12889. var animator = SmoothAnimation.create();
  12890. var ANIMATION_STEP = 15;
  12891. var NUM_TOP_ANIMATION_FRAMES = 10;
  12892. var ANIMATION_RATE = 10;
  12893. var lastScroll = 'data-' + Styles.resolve('last-scroll-top');
  12894. var getTop = function (element) {
  12895. var raw = getRaw(element, 'top').getOr('0');
  12896. return parseInt(raw, 10);
  12897. };
  12898. var getScrollTop = function (element) {
  12899. return parseInt(element.dom().scrollTop, 10);
  12900. };
  12901. var moveScrollAndTop = function (element, destination, finalTop) {
  12902. return Future.nu(function (callback) {
  12903. var getCurrent = curry(getScrollTop, element);
  12904. var update = function (newScroll) {
  12905. element.dom().scrollTop = newScroll;
  12906. set$3(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12907. };
  12908. var finish = function () {
  12909. element.dom().scrollTop = destination;
  12910. set$3(element, 'top', finalTop + 'px');
  12911. callback(destination);
  12912. };
  12913. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12914. });
  12915. };
  12916. var moveOnlyScroll = function (element, destination) {
  12917. return Future.nu(function (callback) {
  12918. var getCurrent = curry(getScrollTop, element);
  12919. set(element, lastScroll, getCurrent());
  12920. var update = function (newScroll, abort) {
  12921. var previous = DataAttributes.safeParse(element, lastScroll);
  12922. if (previous !== element.dom().scrollTop) {
  12923. abort(element.dom().scrollTop);
  12924. } else {
  12925. element.dom().scrollTop = newScroll;
  12926. set(element, lastScroll, newScroll);
  12927. }
  12928. };
  12929. var finish = function () {
  12930. element.dom().scrollTop = destination;
  12931. set(element, lastScroll, destination);
  12932. callback(destination);
  12933. };
  12934. var distance = Math.abs(destination - getCurrent());
  12935. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12936. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12937. });
  12938. };
  12939. var moveOnlyTop = function (element, destination) {
  12940. return Future.nu(function (callback) {
  12941. var getCurrent = curry(getTop, element);
  12942. var update = function (newTop) {
  12943. set$3(element, 'top', newTop + 'px');
  12944. };
  12945. var finish = function () {
  12946. update(destination);
  12947. callback(destination);
  12948. };
  12949. var distance = Math.abs(destination - getCurrent());
  12950. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12951. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12952. });
  12953. };
  12954. var updateTop = function (element, amount) {
  12955. var newTop = amount + IosViewport.getYFixedData(element) + 'px';
  12956. set$3(element, 'top', newTop);
  12957. };
  12958. var moveWindowScroll = function (toolbar, viewport, destY) {
  12959. var outerWindow = owner(toolbar).dom().defaultView;
  12960. return Future.nu(function (callback) {
  12961. updateTop(toolbar, destY);
  12962. updateTop(viewport, destY);
  12963. outerWindow.scrollTo(0, destY);
  12964. callback(destY);
  12965. });
  12966. };
  12967. var IosScrolling = {
  12968. moveScrollAndTop: moveScrollAndTop,
  12969. moveOnlyScroll: moveOnlyScroll,
  12970. moveOnlyTop: moveOnlyTop,
  12971. moveWindowScroll: moveWindowScroll
  12972. };
  12973. function BackgroundActivity (doAction) {
  12974. var action = Cell(LazyValue.pure({}));
  12975. var start = function (value) {
  12976. var future = LazyValue.nu(function (callback) {
  12977. return doAction(value).get(callback);
  12978. });
  12979. action.set(future);
  12980. };
  12981. var idle = function (g) {
  12982. action.get().get(function () {
  12983. g();
  12984. });
  12985. };
  12986. return {
  12987. start: start,
  12988. idle: idle
  12989. };
  12990. }
  12991. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12992. var greenzone = DeviceZones.getGreenzone(socket, dropup);
  12993. var refreshCursor = curry(CursorRefresh.refresh, cWin);
  12994. if (top > greenzone || bottom > greenzone) {
  12995. IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop - greenzone + bottom).get(refreshCursor);
  12996. } else if (top < 0) {
  12997. IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop + top).get(refreshCursor);
  12998. }
  12999. };
  13000. var Greenzone = { scrollIntoView: scrollIntoView };
  13001. var par = function (asyncValues, nu) {
  13002. return nu(function (callback) {
  13003. var r = [];
  13004. var count = 0;
  13005. var cb = function (i) {
  13006. return function (value) {
  13007. r[i] = value;
  13008. count++;
  13009. if (count >= asyncValues.length) {
  13010. callback(r);
  13011. }
  13012. };
  13013. };
  13014. if (asyncValues.length === 0) {
  13015. callback([]);
  13016. } else {
  13017. each$1(asyncValues, function (asyncValue, i) {
  13018. asyncValue.get(cb(i));
  13019. });
  13020. }
  13021. });
  13022. };
  13023. var par$1 = function (futures) {
  13024. return par(futures, Future.nu);
  13025. };
  13026. var updateFixed = function (element, property, winY, offsetY) {
  13027. var destination = winY + offsetY;
  13028. set$3(element, property, destination + 'px');
  13029. return Future.pure(offsetY);
  13030. };
  13031. var updateScrollingFixed = function (element, winY, offsetY) {
  13032. var destTop = winY + offsetY;
  13033. var oldProp = getRaw(element, 'top').getOr(offsetY);
  13034. var delta = destTop - parseInt(oldProp, 10);
  13035. var destScroll = element.dom().scrollTop + delta;
  13036. return IosScrolling.moveScrollAndTop(element, destScroll, destTop);
  13037. };
  13038. var updateFixture = function (fixture, winY) {
  13039. return fixture.fold(function (element, property, offsetY) {
  13040. return updateFixed(element, property, winY, offsetY);
  13041. }, function (element, offsetY) {
  13042. return updateScrollingFixed(element, winY, offsetY);
  13043. });
  13044. };
  13045. var updatePositions = function (container, winY) {
  13046. var fixtures = IosViewport.findFixtures(container);
  13047. var updates = map$1(fixtures, function (fixture) {
  13048. return updateFixture(fixture, winY);
  13049. });
  13050. return par$1(updates);
  13051. };
  13052. var IosUpdates = { updatePositions: updatePositions };
  13053. var VIEW_MARGIN = 5;
  13054. var register$2 = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  13055. var scroller = BackgroundActivity(function (y) {
  13056. return IosScrolling.moveWindowScroll(toolstrip, socket, y);
  13057. });
  13058. var scrollBounds = function () {
  13059. var rects = Rectangles.getRectangles(cWin);
  13060. return Option.from(rects[0]).bind(function (rect) {
  13061. var viewTop = rect.top() - socket.dom().scrollTop;
  13062. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  13063. return outside ? Option.some({
  13064. top: constant(viewTop),
  13065. bottom: constant(viewTop + rect.height())
  13066. }) : Option.none();
  13067. });
  13068. };
  13069. var scrollThrottle = last$1(function () {
  13070. scroller.idle(function () {
  13071. IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(function () {
  13072. var extraScroll = scrollBounds();
  13073. extraScroll.each(function (extra) {
  13074. socket.dom().scrollTop = socket.dom().scrollTop + extra.top();
  13075. });
  13076. scroller.start(0);
  13077. structure.refresh();
  13078. });
  13079. });
  13080. }, 1000);
  13081. var onScroll = bind$3(Element.fromDom(outerWindow), 'scroll', function () {
  13082. if (outerWindow.pageYOffset < 0) {
  13083. return;
  13084. }
  13085. scrollThrottle.throttle();
  13086. });
  13087. IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(identity);
  13088. return { unbind: onScroll.unbind };
  13089. };
  13090. var setup$3 = function (bag) {
  13091. var cWin = bag.cWin();
  13092. var ceBody = bag.ceBody();
  13093. var socket = bag.socket();
  13094. var toolstrip = bag.toolstrip();
  13095. var toolbar = bag.toolbar();
  13096. var contentElement = bag.contentElement();
  13097. var keyboardType = bag.keyboardType();
  13098. var outerWindow = bag.outerWindow();
  13099. var dropup = bag.dropup();
  13100. var structure = IosViewport.takeover(socket, ceBody, toolstrip, dropup);
  13101. var keyboardModel = keyboardType(bag.outerBody(), cWin, body(), contentElement, toolstrip, toolbar);
  13102. var toEditing = function () {
  13103. keyboardModel.toEditing();
  13104. clearSelection();
  13105. };
  13106. var toReading = function () {
  13107. keyboardModel.toReading();
  13108. };
  13109. var onToolbarTouch = function (event) {
  13110. keyboardModel.onToolbarTouch(event);
  13111. };
  13112. var onOrientation = Orientation.onChange(outerWindow, {
  13113. onChange: noop,
  13114. onReady: structure.refresh
  13115. });
  13116. onOrientation.onAdjustment(function () {
  13117. structure.refresh();
  13118. });
  13119. var onResize = bind$3(Element.fromDom(outerWindow), 'resize', function () {
  13120. if (structure.isExpanding()) {
  13121. structure.refresh();
  13122. }
  13123. });
  13124. var onScroll = register$2(toolstrip, socket, bag.outerBody(), outerWindow, structure, cWin);
  13125. var unfocusedSelection = FakeSelection(cWin, contentElement);
  13126. var refreshSelection = function () {
  13127. if (unfocusedSelection.isActive()) {
  13128. unfocusedSelection.update();
  13129. }
  13130. };
  13131. var highlightSelection = function () {
  13132. unfocusedSelection.update();
  13133. };
  13134. var clearSelection = function () {
  13135. unfocusedSelection.clear();
  13136. };
  13137. var scrollIntoView = function (top, bottom) {
  13138. Greenzone.scrollIntoView(cWin, socket, dropup, top, bottom);
  13139. };
  13140. var syncHeight = function () {
  13141. set$3(contentElement, 'height', contentElement.dom().contentWindow.document.body.scrollHeight + 'px');
  13142. };
  13143. var setViewportOffset = function (newYOffset) {
  13144. structure.setViewportOffset(newYOffset);
  13145. IosScrolling.moveOnlyTop(socket, newYOffset).get(identity);
  13146. };
  13147. var destroy = function () {
  13148. structure.restore();
  13149. onOrientation.destroy();
  13150. onScroll.unbind();
  13151. onResize.unbind();
  13152. keyboardModel.destroy();
  13153. unfocusedSelection.destroy();
  13154. CaptureBin.input(body(), blur);
  13155. };
  13156. return {
  13157. toEditing: toEditing,
  13158. toReading: toReading,
  13159. onToolbarTouch: onToolbarTouch,
  13160. refreshSelection: refreshSelection,
  13161. clearSelection: clearSelection,
  13162. highlightSelection: highlightSelection,
  13163. scrollIntoView: scrollIntoView,
  13164. updateToolbarPadding: noop,
  13165. setViewportOffset: setViewportOffset,
  13166. syncHeight: syncHeight,
  13167. refreshStructure: structure.refresh,
  13168. destroy: destroy
  13169. };
  13170. };
  13171. var IosSetup = { setup: setup$3 };
  13172. var create$6 = function (platform, mask) {
  13173. var meta = MetaViewport.tag();
  13174. var priorState = value$2();
  13175. var scrollEvents = value$2();
  13176. var iosApi = api$2();
  13177. var iosEvents = api$2();
  13178. var enter = function () {
  13179. mask.hide();
  13180. var doc = Element.fromDom(domGlobals.document);
  13181. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  13182. priorState.set({
  13183. socketHeight: getRaw(platform.socket, 'height'),
  13184. iframeHeight: getRaw(editorApi.frame(), 'height'),
  13185. outerScroll: domGlobals.document.body.scrollTop
  13186. });
  13187. scrollEvents.set({ exclusives: Scrollables.exclusive(doc, '.' + Scrollable.scrollable()) });
  13188. add$2(platform.container, Styles.resolve('fullscreen-maximized'));
  13189. Thor.clobberStyles(platform.container, editorApi.body());
  13190. meta.maximize();
  13191. set$3(platform.socket, 'overflow', 'scroll');
  13192. set$3(platform.socket, '-webkit-overflow-scrolling', 'touch');
  13193. focus$1(editorApi.body());
  13194. var setupBag = MixedBag([
  13195. 'cWin',
  13196. 'ceBody',
  13197. 'socket',
  13198. 'toolstrip',
  13199. 'toolbar',
  13200. 'dropup',
  13201. 'contentElement',
  13202. 'cursor',
  13203. 'keyboardType',
  13204. 'isScrolling',
  13205. 'outerWindow',
  13206. 'outerBody'
  13207. ], []);
  13208. iosApi.set(IosSetup.setup(setupBag({
  13209. cWin: editorApi.win(),
  13210. ceBody: editorApi.body(),
  13211. socket: platform.socket,
  13212. toolstrip: platform.toolstrip,
  13213. toolbar: platform.toolbar,
  13214. dropup: platform.dropup.element(),
  13215. contentElement: editorApi.frame(),
  13216. cursor: noop,
  13217. outerBody: platform.body,
  13218. outerWindow: platform.win,
  13219. keyboardType: IosKeyboard.stubborn,
  13220. isScrolling: function () {
  13221. var scrollValue = scrollEvents;
  13222. return scrollValue.get().exists(function (s) {
  13223. return s.socket.isScrolling();
  13224. });
  13225. }
  13226. })));
  13227. iosApi.run(function (api) {
  13228. api.syncHeight();
  13229. });
  13230. iosEvents.set(IosEvents.initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  13231. });
  13232. };
  13233. var exit = function () {
  13234. meta.restore();
  13235. iosEvents.clear();
  13236. iosApi.clear();
  13237. mask.show();
  13238. priorState.on(function (s) {
  13239. s.socketHeight.each(function (h) {
  13240. set$3(platform.socket, 'height', h);
  13241. });
  13242. s.iframeHeight.each(function (h) {
  13243. set$3(platform.editor.getFrame(), 'height', h);
  13244. });
  13245. domGlobals.document.body.scrollTop = s.scrollTop;
  13246. });
  13247. priorState.clear();
  13248. scrollEvents.on(function (s) {
  13249. s.exclusives.unbind();
  13250. });
  13251. scrollEvents.clear();
  13252. remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
  13253. Thor.restoreStyles();
  13254. Scrollable.deregister(platform.toolbar);
  13255. remove$5(platform.socket, 'overflow');
  13256. remove$5(platform.socket, '-webkit-overflow-scrolling');
  13257. blur(platform.editor.getFrame());
  13258. PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
  13259. editorApi.clearSelection();
  13260. });
  13261. };
  13262. var refreshStructure = function () {
  13263. iosApi.run(function (api) {
  13264. api.refreshStructure();
  13265. });
  13266. };
  13267. return {
  13268. enter: enter,
  13269. refreshStructure: refreshStructure,
  13270. exit: exit
  13271. };
  13272. };
  13273. var IosMode = { create: create$6 };
  13274. var produce$1 = function (raw) {
  13275. var mobile = asRawOrDie('Getting IosWebapp schema', MobileSchema, raw);
  13276. set$3(mobile.toolstrip, 'width', '100%');
  13277. set$3(mobile.container, 'position', 'relative');
  13278. var onView = function () {
  13279. mobile.setReadOnly(mobile.readOnlyOnInit());
  13280. mode.enter();
  13281. };
  13282. var mask = build$1(TapToEditMask.sketch(onView, mobile.translate));
  13283. mobile.alloy.add(mask);
  13284. var maskApi = {
  13285. show: function () {
  13286. mobile.alloy.add(mask);
  13287. },
  13288. hide: function () {
  13289. mobile.alloy.remove(mask);
  13290. }
  13291. };
  13292. var mode = IosMode.create(mobile, maskApi);
  13293. return {
  13294. setReadOnly: mobile.setReadOnly,
  13295. refreshStructure: mode.refreshStructure,
  13296. enter: mode.enter,
  13297. exit: mode.exit,
  13298. destroy: noop
  13299. };
  13300. };
  13301. var IosWebapp = { produce: produce$1 };
  13302. function IosRealm (scrollIntoView) {
  13303. var alloy = OuterContainer({ classes: [Styles.resolve('ios-container')] });
  13304. var toolbar = ScrollingToolbar();
  13305. var webapp = api$2();
  13306. var switchToEdit = CommonRealm.makeEditSwitch(webapp);
  13307. var socket = CommonRealm.makeSocket();
  13308. var dropup = build$2(function () {
  13309. webapp.run(function (w) {
  13310. w.refreshStructure();
  13311. });
  13312. }, scrollIntoView);
  13313. alloy.add(toolbar.wrapper());
  13314. alloy.add(socket);
  13315. alloy.add(dropup.component());
  13316. var setToolbarGroups = function (rawGroups) {
  13317. var groups = toolbar.createGroups(rawGroups);
  13318. toolbar.setGroups(groups);
  13319. };
  13320. var setContextToolbar = function (rawGroups) {
  13321. var groups = toolbar.createGroups(rawGroups);
  13322. toolbar.setContextToolbar(groups);
  13323. };
  13324. var focusToolbar = function () {
  13325. toolbar.focus();
  13326. };
  13327. var restoreToolbar = function () {
  13328. toolbar.restoreToolbar();
  13329. };
  13330. var init = function (spec) {
  13331. webapp.set(IosWebapp.produce(spec));
  13332. };
  13333. var exit = function () {
  13334. webapp.run(function (w) {
  13335. Replacing.remove(socket, switchToEdit);
  13336. w.exit();
  13337. });
  13338. };
  13339. var updateMode = function (readOnly) {
  13340. CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
  13341. };
  13342. return {
  13343. system: constant(alloy),
  13344. element: alloy.element,
  13345. init: init,
  13346. exit: exit,
  13347. setToolbarGroups: setToolbarGroups,
  13348. setContextToolbar: setContextToolbar,
  13349. focusToolbar: focusToolbar,
  13350. restoreToolbar: restoreToolbar,
  13351. updateMode: updateMode,
  13352. socket: constant(socket),
  13353. dropup: constant(dropup)
  13354. };
  13355. }
  13356. var global$5 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  13357. var derive$3 = function (editor) {
  13358. var base = readOptFrom$1(editor.settings, 'skin_url').fold(function () {
  13359. return global$5.baseURL + '/skins/ui/oxide';
  13360. }, function (url) {
  13361. return url;
  13362. });
  13363. return {
  13364. content: base + '/content.mobile.min.css',
  13365. ui: base + '/skin.mobile.min.css'
  13366. };
  13367. };
  13368. var CssUrls = { derive: derive$3 };
  13369. var fontSizes = [
  13370. 'x-small',
  13371. 'small',
  13372. 'medium',
  13373. 'large',
  13374. 'x-large'
  13375. ];
  13376. var fireChange = function (realm, command, state) {
  13377. realm.system().broadcastOn([TinyChannels.formatChanged()], {
  13378. command: command,
  13379. state: state
  13380. });
  13381. };
  13382. var init$5 = function (realm, editor) {
  13383. var allFormats = keys(editor.formatter.get());
  13384. each$1(allFormats, function (command) {
  13385. editor.formatter.formatChanged(command, function (state) {
  13386. fireChange(realm, command, state);
  13387. });
  13388. });
  13389. each$1([
  13390. 'ul',
  13391. 'ol'
  13392. ], function (command) {
  13393. editor.selection.selectorChanged(command, function (state, data) {
  13394. fireChange(realm, command, state);
  13395. });
  13396. });
  13397. };
  13398. var FormatChangers = {
  13399. init: init$5,
  13400. fontSizes: constant(fontSizes)
  13401. };
  13402. var fireSkinLoaded = function (editor) {
  13403. var done = function () {
  13404. editor._skinLoaded = true;
  13405. editor.fire('SkinLoaded');
  13406. };
  13407. return function () {
  13408. if (editor.initialized) {
  13409. done();
  13410. } else {
  13411. editor.on('init', done);
  13412. }
  13413. };
  13414. };
  13415. var SkinLoaded = { fireSkinLoaded: fireSkinLoaded };
  13416. var READING = constant('toReading');
  13417. var EDITING = constant('toEditing');
  13418. var renderMobileTheme = function (editor) {
  13419. var renderUI = function () {
  13420. var targetNode = editor.getElement();
  13421. var cssUrls = CssUrls.derive(editor);
  13422. if (isSkinDisabled(editor) === false) {
  13423. editor.contentCSS.push(cssUrls.content);
  13424. global$1.DOM.styleSheetLoader.load(cssUrls.ui, SkinLoaded.fireSkinLoaded(editor));
  13425. } else {
  13426. SkinLoaded.fireSkinLoaded(editor)();
  13427. }
  13428. var doScrollIntoView = function () {
  13429. editor.fire('ScrollIntoView');
  13430. };
  13431. var realm = detect$3().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  13432. var original = Element.fromDom(targetNode);
  13433. attachSystemAfter(original, realm.system());
  13434. var findFocusIn = function (elem) {
  13435. return search(elem).bind(function (focused) {
  13436. return realm.system().getByDom(focused).toOption();
  13437. });
  13438. };
  13439. var outerWindow = targetNode.ownerDocument.defaultView;
  13440. var orientation = Orientation.onChange(outerWindow, {
  13441. onChange: function () {
  13442. var alloy = realm.system();
  13443. alloy.broadcastOn([TinyChannels.orientationChanged()], { width: Orientation.getActualWidth(outerWindow) });
  13444. },
  13445. onReady: noop
  13446. });
  13447. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  13448. if (ro === false) {
  13449. editor.selection.collapse();
  13450. }
  13451. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  13452. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  13453. editor.setMode(ro === true ? 'readonly' : 'design');
  13454. editor.fire(ro === true ? READING() : EDITING());
  13455. realm.updateMode(ro);
  13456. };
  13457. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  13458. var dynamic = dynamicGroup.get();
  13459. var toolbars = {
  13460. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  13461. main: dynamic.backToMask.concat(mainGroups.get())
  13462. };
  13463. return toolbars;
  13464. };
  13465. var bindHandler = function (label, handler) {
  13466. editor.on(label, handler);
  13467. return {
  13468. unbind: function () {
  13469. editor.off(label);
  13470. }
  13471. };
  13472. };
  13473. editor.on('init', function () {
  13474. realm.init({
  13475. editor: {
  13476. getFrame: function () {
  13477. return Element.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  13478. },
  13479. onDomChanged: function () {
  13480. return { unbind: noop };
  13481. },
  13482. onToReading: function (handler) {
  13483. return bindHandler(READING(), handler);
  13484. },
  13485. onToEditing: function (handler) {
  13486. return bindHandler(EDITING(), handler);
  13487. },
  13488. onScrollToCursor: function (handler) {
  13489. editor.on('ScrollIntoView', function (tinyEvent) {
  13490. handler(tinyEvent);
  13491. });
  13492. var unbind = function () {
  13493. editor.off('ScrollIntoView');
  13494. orientation.destroy();
  13495. };
  13496. return { unbind: unbind };
  13497. },
  13498. onTouchToolstrip: function () {
  13499. hideDropup();
  13500. },
  13501. onTouchContent: function () {
  13502. var toolbar = Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar')));
  13503. findFocusIn(toolbar).each(emitExecute);
  13504. realm.restoreToolbar();
  13505. hideDropup();
  13506. },
  13507. onTapContent: function (evt) {
  13508. var target = evt.target();
  13509. if (name(target) === 'img') {
  13510. editor.selection.select(target.dom());
  13511. evt.kill();
  13512. } else if (name(target) === 'a') {
  13513. var component = realm.system().getByDom(Element.fromDom(editor.editorContainer));
  13514. component.each(function (container) {
  13515. if (Swapping.isAlpha(container)) {
  13516. TinyCodeDupe.openLink(target.dom());
  13517. }
  13518. });
  13519. }
  13520. }
  13521. },
  13522. container: Element.fromDom(editor.editorContainer),
  13523. socket: Element.fromDom(editor.contentAreaContainer),
  13524. toolstrip: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolstrip'))),
  13525. toolbar: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar'))),
  13526. dropup: realm.dropup(),
  13527. alloy: realm.system(),
  13528. translate: noop,
  13529. setReadOnly: function (ro) {
  13530. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  13531. },
  13532. readOnlyOnInit: function () {
  13533. return readOnlyOnInit();
  13534. }
  13535. });
  13536. var hideDropup = function () {
  13537. realm.dropup().disappear(function () {
  13538. realm.system().broadcastOn([TinyChannels.dropupDismissed()], {});
  13539. });
  13540. };
  13541. var backToMaskGroup = {
  13542. label: 'The first group',
  13543. scrollable: false,
  13544. items: [Buttons.forToolbar('back', function () {
  13545. editor.selection.collapse();
  13546. realm.exit();
  13547. }, {}, editor)]
  13548. };
  13549. var backToReadOnlyGroup = {
  13550. label: 'Back to read only',
  13551. scrollable: false,
  13552. items: [Buttons.forToolbar('readonly-back', function () {
  13553. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  13554. }, {}, editor)]
  13555. };
  13556. var readOnlyGroup = {
  13557. label: 'The read only mode group',
  13558. scrollable: true,
  13559. items: []
  13560. };
  13561. var features = Features.setup(realm, editor);
  13562. var items = Features.detect(editor.settings, features);
  13563. var actionGroup = {
  13564. label: 'the action group',
  13565. scrollable: true,
  13566. items: items
  13567. };
  13568. var extraGroup = {
  13569. label: 'The extra group',
  13570. scrollable: false,
  13571. items: []
  13572. };
  13573. var mainGroups = Cell([
  13574. actionGroup,
  13575. extraGroup
  13576. ]);
  13577. var readOnlyGroups = Cell([
  13578. readOnlyGroup,
  13579. extraGroup
  13580. ]);
  13581. var dynamicGroup = Cell({
  13582. backToMask: [backToMaskGroup],
  13583. backToReadOnly: [backToReadOnlyGroup]
  13584. });
  13585. FormatChangers.init(realm, editor);
  13586. });
  13587. editor.on('remove', function () {
  13588. realm.exit();
  13589. });
  13590. editor.on('detach', function () {
  13591. detachSystem(realm.system());
  13592. realm.system().destroy();
  13593. });
  13594. return {
  13595. iframeContainer: realm.socket().element().dom(),
  13596. editorContainer: realm.element().dom()
  13597. };
  13598. };
  13599. return {
  13600. getNotificationManagerImpl: function () {
  13601. return {
  13602. open: constant({
  13603. progressBar: { value: noop },
  13604. close: noop,
  13605. text: noop,
  13606. getEl: constant(null),
  13607. moveTo: noop,
  13608. moveRel: noop,
  13609. settings: {}
  13610. }),
  13611. close: noop,
  13612. reposition: noop,
  13613. getArgs: constant({})
  13614. };
  13615. },
  13616. renderUI: renderUI
  13617. };
  13618. };
  13619. function Theme () {
  13620. global$2.add('mobile', renderMobileTheme);
  13621. }
  13622. Theme();
  13623. }(window));