theme.js 428 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130
  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.10.2 (2021-11-17)
  8. */
  9. (function () {
  10. 'use strict';
  11. var __assign = function () {
  12. __assign = Object.assign || function __assign(t) {
  13. for (var s, i = 1, n = arguments.length; i < n; i++) {
  14. s = arguments[i];
  15. for (var p in s)
  16. if (Object.prototype.hasOwnProperty.call(s, p))
  17. t[p] = s[p];
  18. }
  19. return t;
  20. };
  21. return __assign.apply(this, arguments);
  22. };
  23. function __rest(s, e) {
  24. var t = {};
  25. for (var p in s)
  26. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  27. t[p] = s[p];
  28. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  29. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  30. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  31. t[p[i]] = s[p[i]];
  32. }
  33. return t;
  34. }
  35. function __spreadArray(to, from, pack) {
  36. if (pack || arguments.length === 2)
  37. for (var i = 0, l = from.length, ar; i < l; i++) {
  38. if (ar || !(i in from)) {
  39. if (!ar)
  40. ar = Array.prototype.slice.call(from, 0, i);
  41. ar[i] = from[i];
  42. }
  43. }
  44. return to.concat(ar || Array.prototype.slice.call(from));
  45. }
  46. var typeOf = function (x) {
  47. var t = typeof x;
  48. if (x === null) {
  49. return 'null';
  50. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  51. return 'array';
  52. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  53. return 'string';
  54. } else {
  55. return t;
  56. }
  57. };
  58. var isType$1 = function (type) {
  59. return function (value) {
  60. return typeOf(value) === type;
  61. };
  62. };
  63. var isSimpleType = function (type) {
  64. return function (value) {
  65. return typeof value === type;
  66. };
  67. };
  68. var eq$1 = function (t) {
  69. return function (a) {
  70. return t === a;
  71. };
  72. };
  73. var isString = isType$1('string');
  74. var isObject = isType$1('object');
  75. var isArray = isType$1('array');
  76. var isNull = eq$1(null);
  77. var isBoolean = isSimpleType('boolean');
  78. var isUndefined = eq$1(undefined);
  79. var isNullable = function (a) {
  80. return a === null || a === undefined;
  81. };
  82. var isNonNullable = function (a) {
  83. return !isNullable(a);
  84. };
  85. var isFunction = isSimpleType('function');
  86. var isNumber = isSimpleType('number');
  87. var noop = function () {
  88. };
  89. var compose = function (fa, fb) {
  90. return function () {
  91. var args = [];
  92. for (var _i = 0; _i < arguments.length; _i++) {
  93. args[_i] = arguments[_i];
  94. }
  95. return fa(fb.apply(null, args));
  96. };
  97. };
  98. var compose1 = function (fbc, fab) {
  99. return function (a) {
  100. return fbc(fab(a));
  101. };
  102. };
  103. var constant$1 = function (value) {
  104. return function () {
  105. return value;
  106. };
  107. };
  108. var identity = function (x) {
  109. return x;
  110. };
  111. var tripleEquals = function (a, b) {
  112. return a === b;
  113. };
  114. function curry(fn) {
  115. var initialArgs = [];
  116. for (var _i = 1; _i < arguments.length; _i++) {
  117. initialArgs[_i - 1] = arguments[_i];
  118. }
  119. return function () {
  120. var restArgs = [];
  121. for (var _i = 0; _i < arguments.length; _i++) {
  122. restArgs[_i] = arguments[_i];
  123. }
  124. var all = initialArgs.concat(restArgs);
  125. return fn.apply(null, all);
  126. };
  127. }
  128. var not = function (f) {
  129. return function (t) {
  130. return !f(t);
  131. };
  132. };
  133. var die = function (msg) {
  134. return function () {
  135. throw new Error(msg);
  136. };
  137. };
  138. var apply$1 = function (f) {
  139. return f();
  140. };
  141. var never = constant$1(false);
  142. var always = constant$1(true);
  143. var none = function () {
  144. return NONE;
  145. };
  146. var NONE = function () {
  147. var call = function (thunk) {
  148. return thunk();
  149. };
  150. var id = identity;
  151. var me = {
  152. fold: function (n, _s) {
  153. return n();
  154. },
  155. isSome: never,
  156. isNone: always,
  157. getOr: id,
  158. getOrThunk: call,
  159. getOrDie: function (msg) {
  160. throw new Error(msg || 'error: getOrDie called on none.');
  161. },
  162. getOrNull: constant$1(null),
  163. getOrUndefined: constant$1(undefined),
  164. or: id,
  165. orThunk: call,
  166. map: none,
  167. each: noop,
  168. bind: none,
  169. exists: never,
  170. forall: always,
  171. filter: function () {
  172. return none();
  173. },
  174. toArray: function () {
  175. return [];
  176. },
  177. toString: constant$1('none()')
  178. };
  179. return me;
  180. }();
  181. var some = function (a) {
  182. var constant_a = constant$1(a);
  183. var self = function () {
  184. return me;
  185. };
  186. var bind = function (f) {
  187. return f(a);
  188. };
  189. var me = {
  190. fold: function (n, s) {
  191. return s(a);
  192. },
  193. isSome: always,
  194. isNone: never,
  195. getOr: constant_a,
  196. getOrThunk: constant_a,
  197. getOrDie: constant_a,
  198. getOrNull: constant_a,
  199. getOrUndefined: constant_a,
  200. or: self,
  201. orThunk: self,
  202. map: function (f) {
  203. return some(f(a));
  204. },
  205. each: function (f) {
  206. f(a);
  207. },
  208. bind: bind,
  209. exists: bind,
  210. forall: bind,
  211. filter: function (f) {
  212. return f(a) ? me : NONE;
  213. },
  214. toArray: function () {
  215. return [a];
  216. },
  217. toString: function () {
  218. return 'some(' + a + ')';
  219. }
  220. };
  221. return me;
  222. };
  223. var from = function (value) {
  224. return value === null || value === undefined ? NONE : some(value);
  225. };
  226. var Optional = {
  227. some: some,
  228. none: none,
  229. from: from
  230. };
  231. var cached = function (f) {
  232. var called = false;
  233. var r;
  234. return function () {
  235. var args = [];
  236. for (var _i = 0; _i < arguments.length; _i++) {
  237. args[_i] = arguments[_i];
  238. }
  239. if (!called) {
  240. called = true;
  241. r = f.apply(null, args);
  242. }
  243. return r;
  244. };
  245. };
  246. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  247. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  248. var isiPhone = os.isiOS() && !isiPad;
  249. var isMobile = os.isiOS() || os.isAndroid();
  250. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  251. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  252. var isPhone = isiPhone || isMobile && !isTablet;
  253. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  254. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  255. return {
  256. isiPad: constant$1(isiPad),
  257. isiPhone: constant$1(isiPhone),
  258. isTablet: constant$1(isTablet),
  259. isPhone: constant$1(isPhone),
  260. isTouch: constant$1(isTouch),
  261. isAndroid: os.isAndroid,
  262. isiOS: os.isiOS,
  263. isWebView: constant$1(iOSwebview),
  264. isDesktop: constant$1(isDesktop)
  265. };
  266. };
  267. var nativeSlice = Array.prototype.slice;
  268. var nativeIndexOf = Array.prototype.indexOf;
  269. var nativePush = Array.prototype.push;
  270. var rawIndexOf = function (ts, t) {
  271. return nativeIndexOf.call(ts, t);
  272. };
  273. var contains$1 = function (xs, x) {
  274. return rawIndexOf(xs, x) > -1;
  275. };
  276. var exists = function (xs, pred) {
  277. for (var i = 0, len = xs.length; i < len; i++) {
  278. var x = xs[i];
  279. if (pred(x, i)) {
  280. return true;
  281. }
  282. }
  283. return false;
  284. };
  285. var map$2 = function (xs, f) {
  286. var len = xs.length;
  287. var r = new Array(len);
  288. for (var i = 0; i < len; i++) {
  289. var x = xs[i];
  290. r[i] = f(x, i);
  291. }
  292. return r;
  293. };
  294. var each$1 = function (xs, f) {
  295. for (var i = 0, len = xs.length; i < len; i++) {
  296. var x = xs[i];
  297. f(x, i);
  298. }
  299. };
  300. var eachr = function (xs, f) {
  301. for (var i = xs.length - 1; i >= 0; i--) {
  302. var x = xs[i];
  303. f(x, i);
  304. }
  305. };
  306. var filter$2 = function (xs, pred) {
  307. var r = [];
  308. for (var i = 0, len = xs.length; i < len; i++) {
  309. var x = xs[i];
  310. if (pred(x, i)) {
  311. r.push(x);
  312. }
  313. }
  314. return r;
  315. };
  316. var foldr = function (xs, f, acc) {
  317. eachr(xs, function (x, i) {
  318. acc = f(acc, x, i);
  319. });
  320. return acc;
  321. };
  322. var foldl = function (xs, f, acc) {
  323. each$1(xs, function (x, i) {
  324. acc = f(acc, x, i);
  325. });
  326. return acc;
  327. };
  328. var findUntil = function (xs, pred, until) {
  329. for (var i = 0, len = xs.length; i < len; i++) {
  330. var x = xs[i];
  331. if (pred(x, i)) {
  332. return Optional.some(x);
  333. } else if (until(x, i)) {
  334. break;
  335. }
  336. }
  337. return Optional.none();
  338. };
  339. var find$2 = function (xs, pred) {
  340. return findUntil(xs, pred, never);
  341. };
  342. var findIndex$1 = function (xs, pred) {
  343. for (var i = 0, len = xs.length; i < len; i++) {
  344. var x = xs[i];
  345. if (pred(x, i)) {
  346. return Optional.some(i);
  347. }
  348. }
  349. return Optional.none();
  350. };
  351. var flatten = function (xs) {
  352. var r = [];
  353. for (var i = 0, len = xs.length; i < len; ++i) {
  354. if (!isArray(xs[i])) {
  355. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  356. }
  357. nativePush.apply(r, xs[i]);
  358. }
  359. return r;
  360. };
  361. var bind$3 = function (xs, f) {
  362. return flatten(map$2(xs, f));
  363. };
  364. var forall = function (xs, pred) {
  365. for (var i = 0, len = xs.length; i < len; ++i) {
  366. var x = xs[i];
  367. if (pred(x, i) !== true) {
  368. return false;
  369. }
  370. }
  371. return true;
  372. };
  373. var reverse = function (xs) {
  374. var r = nativeSlice.call(xs, 0);
  375. r.reverse();
  376. return r;
  377. };
  378. var difference = function (a1, a2) {
  379. return filter$2(a1, function (x) {
  380. return !contains$1(a2, x);
  381. });
  382. };
  383. var pure$2 = function (x) {
  384. return [x];
  385. };
  386. var sort = function (xs, comparator) {
  387. var copy = nativeSlice.call(xs, 0);
  388. copy.sort(comparator);
  389. return copy;
  390. };
  391. var get$d = function (xs, i) {
  392. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  393. };
  394. var head = function (xs) {
  395. return get$d(xs, 0);
  396. };
  397. var findMap = function (arr, f) {
  398. for (var i = 0; i < arr.length; i++) {
  399. var r = f(arr[i], i);
  400. if (r.isSome()) {
  401. return r;
  402. }
  403. }
  404. return Optional.none();
  405. };
  406. var firstMatch = function (regexes, s) {
  407. for (var i = 0; i < regexes.length; i++) {
  408. var x = regexes[i];
  409. if (x.test(s)) {
  410. return x;
  411. }
  412. }
  413. return undefined;
  414. };
  415. var find$1 = function (regexes, agent) {
  416. var r = firstMatch(regexes, agent);
  417. if (!r) {
  418. return {
  419. major: 0,
  420. minor: 0
  421. };
  422. }
  423. var group = function (i) {
  424. return Number(agent.replace(r, '$' + i));
  425. };
  426. return nu$8(group(1), group(2));
  427. };
  428. var detect$4 = function (versionRegexes, agent) {
  429. var cleanedAgent = String(agent).toLowerCase();
  430. if (versionRegexes.length === 0) {
  431. return unknown$3();
  432. }
  433. return find$1(versionRegexes, cleanedAgent);
  434. };
  435. var unknown$3 = function () {
  436. return nu$8(0, 0);
  437. };
  438. var nu$8 = function (major, minor) {
  439. return {
  440. major: major,
  441. minor: minor
  442. };
  443. };
  444. var Version = {
  445. nu: nu$8,
  446. detect: detect$4,
  447. unknown: unknown$3
  448. };
  449. var detectBrowser$1 = function (browsers, userAgentData) {
  450. return findMap(userAgentData.brands, function (uaBrand) {
  451. var lcBrand = uaBrand.brand.toLowerCase();
  452. return find$2(browsers, function (browser) {
  453. var _a;
  454. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  455. }).map(function (info) {
  456. return {
  457. current: info.name,
  458. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  459. };
  460. });
  461. });
  462. };
  463. var detect$3 = function (candidates, userAgent) {
  464. var agent = String(userAgent).toLowerCase();
  465. return find$2(candidates, function (candidate) {
  466. return candidate.search(agent);
  467. });
  468. };
  469. var detectBrowser = function (browsers, userAgent) {
  470. return detect$3(browsers, userAgent).map(function (browser) {
  471. var version = Version.detect(browser.versionRegexes, userAgent);
  472. return {
  473. current: browser.name,
  474. version: version
  475. };
  476. });
  477. };
  478. var detectOs = function (oses, userAgent) {
  479. return detect$3(oses, userAgent).map(function (os) {
  480. var version = Version.detect(os.versionRegexes, userAgent);
  481. return {
  482. current: os.name,
  483. version: version
  484. };
  485. });
  486. };
  487. var checkRange = function (str, substr, start) {
  488. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  489. };
  490. var supplant = function (str, obj) {
  491. var isStringOrNumber = function (a) {
  492. var t = typeof a;
  493. return t === 'string' || t === 'number';
  494. };
  495. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  496. var value = obj[key];
  497. return isStringOrNumber(value) ? value.toString() : fullMatch;
  498. });
  499. };
  500. var contains = function (str, substr) {
  501. return str.indexOf(substr) !== -1;
  502. };
  503. var endsWith = function (str, suffix) {
  504. return checkRange(str, suffix, str.length - suffix.length);
  505. };
  506. var blank = function (r) {
  507. return function (s) {
  508. return s.replace(r, '');
  509. };
  510. };
  511. var trim = blank(/^\s+|\s+$/g);
  512. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  513. var checkContains = function (target) {
  514. return function (uastring) {
  515. return contains(uastring, target);
  516. };
  517. };
  518. var browsers = [
  519. {
  520. name: 'Edge',
  521. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  522. search: function (uastring) {
  523. return contains(uastring, 'edge/') && contains(uastring, 'chrome') && contains(uastring, 'safari') && contains(uastring, 'applewebkit');
  524. }
  525. },
  526. {
  527. name: 'Chrome',
  528. brand: 'Chromium',
  529. versionRegexes: [
  530. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  531. normalVersionRegex
  532. ],
  533. search: function (uastring) {
  534. return contains(uastring, 'chrome') && !contains(uastring, 'chromeframe');
  535. }
  536. },
  537. {
  538. name: 'IE',
  539. versionRegexes: [
  540. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  541. /.*?rv:([0-9]+)\.([0-9]+).*/
  542. ],
  543. search: function (uastring) {
  544. return contains(uastring, 'msie') || contains(uastring, 'trident');
  545. }
  546. },
  547. {
  548. name: 'Opera',
  549. versionRegexes: [
  550. normalVersionRegex,
  551. /.*?opera\/([0-9]+)\.([0-9]+).*/
  552. ],
  553. search: checkContains('opera')
  554. },
  555. {
  556. name: 'Firefox',
  557. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  558. search: checkContains('firefox')
  559. },
  560. {
  561. name: 'Safari',
  562. versionRegexes: [
  563. normalVersionRegex,
  564. /.*?cpu os ([0-9]+)_([0-9]+).*/
  565. ],
  566. search: function (uastring) {
  567. return (contains(uastring, 'safari') || contains(uastring, 'mobile/')) && contains(uastring, 'applewebkit');
  568. }
  569. }
  570. ];
  571. var oses = [
  572. {
  573. name: 'Windows',
  574. search: checkContains('win'),
  575. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  576. },
  577. {
  578. name: 'iOS',
  579. search: function (uastring) {
  580. return contains(uastring, 'iphone') || contains(uastring, 'ipad');
  581. },
  582. versionRegexes: [
  583. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  584. /.*cpu os ([0-9]+)_([0-9]+).*/,
  585. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  586. ]
  587. },
  588. {
  589. name: 'Android',
  590. search: checkContains('android'),
  591. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  592. },
  593. {
  594. name: 'OSX',
  595. search: checkContains('mac os x'),
  596. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  597. },
  598. {
  599. name: 'Linux',
  600. search: checkContains('linux'),
  601. versionRegexes: []
  602. },
  603. {
  604. name: 'Solaris',
  605. search: checkContains('sunos'),
  606. versionRegexes: []
  607. },
  608. {
  609. name: 'FreeBSD',
  610. search: checkContains('freebsd'),
  611. versionRegexes: []
  612. },
  613. {
  614. name: 'ChromeOS',
  615. search: checkContains('cros'),
  616. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  617. }
  618. ];
  619. var PlatformInfo = {
  620. browsers: constant$1(browsers),
  621. oses: constant$1(oses)
  622. };
  623. var edge = 'Edge';
  624. var chrome = 'Chrome';
  625. var ie = 'IE';
  626. var opera = 'Opera';
  627. var firefox = 'Firefox';
  628. var safari = 'Safari';
  629. var unknown$2 = function () {
  630. return nu$7({
  631. current: undefined,
  632. version: Version.unknown()
  633. });
  634. };
  635. var nu$7 = function (info) {
  636. var current = info.current;
  637. var version = info.version;
  638. var isBrowser = function (name) {
  639. return function () {
  640. return current === name;
  641. };
  642. };
  643. return {
  644. current: current,
  645. version: version,
  646. isEdge: isBrowser(edge),
  647. isChrome: isBrowser(chrome),
  648. isIE: isBrowser(ie),
  649. isOpera: isBrowser(opera),
  650. isFirefox: isBrowser(firefox),
  651. isSafari: isBrowser(safari)
  652. };
  653. };
  654. var Browser = {
  655. unknown: unknown$2,
  656. nu: nu$7,
  657. edge: constant$1(edge),
  658. chrome: constant$1(chrome),
  659. ie: constant$1(ie),
  660. opera: constant$1(opera),
  661. firefox: constant$1(firefox),
  662. safari: constant$1(safari)
  663. };
  664. var windows = 'Windows';
  665. var ios = 'iOS';
  666. var android = 'Android';
  667. var linux = 'Linux';
  668. var osx = 'OSX';
  669. var solaris = 'Solaris';
  670. var freebsd = 'FreeBSD';
  671. var chromeos = 'ChromeOS';
  672. var unknown$1 = function () {
  673. return nu$6({
  674. current: undefined,
  675. version: Version.unknown()
  676. });
  677. };
  678. var nu$6 = function (info) {
  679. var current = info.current;
  680. var version = info.version;
  681. var isOS = function (name) {
  682. return function () {
  683. return current === name;
  684. };
  685. };
  686. return {
  687. current: current,
  688. version: version,
  689. isWindows: isOS(windows),
  690. isiOS: isOS(ios),
  691. isAndroid: isOS(android),
  692. isOSX: isOS(osx),
  693. isLinux: isOS(linux),
  694. isSolaris: isOS(solaris),
  695. isFreeBSD: isOS(freebsd),
  696. isChromeOS: isOS(chromeos)
  697. };
  698. };
  699. var OperatingSystem = {
  700. unknown: unknown$1,
  701. nu: nu$6,
  702. windows: constant$1(windows),
  703. ios: constant$1(ios),
  704. android: constant$1(android),
  705. linux: constant$1(linux),
  706. osx: constant$1(osx),
  707. solaris: constant$1(solaris),
  708. freebsd: constant$1(freebsd),
  709. chromeos: constant$1(chromeos)
  710. };
  711. var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) {
  712. var browsers = PlatformInfo.browsers();
  713. var oses = PlatformInfo.oses();
  714. var browser = userAgentDataOpt.bind(function (userAgentData) {
  715. return detectBrowser$1(browsers, userAgentData);
  716. }).orThunk(function () {
  717. return detectBrowser(browsers, userAgent);
  718. }).fold(Browser.unknown, Browser.nu);
  719. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  720. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  721. return {
  722. browser: browser,
  723. os: os,
  724. deviceType: deviceType
  725. };
  726. };
  727. var PlatformDetection = { detect: detect$2 };
  728. var mediaMatch = function (query) {
  729. return window.matchMedia(query).matches;
  730. };
  731. var platform$1 = cached(function () {
  732. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  733. });
  734. var detect$1 = function () {
  735. return platform$1();
  736. };
  737. var constant = constant$1;
  738. var touchstart = constant('touchstart');
  739. var touchmove = constant('touchmove');
  740. var touchend = constant('touchend');
  741. var mousedown = constant('mousedown');
  742. var mousemove = constant('mousemove');
  743. var mouseup = constant('mouseup');
  744. var mouseover = constant('mouseover');
  745. var keydown = constant('keydown');
  746. var keyup = constant('keyup');
  747. var input$1 = constant('input');
  748. var change = constant('change');
  749. var click = constant('click');
  750. var transitionend = constant('transitionend');
  751. var selectstart = constant('selectstart');
  752. var prefixName = function (name) {
  753. return constant$1('alloy.' + name);
  754. };
  755. var alloy = { tap: prefixName('tap') };
  756. var focus$4 = prefixName('focus');
  757. var postBlur = prefixName('blur.post');
  758. var postPaste = prefixName('paste.post');
  759. var receive$1 = prefixName('receive');
  760. var execute$5 = prefixName('execute');
  761. var focusItem = prefixName('focus.item');
  762. var tap = alloy.tap;
  763. var longpress = prefixName('longpress');
  764. var systemInit = prefixName('system.init');
  765. var attachedToDom = prefixName('system.attached');
  766. var detachedFromDom = prefixName('system.detached');
  767. var focusShifted = prefixName('focusmanager.shifted');
  768. var highlight$1 = prefixName('highlight');
  769. var dehighlight$1 = prefixName('dehighlight');
  770. var emit = function (component, event) {
  771. dispatchWith(component, component.element, event, {});
  772. };
  773. var emitWith = function (component, event, properties) {
  774. dispatchWith(component, component.element, event, properties);
  775. };
  776. var emitExecute = function (component) {
  777. emit(component, execute$5());
  778. };
  779. var dispatch = function (component, target, event) {
  780. dispatchWith(component, target, event, {});
  781. };
  782. var dispatchWith = function (component, target, event, properties) {
  783. var data = __assign({ target: target }, properties);
  784. component.getSystem().triggerEvent(event, target, data);
  785. };
  786. var dispatchEvent = function (component, target, event, simulatedEvent) {
  787. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  788. };
  789. var dispatchFocus = function (component, target) {
  790. component.getSystem().triggerFocus(target, component.element);
  791. };
  792. var DOCUMENT = 9;
  793. var DOCUMENT_FRAGMENT = 11;
  794. var ELEMENT = 1;
  795. var TEXT = 3;
  796. var fromHtml$2 = function (html, scope) {
  797. var doc = scope || document;
  798. var div = doc.createElement('div');
  799. div.innerHTML = html;
  800. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  801. console.error('HTML does not have a single root node', html);
  802. throw new Error('HTML must have a single root node');
  803. }
  804. return fromDom(div.childNodes[0]);
  805. };
  806. var fromTag = function (tag, scope) {
  807. var doc = scope || document;
  808. var node = doc.createElement(tag);
  809. return fromDom(node);
  810. };
  811. var fromText = function (text, scope) {
  812. var doc = scope || document;
  813. var node = doc.createTextNode(text);
  814. return fromDom(node);
  815. };
  816. var fromDom = function (node) {
  817. if (node === null || node === undefined) {
  818. throw new Error('Node cannot be null or undefined');
  819. }
  820. return { dom: node };
  821. };
  822. var fromPoint = function (docElm, x, y) {
  823. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  824. };
  825. var SugarElement = {
  826. fromHtml: fromHtml$2,
  827. fromTag: fromTag,
  828. fromText: fromText,
  829. fromDom: fromDom,
  830. fromPoint: fromPoint
  831. };
  832. var is$1 = function (element, selector) {
  833. var dom = element.dom;
  834. if (dom.nodeType !== ELEMENT) {
  835. return false;
  836. } else {
  837. var elem = dom;
  838. if (elem.matches !== undefined) {
  839. return elem.matches(selector);
  840. } else if (elem.msMatchesSelector !== undefined) {
  841. return elem.msMatchesSelector(selector);
  842. } else if (elem.webkitMatchesSelector !== undefined) {
  843. return elem.webkitMatchesSelector(selector);
  844. } else if (elem.mozMatchesSelector !== undefined) {
  845. return elem.mozMatchesSelector(selector);
  846. } else {
  847. throw new Error('Browser lacks native selectors');
  848. }
  849. }
  850. };
  851. var bypassSelector = function (dom) {
  852. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  853. };
  854. var all$2 = function (selector, scope) {
  855. var base = scope === undefined ? document : scope.dom;
  856. return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  857. };
  858. var one = function (selector, scope) {
  859. var base = scope === undefined ? document : scope.dom;
  860. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  861. };
  862. var eq = function (e1, e2) {
  863. return e1.dom === e2.dom;
  864. };
  865. typeof window !== 'undefined' ? window : Function('return this;')();
  866. var name$1 = function (element) {
  867. var r = element.dom.nodeName;
  868. return r.toLowerCase();
  869. };
  870. var type = function (element) {
  871. return element.dom.nodeType;
  872. };
  873. var isType = function (t) {
  874. return function (element) {
  875. return type(element) === t;
  876. };
  877. };
  878. var isElement = isType(ELEMENT);
  879. var isText = isType(TEXT);
  880. var isDocument = isType(DOCUMENT);
  881. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  882. var owner$2 = function (element) {
  883. return SugarElement.fromDom(element.dom.ownerDocument);
  884. };
  885. var documentOrOwner = function (dos) {
  886. return isDocument(dos) ? dos : owner$2(dos);
  887. };
  888. var defaultView = function (element) {
  889. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  890. };
  891. var parent = function (element) {
  892. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  893. };
  894. var parents = function (element, isRoot) {
  895. var stop = isFunction(isRoot) ? isRoot : never;
  896. var dom = element.dom;
  897. var ret = [];
  898. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  899. var rawParent = dom.parentNode;
  900. var p = SugarElement.fromDom(rawParent);
  901. ret.push(p);
  902. if (stop(p) === true) {
  903. break;
  904. } else {
  905. dom = rawParent;
  906. }
  907. }
  908. return ret;
  909. };
  910. var siblings$2 = function (element) {
  911. var filterSelf = function (elements) {
  912. return filter$2(elements, function (x) {
  913. return !eq(element, x);
  914. });
  915. };
  916. return parent(element).map(children).map(filterSelf).getOr([]);
  917. };
  918. var nextSibling = function (element) {
  919. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  920. };
  921. var children = function (element) {
  922. return map$2(element.dom.childNodes, SugarElement.fromDom);
  923. };
  924. var child = function (element, index) {
  925. var cs = element.dom.childNodes;
  926. return Optional.from(cs[index]).map(SugarElement.fromDom);
  927. };
  928. var firstChild = function (element) {
  929. return child(element, 0);
  930. };
  931. var before$1 = function (marker, element) {
  932. var parent$1 = parent(marker);
  933. parent$1.each(function (v) {
  934. v.dom.insertBefore(element.dom, marker.dom);
  935. });
  936. };
  937. var after$2 = function (marker, element) {
  938. var sibling = nextSibling(marker);
  939. sibling.fold(function () {
  940. var parent$1 = parent(marker);
  941. parent$1.each(function (v) {
  942. append$2(v, element);
  943. });
  944. }, function (v) {
  945. before$1(v, element);
  946. });
  947. };
  948. var prepend$1 = function (parent, element) {
  949. var firstChild$1 = firstChild(parent);
  950. firstChild$1.fold(function () {
  951. append$2(parent, element);
  952. }, function (v) {
  953. parent.dom.insertBefore(element.dom, v.dom);
  954. });
  955. };
  956. var append$2 = function (parent, element) {
  957. parent.dom.appendChild(element.dom);
  958. };
  959. var appendAt = function (parent, element, index) {
  960. child(parent, index).fold(function () {
  961. append$2(parent, element);
  962. }, function (v) {
  963. before$1(v, element);
  964. });
  965. };
  966. var append$1 = function (parent, elements) {
  967. each$1(elements, function (x) {
  968. append$2(parent, x);
  969. });
  970. };
  971. var empty = function (element) {
  972. element.dom.textContent = '';
  973. each$1(children(element), function (rogue) {
  974. remove$7(rogue);
  975. });
  976. };
  977. var remove$7 = function (element) {
  978. var dom = element.dom;
  979. if (dom.parentNode !== null) {
  980. dom.parentNode.removeChild(dom);
  981. }
  982. };
  983. var isShadowRoot = function (dos) {
  984. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  985. };
  986. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  987. var isSupported$1 = constant$1(supported);
  988. var getRootNode = supported ? function (e) {
  989. return SugarElement.fromDom(e.dom.getRootNode());
  990. } : documentOrOwner;
  991. var getShadowRoot = function (e) {
  992. var r = getRootNode(e);
  993. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  994. };
  995. var getShadowHost = function (e) {
  996. return SugarElement.fromDom(e.dom.host);
  997. };
  998. var getOriginalEventTarget = function (event) {
  999. if (isSupported$1() && isNonNullable(event.target)) {
  1000. var el = SugarElement.fromDom(event.target);
  1001. if (isElement(el) && isOpenShadowHost(el)) {
  1002. if (event.composed && event.composedPath) {
  1003. var composedPath = event.composedPath();
  1004. if (composedPath) {
  1005. return head(composedPath);
  1006. }
  1007. }
  1008. }
  1009. }
  1010. return Optional.from(event.target);
  1011. };
  1012. var isOpenShadowHost = function (element) {
  1013. return isNonNullable(element.dom.shadowRoot);
  1014. };
  1015. var inBody = function (element) {
  1016. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1017. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1018. return false;
  1019. }
  1020. var doc = dom.ownerDocument;
  1021. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1022. return doc.body.contains(dom);
  1023. }, compose1(inBody, getShadowHost));
  1024. };
  1025. var body = function () {
  1026. return getBody(SugarElement.fromDom(document));
  1027. };
  1028. var getBody = function (doc) {
  1029. var b = doc.dom.body;
  1030. if (b === null || b === undefined) {
  1031. throw new Error('Body is not available yet');
  1032. }
  1033. return SugarElement.fromDom(b);
  1034. };
  1035. var fireDetaching = function (component) {
  1036. emit(component, detachedFromDom());
  1037. var children = component.components();
  1038. each$1(children, fireDetaching);
  1039. };
  1040. var fireAttaching = function (component) {
  1041. var children = component.components();
  1042. each$1(children, fireAttaching);
  1043. emit(component, attachedToDom());
  1044. };
  1045. var attach$1 = function (parent, child) {
  1046. append$2(parent.element, child.element);
  1047. };
  1048. var detachChildren = function (component) {
  1049. each$1(component.components(), function (childComp) {
  1050. return remove$7(childComp.element);
  1051. });
  1052. empty(component.element);
  1053. component.syncComponents();
  1054. };
  1055. var replaceChildren = function (component, newChildren) {
  1056. var subs = component.components();
  1057. detachChildren(component);
  1058. var deleted = difference(subs, newChildren);
  1059. each$1(deleted, function (comp) {
  1060. fireDetaching(comp);
  1061. component.getSystem().removeFromWorld(comp);
  1062. });
  1063. each$1(newChildren, function (childComp) {
  1064. if (!childComp.getSystem().isConnected()) {
  1065. component.getSystem().addToWorld(childComp);
  1066. attach$1(component, childComp);
  1067. if (inBody(component.element)) {
  1068. fireAttaching(childComp);
  1069. }
  1070. } else {
  1071. attach$1(component, childComp);
  1072. }
  1073. component.syncComponents();
  1074. });
  1075. };
  1076. var attach = function (parent, child) {
  1077. attachWith(parent, child, append$2);
  1078. };
  1079. var attachWith = function (parent, child, insertion) {
  1080. parent.getSystem().addToWorld(child);
  1081. insertion(parent.element, child.element);
  1082. if (inBody(parent.element)) {
  1083. fireAttaching(child);
  1084. }
  1085. parent.syncComponents();
  1086. };
  1087. var doDetach = function (component) {
  1088. fireDetaching(component);
  1089. remove$7(component.element);
  1090. component.getSystem().removeFromWorld(component);
  1091. };
  1092. var detach = function (component) {
  1093. var parent$1 = parent(component.element).bind(function (p) {
  1094. return component.getSystem().getByDom(p).toOptional();
  1095. });
  1096. doDetach(component);
  1097. parent$1.each(function (p) {
  1098. p.syncComponents();
  1099. });
  1100. };
  1101. var attachSystemAfter = function (element, guiSystem) {
  1102. attachSystemWith(element, guiSystem, after$2);
  1103. };
  1104. var attachSystemWith = function (element, guiSystem, inserter) {
  1105. inserter(element, guiSystem.element);
  1106. var children$1 = children(guiSystem.element);
  1107. each$1(children$1, function (child) {
  1108. guiSystem.getByDom(child).each(fireAttaching);
  1109. });
  1110. };
  1111. var detachSystem = function (guiSystem) {
  1112. var children$1 = children(guiSystem.element);
  1113. each$1(children$1, function (child) {
  1114. guiSystem.getByDom(child).each(fireDetaching);
  1115. });
  1116. remove$7(guiSystem.element);
  1117. };
  1118. var keys = Object.keys;
  1119. var hasOwnProperty = Object.hasOwnProperty;
  1120. var each = function (obj, f) {
  1121. var props = keys(obj);
  1122. for (var k = 0, len = props.length; k < len; k++) {
  1123. var i = props[k];
  1124. var x = obj[i];
  1125. f(x, i);
  1126. }
  1127. };
  1128. var map$1 = function (obj, f) {
  1129. return tupleMap(obj, function (x, i) {
  1130. return {
  1131. k: i,
  1132. v: f(x, i)
  1133. };
  1134. });
  1135. };
  1136. var tupleMap = function (obj, f) {
  1137. var r = {};
  1138. each(obj, function (x, i) {
  1139. var tuple = f(x, i);
  1140. r[tuple.k] = tuple.v;
  1141. });
  1142. return r;
  1143. };
  1144. var objAcc = function (r) {
  1145. return function (x, i) {
  1146. r[i] = x;
  1147. };
  1148. };
  1149. var internalFilter = function (obj, pred, onTrue, onFalse) {
  1150. var r = {};
  1151. each(obj, function (x, i) {
  1152. (pred(x, i) ? onTrue : onFalse)(x, i);
  1153. });
  1154. return r;
  1155. };
  1156. var filter$1 = function (obj, pred) {
  1157. var t = {};
  1158. internalFilter(obj, pred, objAcc(t), noop);
  1159. return t;
  1160. };
  1161. var mapToArray = function (obj, f) {
  1162. var r = [];
  1163. each(obj, function (value, name) {
  1164. r.push(f(value, name));
  1165. });
  1166. return r;
  1167. };
  1168. var find = function (obj, pred) {
  1169. var props = keys(obj);
  1170. for (var k = 0, len = props.length; k < len; k++) {
  1171. var i = props[k];
  1172. var x = obj[i];
  1173. if (pred(x, i, obj)) {
  1174. return Optional.some(x);
  1175. }
  1176. }
  1177. return Optional.none();
  1178. };
  1179. var values = function (obj) {
  1180. return mapToArray(obj, identity);
  1181. };
  1182. var get$c = function (obj, key) {
  1183. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  1184. };
  1185. var has$2 = function (obj, key) {
  1186. return hasOwnProperty.call(obj, key);
  1187. };
  1188. var hasNonNullableKey = function (obj, key) {
  1189. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  1190. };
  1191. var rawSet = function (dom, key, value) {
  1192. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1193. dom.setAttribute(key, value + '');
  1194. } else {
  1195. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1196. throw new Error('Attribute value was not simple');
  1197. }
  1198. };
  1199. var set$8 = function (element, key, value) {
  1200. rawSet(element.dom, key, value);
  1201. };
  1202. var setAll$1 = function (element, attrs) {
  1203. var dom = element.dom;
  1204. each(attrs, function (v, k) {
  1205. rawSet(dom, k, v);
  1206. });
  1207. };
  1208. var get$b = function (element, key) {
  1209. var v = element.dom.getAttribute(key);
  1210. return v === null ? undefined : v;
  1211. };
  1212. var getOpt = function (element, key) {
  1213. return Optional.from(get$b(element, key));
  1214. };
  1215. var has$1 = function (element, key) {
  1216. var dom = element.dom;
  1217. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1218. };
  1219. var remove$6 = function (element, key) {
  1220. element.dom.removeAttribute(key);
  1221. };
  1222. var read$2 = function (element, attr) {
  1223. var value = get$b(element, attr);
  1224. return value === undefined || value === '' ? [] : value.split(' ');
  1225. };
  1226. var add$3 = function (element, attr, id) {
  1227. var old = read$2(element, attr);
  1228. var nu = old.concat([id]);
  1229. set$8(element, attr, nu.join(' '));
  1230. return true;
  1231. };
  1232. var remove$5 = function (element, attr, id) {
  1233. var nu = filter$2(read$2(element, attr), function (v) {
  1234. return v !== id;
  1235. });
  1236. if (nu.length > 0) {
  1237. set$8(element, attr, nu.join(' '));
  1238. } else {
  1239. remove$6(element, attr);
  1240. }
  1241. return false;
  1242. };
  1243. var supports = function (element) {
  1244. return element.dom.classList !== undefined;
  1245. };
  1246. var get$a = function (element) {
  1247. return read$2(element, 'class');
  1248. };
  1249. var add$2 = function (element, clazz) {
  1250. return add$3(element, 'class', clazz);
  1251. };
  1252. var remove$4 = function (element, clazz) {
  1253. return remove$5(element, 'class', clazz);
  1254. };
  1255. var add$1 = function (element, clazz) {
  1256. if (supports(element)) {
  1257. element.dom.classList.add(clazz);
  1258. } else {
  1259. add$2(element, clazz);
  1260. }
  1261. };
  1262. var cleanClass = function (element) {
  1263. var classList = supports(element) ? element.dom.classList : get$a(element);
  1264. if (classList.length === 0) {
  1265. remove$6(element, 'class');
  1266. }
  1267. };
  1268. var remove$3 = function (element, clazz) {
  1269. if (supports(element)) {
  1270. var classList = element.dom.classList;
  1271. classList.remove(clazz);
  1272. } else {
  1273. remove$4(element, clazz);
  1274. }
  1275. cleanClass(element);
  1276. };
  1277. var has = function (element, clazz) {
  1278. return supports(element) && element.dom.classList.contains(clazz);
  1279. };
  1280. var swap = function (element, addCls, removeCls) {
  1281. remove$3(element, removeCls);
  1282. add$1(element, addCls);
  1283. };
  1284. var toAlpha = function (component, swapConfig, _swapState) {
  1285. swap(component.element, swapConfig.alpha, swapConfig.omega);
  1286. };
  1287. var toOmega = function (component, swapConfig, _swapState) {
  1288. swap(component.element, swapConfig.omega, swapConfig.alpha);
  1289. };
  1290. var clear$1 = function (component, swapConfig, _swapState) {
  1291. remove$3(component.element, swapConfig.alpha);
  1292. remove$3(component.element, swapConfig.omega);
  1293. };
  1294. var isAlpha = function (component, swapConfig, _swapState) {
  1295. return has(component.element, swapConfig.alpha);
  1296. };
  1297. var isOmega = function (component, swapConfig, _swapState) {
  1298. return has(component.element, swapConfig.omega);
  1299. };
  1300. var SwapApis = /*#__PURE__*/Object.freeze({
  1301. __proto__: null,
  1302. toAlpha: toAlpha,
  1303. toOmega: toOmega,
  1304. isAlpha: isAlpha,
  1305. isOmega: isOmega,
  1306. clear: clear$1
  1307. });
  1308. var value$2 = function (o) {
  1309. var or = function (_opt) {
  1310. return value$2(o);
  1311. };
  1312. var orThunk = function (_f) {
  1313. return value$2(o);
  1314. };
  1315. var map = function (f) {
  1316. return value$2(f(o));
  1317. };
  1318. var mapError = function (_f) {
  1319. return value$2(o);
  1320. };
  1321. var each = function (f) {
  1322. f(o);
  1323. };
  1324. var bind = function (f) {
  1325. return f(o);
  1326. };
  1327. var fold = function (_, onValue) {
  1328. return onValue(o);
  1329. };
  1330. var exists = function (f) {
  1331. return f(o);
  1332. };
  1333. var forall = function (f) {
  1334. return f(o);
  1335. };
  1336. var toOptional = function () {
  1337. return Optional.some(o);
  1338. };
  1339. return {
  1340. isValue: always,
  1341. isError: never,
  1342. getOr: constant$1(o),
  1343. getOrThunk: constant$1(o),
  1344. getOrDie: constant$1(o),
  1345. or: or,
  1346. orThunk: orThunk,
  1347. fold: fold,
  1348. map: map,
  1349. mapError: mapError,
  1350. each: each,
  1351. bind: bind,
  1352. exists: exists,
  1353. forall: forall,
  1354. toOptional: toOptional
  1355. };
  1356. };
  1357. var error = function (message) {
  1358. var getOrThunk = function (f) {
  1359. return f();
  1360. };
  1361. var getOrDie = function () {
  1362. return die(String(message))();
  1363. };
  1364. var or = identity;
  1365. var orThunk = function (f) {
  1366. return f();
  1367. };
  1368. var map = function (_f) {
  1369. return error(message);
  1370. };
  1371. var mapError = function (f) {
  1372. return error(f(message));
  1373. };
  1374. var bind = function (_f) {
  1375. return error(message);
  1376. };
  1377. var fold = function (onError, _) {
  1378. return onError(message);
  1379. };
  1380. return {
  1381. isValue: never,
  1382. isError: always,
  1383. getOr: identity,
  1384. getOrThunk: getOrThunk,
  1385. getOrDie: getOrDie,
  1386. or: or,
  1387. orThunk: orThunk,
  1388. fold: fold,
  1389. map: map,
  1390. mapError: mapError,
  1391. each: noop,
  1392. bind: bind,
  1393. exists: never,
  1394. forall: always,
  1395. toOptional: Optional.none
  1396. };
  1397. };
  1398. var fromOption = function (opt, err) {
  1399. return opt.fold(function () {
  1400. return error(err);
  1401. }, value$2);
  1402. };
  1403. var Result = {
  1404. value: value$2,
  1405. error: error,
  1406. fromOption: fromOption
  1407. };
  1408. var SimpleResultType;
  1409. (function (SimpleResultType) {
  1410. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1411. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1412. }(SimpleResultType || (SimpleResultType = {})));
  1413. var fold$1 = function (res, onError, onValue) {
  1414. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1415. };
  1416. var partition$1 = function (results) {
  1417. var values = [];
  1418. var errors = [];
  1419. each$1(results, function (obj) {
  1420. fold$1(obj, function (err) {
  1421. return errors.push(err);
  1422. }, function (val) {
  1423. return values.push(val);
  1424. });
  1425. });
  1426. return {
  1427. values: values,
  1428. errors: errors
  1429. };
  1430. };
  1431. var mapError = function (res, f) {
  1432. if (res.stype === SimpleResultType.Error) {
  1433. return {
  1434. stype: SimpleResultType.Error,
  1435. serror: f(res.serror)
  1436. };
  1437. } else {
  1438. return res;
  1439. }
  1440. };
  1441. var map = function (res, f) {
  1442. if (res.stype === SimpleResultType.Value) {
  1443. return {
  1444. stype: SimpleResultType.Value,
  1445. svalue: f(res.svalue)
  1446. };
  1447. } else {
  1448. return res;
  1449. }
  1450. };
  1451. var bind$2 = function (res, f) {
  1452. if (res.stype === SimpleResultType.Value) {
  1453. return f(res.svalue);
  1454. } else {
  1455. return res;
  1456. }
  1457. };
  1458. var bindError = function (res, f) {
  1459. if (res.stype === SimpleResultType.Error) {
  1460. return f(res.serror);
  1461. } else {
  1462. return res;
  1463. }
  1464. };
  1465. var svalue = function (v) {
  1466. return {
  1467. stype: SimpleResultType.Value,
  1468. svalue: v
  1469. };
  1470. };
  1471. var serror = function (e) {
  1472. return {
  1473. stype: SimpleResultType.Error,
  1474. serror: e
  1475. };
  1476. };
  1477. var toResult$1 = function (res) {
  1478. return fold$1(res, Result.error, Result.value);
  1479. };
  1480. var fromResult = function (res) {
  1481. return res.fold(serror, svalue);
  1482. };
  1483. var SimpleResult = {
  1484. fromResult: fromResult,
  1485. toResult: toResult$1,
  1486. svalue: svalue,
  1487. partition: partition$1,
  1488. serror: serror,
  1489. bind: bind$2,
  1490. bindError: bindError,
  1491. map: map,
  1492. mapError: mapError,
  1493. fold: fold$1
  1494. };
  1495. var field$3 = function (key, newKey, presence, prop) {
  1496. return {
  1497. tag: 'field',
  1498. key: key,
  1499. newKey: newKey,
  1500. presence: presence,
  1501. prop: prop
  1502. };
  1503. };
  1504. var customField$1 = function (newKey, instantiator) {
  1505. return {
  1506. tag: 'custom',
  1507. newKey: newKey,
  1508. instantiator: instantiator
  1509. };
  1510. };
  1511. var fold = function (value, ifField, ifCustom) {
  1512. switch (value.tag) {
  1513. case 'field':
  1514. return ifField(value.key, value.newKey, value.presence, value.prop);
  1515. case 'custom':
  1516. return ifCustom(value.newKey, value.instantiator);
  1517. }
  1518. };
  1519. var shallow$1 = function (old, nu) {
  1520. return nu;
  1521. };
  1522. var deep = function (old, nu) {
  1523. var bothObjects = isObject(old) && isObject(nu);
  1524. return bothObjects ? deepMerge(old, nu) : nu;
  1525. };
  1526. var baseMerge = function (merger) {
  1527. return function () {
  1528. var objects = [];
  1529. for (var _i = 0; _i < arguments.length; _i++) {
  1530. objects[_i] = arguments[_i];
  1531. }
  1532. if (objects.length === 0) {
  1533. throw new Error('Can\'t merge zero objects');
  1534. }
  1535. var ret = {};
  1536. for (var j = 0; j < objects.length; j++) {
  1537. var curObject = objects[j];
  1538. for (var key in curObject) {
  1539. if (has$2(curObject, key)) {
  1540. ret[key] = merger(ret[key], curObject[key]);
  1541. }
  1542. }
  1543. }
  1544. return ret;
  1545. };
  1546. };
  1547. var deepMerge = baseMerge(deep);
  1548. var merge$1 = baseMerge(shallow$1);
  1549. var required$2 = function () {
  1550. return {
  1551. tag: 'required',
  1552. process: {}
  1553. };
  1554. };
  1555. var defaultedThunk = function (fallbackThunk) {
  1556. return {
  1557. tag: 'defaultedThunk',
  1558. process: fallbackThunk
  1559. };
  1560. };
  1561. var defaulted$1 = function (fallback) {
  1562. return defaultedThunk(constant$1(fallback));
  1563. };
  1564. var asOption = function () {
  1565. return {
  1566. tag: 'option',
  1567. process: {}
  1568. };
  1569. };
  1570. var mergeWithThunk = function (baseThunk) {
  1571. return {
  1572. tag: 'mergeWithThunk',
  1573. process: baseThunk
  1574. };
  1575. };
  1576. var mergeWith = function (base) {
  1577. return mergeWithThunk(constant$1(base));
  1578. };
  1579. var mergeValues$1 = function (values, base) {
  1580. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  1581. };
  1582. var mergeErrors$1 = function (errors) {
  1583. return compose(SimpleResult.serror, flatten)(errors);
  1584. };
  1585. var consolidateObj = function (objects, base) {
  1586. var partition = SimpleResult.partition(objects);
  1587. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1588. };
  1589. var consolidateArr = function (objects) {
  1590. var partitions = SimpleResult.partition(objects);
  1591. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1592. };
  1593. var ResultCombine = {
  1594. consolidateObj: consolidateObj,
  1595. consolidateArr: consolidateArr
  1596. };
  1597. var formatObj = function (input) {
  1598. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1599. };
  1600. var formatErrors = function (errors) {
  1601. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1602. path: [],
  1603. getErrorInfo: constant$1('... (only showing first ten failures)')
  1604. }]) : errors;
  1605. return map$2(es, function (e) {
  1606. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1607. });
  1608. };
  1609. var nu$5 = function (path, getErrorInfo) {
  1610. return SimpleResult.serror([{
  1611. path: path,
  1612. getErrorInfo: getErrorInfo
  1613. }]);
  1614. };
  1615. var missingRequired = function (path, key, obj) {
  1616. return nu$5(path, function () {
  1617. return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
  1618. });
  1619. };
  1620. var missingKey = function (path, key) {
  1621. return nu$5(path, function () {
  1622. return 'Choice schema did not contain choice key: "' + key + '"';
  1623. });
  1624. };
  1625. var missingBranch = function (path, branches, branch) {
  1626. return nu$5(path, function () {
  1627. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1628. });
  1629. };
  1630. var unsupportedFields = function (path, unsupported) {
  1631. return nu$5(path, function () {
  1632. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1633. });
  1634. };
  1635. var custom = function (path, err) {
  1636. return nu$5(path, constant$1(err));
  1637. };
  1638. var value$1 = function (validator) {
  1639. var extract = function (path, val) {
  1640. return SimpleResult.bindError(validator(val), function (err) {
  1641. return custom(path, err);
  1642. });
  1643. };
  1644. var toString = constant$1('val');
  1645. return {
  1646. extract: extract,
  1647. toString: toString
  1648. };
  1649. };
  1650. var anyValue$1 = value$1(SimpleResult.svalue);
  1651. var requiredAccess = function (path, obj, key, bundle) {
  1652. return get$c(obj, key).fold(function () {
  1653. return missingRequired(path, key, obj);
  1654. }, bundle);
  1655. };
  1656. var fallbackAccess = function (obj, key, fallback, bundle) {
  1657. var v = get$c(obj, key).getOrThunk(function () {
  1658. return fallback(obj);
  1659. });
  1660. return bundle(v);
  1661. };
  1662. var optionAccess = function (obj, key, bundle) {
  1663. return bundle(get$c(obj, key));
  1664. };
  1665. var optionDefaultedAccess = function (obj, key, fallback, bundle) {
  1666. var opt = get$c(obj, key).map(function (val) {
  1667. return val === true ? fallback(obj) : val;
  1668. });
  1669. return bundle(opt);
  1670. };
  1671. var extractField = function (field, path, obj, key, prop) {
  1672. var bundle = function (av) {
  1673. return prop.extract(path.concat([key]), av);
  1674. };
  1675. var bundleAsOption = function (optValue) {
  1676. return optValue.fold(function () {
  1677. return SimpleResult.svalue(Optional.none());
  1678. }, function (ov) {
  1679. var result = prop.extract(path.concat([key]), ov);
  1680. return SimpleResult.map(result, Optional.some);
  1681. });
  1682. };
  1683. switch (field.tag) {
  1684. case 'required':
  1685. return requiredAccess(path, obj, key, bundle);
  1686. case 'defaultedThunk':
  1687. return fallbackAccess(obj, key, field.process, bundle);
  1688. case 'option':
  1689. return optionAccess(obj, key, bundleAsOption);
  1690. case 'defaultedOptionThunk':
  1691. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  1692. case 'mergeWithThunk': {
  1693. return fallbackAccess(obj, key, constant$1({}), function (v) {
  1694. var result = deepMerge(field.process(obj), v);
  1695. return bundle(result);
  1696. });
  1697. }
  1698. }
  1699. };
  1700. var extractFields = function (path, obj, fields) {
  1701. var success = {};
  1702. var errors = [];
  1703. for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
  1704. var field = fields_1[_i];
  1705. fold(field, function (key, newKey, presence, prop) {
  1706. var result = extractField(presence, path, obj, key, prop);
  1707. SimpleResult.fold(result, function (err) {
  1708. errors.push.apply(errors, err);
  1709. }, function (res) {
  1710. success[newKey] = res;
  1711. });
  1712. }, function (newKey, instantiator) {
  1713. success[newKey] = instantiator(obj);
  1714. });
  1715. }
  1716. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  1717. };
  1718. var getSetKeys = function (obj) {
  1719. return keys(filter$1(obj, isNonNullable));
  1720. };
  1721. var objOfOnly = function (fields) {
  1722. var delegate = objOf(fields);
  1723. var fieldNames = foldr(fields, function (acc, value) {
  1724. return fold(value, function (key) {
  1725. var _a;
  1726. return deepMerge(acc, (_a = {}, _a[key] = true, _a));
  1727. }, constant$1(acc));
  1728. }, {});
  1729. var extract = function (path, o) {
  1730. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1731. var extra = filter$2(keys, function (k) {
  1732. return !hasNonNullableKey(fieldNames, k);
  1733. });
  1734. return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  1735. };
  1736. return {
  1737. extract: extract,
  1738. toString: delegate.toString
  1739. };
  1740. };
  1741. var objOf = function (values) {
  1742. var extract = function (path, o) {
  1743. return extractFields(path, o, values);
  1744. };
  1745. var toString = function () {
  1746. var fieldStrings = map$2(values, function (value) {
  1747. return fold(value, function (key, _okey, _presence, prop) {
  1748. return key + ' -> ' + prop.toString();
  1749. }, function (newKey, _instantiator) {
  1750. return 'state(' + newKey + ')';
  1751. });
  1752. });
  1753. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1754. };
  1755. return {
  1756. extract: extract,
  1757. toString: toString
  1758. };
  1759. };
  1760. var arrOf = function (prop) {
  1761. var extract = function (path, array) {
  1762. var results = map$2(array, function (a, i) {
  1763. return prop.extract(path.concat(['[' + i + ']']), a);
  1764. });
  1765. return ResultCombine.consolidateArr(results);
  1766. };
  1767. var toString = function () {
  1768. return 'array(' + prop.toString() + ')';
  1769. };
  1770. return {
  1771. extract: extract,
  1772. toString: toString
  1773. };
  1774. };
  1775. var setOf$1 = function (validator, prop) {
  1776. var validateKeys = function (path, keys) {
  1777. return arrOf(value$1(validator)).extract(path, keys);
  1778. };
  1779. var extract = function (path, o) {
  1780. var keys$1 = keys(o);
  1781. var validatedKeys = validateKeys(path, keys$1);
  1782. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1783. var schema = map$2(validKeys, function (vk) {
  1784. return field$3(vk, vk, required$2(), prop);
  1785. });
  1786. return objOf(schema).extract(path, o);
  1787. });
  1788. };
  1789. var toString = function () {
  1790. return 'setOf(' + prop.toString() + ')';
  1791. };
  1792. return {
  1793. extract: extract,
  1794. toString: toString
  1795. };
  1796. };
  1797. var anyValue = constant$1(anyValue$1);
  1798. var typedValue = function (validator, expectedType) {
  1799. return value$1(function (a) {
  1800. var actualType = typeof a;
  1801. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1802. });
  1803. };
  1804. var functionProcessor = typedValue(isFunction, 'function');
  1805. var chooseFrom = function (path, input, branches, ch) {
  1806. var fields = get$c(branches, ch);
  1807. return fields.fold(function () {
  1808. return missingBranch(path, branches, ch);
  1809. }, function (vp) {
  1810. return vp.extract(path.concat(['branch: ' + ch]), input);
  1811. });
  1812. };
  1813. var choose$2 = function (key, branches) {
  1814. var extract = function (path, input) {
  1815. var choice = get$c(input, key);
  1816. return choice.fold(function () {
  1817. return missingKey(path, key);
  1818. }, function (chosen) {
  1819. return chooseFrom(path, input, branches, chosen);
  1820. });
  1821. };
  1822. var toString = function () {
  1823. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1824. };
  1825. return {
  1826. extract: extract,
  1827. toString: toString
  1828. };
  1829. };
  1830. var valueOf = function (validator) {
  1831. return value$1(function (v) {
  1832. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1833. });
  1834. };
  1835. var setOf = function (validator, prop) {
  1836. return setOf$1(function (v) {
  1837. return SimpleResult.fromResult(validator(v));
  1838. }, prop);
  1839. };
  1840. var extractValue = function (label, prop, obj) {
  1841. var res = prop.extract([label], obj);
  1842. return SimpleResult.mapError(res, function (errs) {
  1843. return {
  1844. input: obj,
  1845. errors: errs
  1846. };
  1847. });
  1848. };
  1849. var asRaw = function (label, prop, obj) {
  1850. return SimpleResult.toResult(extractValue(label, prop, obj));
  1851. };
  1852. var getOrDie = function (extraction) {
  1853. return extraction.fold(function (errInfo) {
  1854. throw new Error(formatError(errInfo));
  1855. }, identity);
  1856. };
  1857. var asRawOrDie$1 = function (label, prop, obj) {
  1858. return getOrDie(asRaw(label, prop, obj));
  1859. };
  1860. var formatError = function (errInfo) {
  1861. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1862. };
  1863. var choose$1 = function (key, branches) {
  1864. return choose$2(key, map$1(branches, objOf));
  1865. };
  1866. var field$2 = field$3;
  1867. var customField = customField$1;
  1868. var required$1 = function (key) {
  1869. return field$2(key, key, required$2(), anyValue());
  1870. };
  1871. var requiredOf = function (key, schema) {
  1872. return field$2(key, key, required$2(), schema);
  1873. };
  1874. var forbid = function (key, message) {
  1875. return field$2(key, key, asOption(), value$1(function (_v) {
  1876. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1877. }));
  1878. };
  1879. var requiredObjOf = function (key, objSchema) {
  1880. return field$2(key, key, required$2(), objOf(objSchema));
  1881. };
  1882. var option = function (key) {
  1883. return field$2(key, key, asOption(), anyValue());
  1884. };
  1885. var optionOf = function (key, schema) {
  1886. return field$2(key, key, asOption(), schema);
  1887. };
  1888. var optionObjOf = function (key, objSchema) {
  1889. return optionOf(key, objOf(objSchema));
  1890. };
  1891. var optionObjOfOnly = function (key, objSchema) {
  1892. return optionOf(key, objOfOnly(objSchema));
  1893. };
  1894. var defaulted = function (key, fallback) {
  1895. return field$2(key, key, defaulted$1(fallback), anyValue());
  1896. };
  1897. var defaultedOf = function (key, fallback, schema) {
  1898. return field$2(key, key, defaulted$1(fallback), schema);
  1899. };
  1900. var defaultedFunction = function (key, fallback) {
  1901. return defaultedOf(key, fallback, functionProcessor);
  1902. };
  1903. var defaultedObjOf = function (key, fallback, objSchema) {
  1904. return defaultedOf(key, fallback, objOf(objSchema));
  1905. };
  1906. var SwapSchema = [
  1907. required$1('alpha'),
  1908. required$1('omega')
  1909. ];
  1910. var generate$5 = function (cases) {
  1911. if (!isArray(cases)) {
  1912. throw new Error('cases must be an array');
  1913. }
  1914. if (cases.length === 0) {
  1915. throw new Error('there must be at least one case');
  1916. }
  1917. var constructors = [];
  1918. var adt = {};
  1919. each$1(cases, function (acase, count) {
  1920. var keys$1 = keys(acase);
  1921. if (keys$1.length !== 1) {
  1922. throw new Error('one and only one name per case');
  1923. }
  1924. var key = keys$1[0];
  1925. var value = acase[key];
  1926. if (adt[key] !== undefined) {
  1927. throw new Error('duplicate key detected:' + key);
  1928. } else if (key === 'cata') {
  1929. throw new Error('cannot have a case named cata (sorry)');
  1930. } else if (!isArray(value)) {
  1931. throw new Error('case arguments must be an array');
  1932. }
  1933. constructors.push(key);
  1934. adt[key] = function () {
  1935. var args = [];
  1936. for (var _i = 0; _i < arguments.length; _i++) {
  1937. args[_i] = arguments[_i];
  1938. }
  1939. var argLength = args.length;
  1940. if (argLength !== value.length) {
  1941. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1942. }
  1943. var match = function (branches) {
  1944. var branchKeys = keys(branches);
  1945. if (constructors.length !== branchKeys.length) {
  1946. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1947. }
  1948. var allReqd = forall(constructors, function (reqKey) {
  1949. return contains$1(branchKeys, reqKey);
  1950. });
  1951. if (!allReqd) {
  1952. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1953. }
  1954. return branches[key].apply(null, args);
  1955. };
  1956. return {
  1957. fold: function () {
  1958. var foldArgs = [];
  1959. for (var _i = 0; _i < arguments.length; _i++) {
  1960. foldArgs[_i] = arguments[_i];
  1961. }
  1962. if (foldArgs.length !== cases.length) {
  1963. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  1964. }
  1965. var target = foldArgs[count];
  1966. return target.apply(null, args);
  1967. },
  1968. match: match,
  1969. log: function (label) {
  1970. console.log(label, {
  1971. constructors: constructors,
  1972. constructor: key,
  1973. params: args
  1974. });
  1975. }
  1976. };
  1977. };
  1978. });
  1979. return adt;
  1980. };
  1981. var Adt = { generate: generate$5 };
  1982. Adt.generate([
  1983. {
  1984. bothErrors: [
  1985. 'error1',
  1986. 'error2'
  1987. ]
  1988. },
  1989. {
  1990. firstError: [
  1991. 'error1',
  1992. 'value2'
  1993. ]
  1994. },
  1995. {
  1996. secondError: [
  1997. 'value1',
  1998. 'error2'
  1999. ]
  2000. },
  2001. {
  2002. bothValues: [
  2003. 'value1',
  2004. 'value2'
  2005. ]
  2006. }
  2007. ]);
  2008. var partition = function (results) {
  2009. var errors = [];
  2010. var values = [];
  2011. each$1(results, function (result) {
  2012. result.fold(function (err) {
  2013. errors.push(err);
  2014. }, function (value) {
  2015. values.push(value);
  2016. });
  2017. });
  2018. return {
  2019. errors: errors,
  2020. values: values
  2021. };
  2022. };
  2023. var exclude$1 = function (obj, fields) {
  2024. var r = {};
  2025. each(obj, function (v, k) {
  2026. if (!contains$1(fields, k)) {
  2027. r[k] = v;
  2028. }
  2029. });
  2030. return r;
  2031. };
  2032. var wrap$1 = function (key, value) {
  2033. var _a;
  2034. return _a = {}, _a[key] = value, _a;
  2035. };
  2036. var wrapAll$1 = function (keyvalues) {
  2037. var r = {};
  2038. each$1(keyvalues, function (kv) {
  2039. r[kv.key] = kv.value;
  2040. });
  2041. return r;
  2042. };
  2043. var exclude = function (obj, fields) {
  2044. return exclude$1(obj, fields);
  2045. };
  2046. var wrap = function (key, value) {
  2047. return wrap$1(key, value);
  2048. };
  2049. var wrapAll = function (keyvalues) {
  2050. return wrapAll$1(keyvalues);
  2051. };
  2052. var mergeValues = function (values, base) {
  2053. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  2054. };
  2055. var mergeErrors = function (errors) {
  2056. return Result.error(flatten(errors));
  2057. };
  2058. var consolidate = function (objs, base) {
  2059. var partitions = partition(objs);
  2060. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2061. };
  2062. var is = function (lhs, rhs, comparator) {
  2063. if (comparator === void 0) {
  2064. comparator = tripleEquals;
  2065. }
  2066. return lhs.exists(function (left) {
  2067. return comparator(left, rhs);
  2068. });
  2069. };
  2070. var cat = function (arr) {
  2071. var r = [];
  2072. var push = function (x) {
  2073. r.push(x);
  2074. };
  2075. for (var i = 0; i < arr.length; i++) {
  2076. arr[i].each(push);
  2077. }
  2078. return r;
  2079. };
  2080. var sequence = function (arr) {
  2081. var r = [];
  2082. for (var i = 0; i < arr.length; i++) {
  2083. var x = arr[i];
  2084. if (x.isSome()) {
  2085. r.push(x.getOrDie());
  2086. } else {
  2087. return Optional.none();
  2088. }
  2089. }
  2090. return Optional.some(r);
  2091. };
  2092. var lift2 = function (oa, ob, f) {
  2093. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  2094. };
  2095. var someIf = function (b, a) {
  2096. return b ? Optional.some(a) : Optional.none();
  2097. };
  2098. var ensureIsRoot = function (isRoot) {
  2099. return isFunction(isRoot) ? isRoot : never;
  2100. };
  2101. var ancestor$2 = function (scope, transform, isRoot) {
  2102. var element = scope.dom;
  2103. var stop = ensureIsRoot(isRoot);
  2104. while (element.parentNode) {
  2105. element = element.parentNode;
  2106. var el = SugarElement.fromDom(element);
  2107. var transformed = transform(el);
  2108. if (transformed.isSome()) {
  2109. return transformed;
  2110. } else if (stop(el)) {
  2111. break;
  2112. }
  2113. }
  2114. return Optional.none();
  2115. };
  2116. var closest$3 = function (scope, transform, isRoot) {
  2117. var current = transform(scope);
  2118. var stop = ensureIsRoot(isRoot);
  2119. return current.orThunk(function () {
  2120. return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop);
  2121. });
  2122. };
  2123. var isSource = function (component, simulatedEvent) {
  2124. return eq(component.element, simulatedEvent.event.target);
  2125. };
  2126. var defaultEventHandler = {
  2127. can: always,
  2128. abort: never,
  2129. run: noop
  2130. };
  2131. var nu$4 = function (parts) {
  2132. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2133. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2134. }
  2135. return __assign(__assign({}, defaultEventHandler), parts);
  2136. };
  2137. var all$1 = function (handlers, f) {
  2138. return function () {
  2139. var args = [];
  2140. for (var _i = 0; _i < arguments.length; _i++) {
  2141. args[_i] = arguments[_i];
  2142. }
  2143. return foldl(handlers, function (acc, handler) {
  2144. return acc && f(handler).apply(undefined, args);
  2145. }, true);
  2146. };
  2147. };
  2148. var any = function (handlers, f) {
  2149. return function () {
  2150. var args = [];
  2151. for (var _i = 0; _i < arguments.length; _i++) {
  2152. args[_i] = arguments[_i];
  2153. }
  2154. return foldl(handlers, function (acc, handler) {
  2155. return acc || f(handler).apply(undefined, args);
  2156. }, false);
  2157. };
  2158. };
  2159. var read$1 = function (handler) {
  2160. return isFunction(handler) ? {
  2161. can: always,
  2162. abort: never,
  2163. run: handler
  2164. } : handler;
  2165. };
  2166. var fuse$1 = function (handlers) {
  2167. var can = all$1(handlers, function (handler) {
  2168. return handler.can;
  2169. });
  2170. var abort = any(handlers, function (handler) {
  2171. return handler.abort;
  2172. });
  2173. var run = function () {
  2174. var args = [];
  2175. for (var _i = 0; _i < arguments.length; _i++) {
  2176. args[_i] = arguments[_i];
  2177. }
  2178. each$1(handlers, function (handler) {
  2179. handler.run.apply(undefined, args);
  2180. });
  2181. };
  2182. return {
  2183. can: can,
  2184. abort: abort,
  2185. run: run
  2186. };
  2187. };
  2188. var derive$3 = function (configs) {
  2189. return wrapAll(configs);
  2190. };
  2191. var abort = function (name, predicate) {
  2192. return {
  2193. key: name,
  2194. value: nu$4({ abort: predicate })
  2195. };
  2196. };
  2197. var can = function (name, predicate) {
  2198. return {
  2199. key: name,
  2200. value: nu$4({ can: predicate })
  2201. };
  2202. };
  2203. var run = function (name, handler) {
  2204. return {
  2205. key: name,
  2206. value: nu$4({ run: handler })
  2207. };
  2208. };
  2209. var runActionExtra = function (name, action, extra) {
  2210. return {
  2211. key: name,
  2212. value: nu$4({
  2213. run: function (component, simulatedEvent) {
  2214. action.apply(undefined, [
  2215. component,
  2216. simulatedEvent
  2217. ].concat(extra));
  2218. }
  2219. })
  2220. };
  2221. };
  2222. var runOnName = function (name) {
  2223. return function (handler) {
  2224. return run(name, handler);
  2225. };
  2226. };
  2227. var runOnSourceName = function (name) {
  2228. return function (handler) {
  2229. return {
  2230. key: name,
  2231. value: nu$4({
  2232. run: function (component, simulatedEvent) {
  2233. if (isSource(component, simulatedEvent)) {
  2234. handler(component, simulatedEvent);
  2235. }
  2236. }
  2237. })
  2238. };
  2239. };
  2240. };
  2241. var redirectToUid = function (name, uid) {
  2242. return run(name, function (component, simulatedEvent) {
  2243. component.getSystem().getByUid(uid).each(function (redirectee) {
  2244. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2245. });
  2246. });
  2247. };
  2248. var redirectToPart = function (name, detail, partName) {
  2249. var uid = detail.partUids[partName];
  2250. return redirectToUid(name, uid);
  2251. };
  2252. var cutter = function (name) {
  2253. return run(name, function (component, simulatedEvent) {
  2254. simulatedEvent.cut();
  2255. });
  2256. };
  2257. var stopper = function (name) {
  2258. return run(name, function (component, simulatedEvent) {
  2259. simulatedEvent.stop();
  2260. });
  2261. };
  2262. var runOnSource = function (name, f) {
  2263. return runOnSourceName(name)(f);
  2264. };
  2265. var runOnAttached = runOnSourceName(attachedToDom());
  2266. var runOnDetached = runOnSourceName(detachedFromDom());
  2267. var runOnInit = runOnSourceName(systemInit());
  2268. var runOnExecute = runOnName(execute$5());
  2269. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2270. var delegate = apiFunction.toString();
  2271. var endIndex = delegate.indexOf(')') + 1;
  2272. var openBracketIndex = delegate.indexOf('(');
  2273. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2274. f.toFunctionAnnotation = function () {
  2275. return {
  2276. name: apiName,
  2277. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2278. };
  2279. };
  2280. return f;
  2281. };
  2282. var cleanParameters = function (parameters) {
  2283. return map$2(parameters, function (p) {
  2284. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2285. });
  2286. };
  2287. var markAsExtraApi = function (f, extraName) {
  2288. var delegate = f.toString();
  2289. var endIndex = delegate.indexOf(')') + 1;
  2290. var openBracketIndex = delegate.indexOf('(');
  2291. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2292. f.toFunctionAnnotation = function () {
  2293. return {
  2294. name: extraName,
  2295. parameters: cleanParameters(parameters)
  2296. };
  2297. };
  2298. return f;
  2299. };
  2300. var markAsSketchApi = function (f, apiFunction) {
  2301. var delegate = apiFunction.toString();
  2302. var endIndex = delegate.indexOf(')') + 1;
  2303. var openBracketIndex = delegate.indexOf('(');
  2304. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2305. f.toFunctionAnnotation = function () {
  2306. return {
  2307. name: 'OVERRIDE',
  2308. parameters: cleanParameters(parameters.slice(1))
  2309. };
  2310. };
  2311. return f;
  2312. };
  2313. var nu$3 = function (s) {
  2314. return {
  2315. classes: isUndefined(s.classes) ? [] : s.classes,
  2316. attributes: isUndefined(s.attributes) ? {} : s.attributes,
  2317. styles: isUndefined(s.styles) ? {} : s.styles
  2318. };
  2319. };
  2320. var merge = function (defnA, mod) {
  2321. return __assign(__assign({}, defnA), {
  2322. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2323. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2324. classes: defnA.classes.concat(mod.classes)
  2325. });
  2326. };
  2327. var executeEvent = function (bConfig, bState, executor) {
  2328. return runOnExecute(function (component) {
  2329. executor(component, bConfig, bState);
  2330. });
  2331. };
  2332. var loadEvent = function (bConfig, bState, f) {
  2333. return runOnInit(function (component, _simulatedEvent) {
  2334. f(component, bConfig, bState);
  2335. });
  2336. };
  2337. var create$6 = function (schema, name, active, apis, extra, state) {
  2338. var configSchema = objOfOnly(schema);
  2339. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2340. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2341. };
  2342. var createModes$1 = function (modes, name, active, apis, extra, state) {
  2343. var configSchema = modes;
  2344. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2345. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2346. };
  2347. var wrapApi = function (bName, apiFunction, apiName) {
  2348. var f = function (component) {
  2349. var rest = [];
  2350. for (var _i = 1; _i < arguments.length; _i++) {
  2351. rest[_i - 1] = arguments[_i];
  2352. }
  2353. var args = [component].concat(rest);
  2354. return component.config({ name: constant$1(bName) }).fold(function () {
  2355. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2356. }, function (info) {
  2357. var rest = Array.prototype.slice.call(args, 1);
  2358. return apiFunction.apply(undefined, [
  2359. component,
  2360. info.config,
  2361. info.state
  2362. ].concat(rest));
  2363. });
  2364. };
  2365. return markAsBehaviourApi(f, apiName, apiFunction);
  2366. };
  2367. var revokeBehaviour = function (name) {
  2368. return {
  2369. key: name,
  2370. value: undefined
  2371. };
  2372. };
  2373. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2374. var getConfig = function (info) {
  2375. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  2376. };
  2377. var wrappedApis = map$1(apis, function (apiF, apiName) {
  2378. return wrapApi(name, apiF, apiName);
  2379. });
  2380. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  2381. return markAsExtraApi(extraF, extraName);
  2382. });
  2383. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2384. revoke: curry(revokeBehaviour, name),
  2385. config: function (spec) {
  2386. var prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  2387. return {
  2388. key: name,
  2389. value: {
  2390. config: prepared,
  2391. me: me,
  2392. configAsRaw: cached(function () {
  2393. return asRawOrDie$1(name + '-config', configSchema, spec);
  2394. }),
  2395. initialConfig: spec,
  2396. state: state
  2397. }
  2398. };
  2399. },
  2400. schema: constant$1(schemaSchema),
  2401. exhibit: function (info, base) {
  2402. return lift2(getConfig(info), get$c(active, 'exhibit'), function (behaviourInfo, exhibitor) {
  2403. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2404. }).getOrThunk(function () {
  2405. return nu$3({});
  2406. });
  2407. },
  2408. name: constant$1(name),
  2409. handlers: function (info) {
  2410. return getConfig(info).map(function (behaviourInfo) {
  2411. var getEvents = get$c(active, 'events').getOr(function () {
  2412. return {};
  2413. });
  2414. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2415. }).getOr({});
  2416. }
  2417. });
  2418. return me;
  2419. };
  2420. var NoState = {
  2421. init: function () {
  2422. return nu$2({ readState: constant$1('No State required') });
  2423. }
  2424. };
  2425. var nu$2 = function (spec) {
  2426. return spec;
  2427. };
  2428. var derive$2 = function (capabilities) {
  2429. return wrapAll(capabilities);
  2430. };
  2431. var simpleSchema = objOfOnly([
  2432. required$1('fields'),
  2433. required$1('name'),
  2434. defaulted('active', {}),
  2435. defaulted('apis', {}),
  2436. defaulted('state', NoState),
  2437. defaulted('extra', {})
  2438. ]);
  2439. var create$5 = function (data) {
  2440. var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  2441. return create$6(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2442. };
  2443. var modeSchema = objOfOnly([
  2444. required$1('branchKey'),
  2445. required$1('branches'),
  2446. required$1('name'),
  2447. defaulted('active', {}),
  2448. defaulted('apis', {}),
  2449. defaulted('state', NoState),
  2450. defaulted('extra', {})
  2451. ]);
  2452. var createModes = function (data) {
  2453. var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  2454. return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2455. };
  2456. var revoke = constant$1(undefined);
  2457. var Swapping = create$5({
  2458. fields: SwapSchema,
  2459. name: 'swapping',
  2460. apis: SwapApis
  2461. });
  2462. var Cell = function (initial) {
  2463. var value = initial;
  2464. var get = function () {
  2465. return value;
  2466. };
  2467. var set = function (v) {
  2468. value = v;
  2469. };
  2470. return {
  2471. get: get,
  2472. set: set
  2473. };
  2474. };
  2475. var getDocument = function () {
  2476. return SugarElement.fromDom(document);
  2477. };
  2478. var focus$3 = function (element) {
  2479. return element.dom.focus();
  2480. };
  2481. var blur$1 = function (element) {
  2482. return element.dom.blur();
  2483. };
  2484. var hasFocus = function (element) {
  2485. var root = getRootNode(element).dom;
  2486. return element.dom === root.activeElement;
  2487. };
  2488. var active = function (root) {
  2489. if (root === void 0) {
  2490. root = getDocument();
  2491. }
  2492. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  2493. };
  2494. var search = function (element) {
  2495. return active(getRootNode(element)).filter(function (e) {
  2496. return element.dom.contains(e.dom);
  2497. });
  2498. };
  2499. var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2500. var global$4 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2501. var openLink = function (target) {
  2502. var link = document.createElement('a');
  2503. link.target = '_blank';
  2504. link.href = target.href;
  2505. link.rel = 'noreferrer noopener';
  2506. var nuEvt = document.createEvent('MouseEvents');
  2507. nuEvt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2508. document.body.appendChild(link);
  2509. link.dispatchEvent(nuEvt);
  2510. document.body.removeChild(link);
  2511. };
  2512. var DefaultStyleFormats = [
  2513. {
  2514. title: 'Headings',
  2515. items: [
  2516. {
  2517. title: 'Heading 1',
  2518. format: 'h1'
  2519. },
  2520. {
  2521. title: 'Heading 2',
  2522. format: 'h2'
  2523. },
  2524. {
  2525. title: 'Heading 3',
  2526. format: 'h3'
  2527. },
  2528. {
  2529. title: 'Heading 4',
  2530. format: 'h4'
  2531. },
  2532. {
  2533. title: 'Heading 5',
  2534. format: 'h5'
  2535. },
  2536. {
  2537. title: 'Heading 6',
  2538. format: 'h6'
  2539. }
  2540. ]
  2541. },
  2542. {
  2543. title: 'Inline',
  2544. items: [
  2545. {
  2546. title: 'Bold',
  2547. icon: 'bold',
  2548. format: 'bold'
  2549. },
  2550. {
  2551. title: 'Italic',
  2552. icon: 'italic',
  2553. format: 'italic'
  2554. },
  2555. {
  2556. title: 'Underline',
  2557. icon: 'underline',
  2558. format: 'underline'
  2559. },
  2560. {
  2561. title: 'Strikethrough',
  2562. icon: 'strikethrough',
  2563. format: 'strikethrough'
  2564. },
  2565. {
  2566. title: 'Superscript',
  2567. icon: 'superscript',
  2568. format: 'superscript'
  2569. },
  2570. {
  2571. title: 'Subscript',
  2572. icon: 'subscript',
  2573. format: 'subscript'
  2574. },
  2575. {
  2576. title: 'Code',
  2577. icon: 'code',
  2578. format: 'code'
  2579. }
  2580. ]
  2581. },
  2582. {
  2583. title: 'Blocks',
  2584. items: [
  2585. {
  2586. title: 'Paragraph',
  2587. format: 'p'
  2588. },
  2589. {
  2590. title: 'Blockquote',
  2591. format: 'blockquote'
  2592. },
  2593. {
  2594. title: 'Div',
  2595. format: 'div'
  2596. },
  2597. {
  2598. title: 'Pre',
  2599. format: 'pre'
  2600. }
  2601. ]
  2602. },
  2603. {
  2604. title: 'Alignment',
  2605. items: [
  2606. {
  2607. title: 'Left',
  2608. icon: 'alignleft',
  2609. format: 'alignleft'
  2610. },
  2611. {
  2612. title: 'Center',
  2613. icon: 'aligncenter',
  2614. format: 'aligncenter'
  2615. },
  2616. {
  2617. title: 'Right',
  2618. icon: 'alignright',
  2619. format: 'alignright'
  2620. },
  2621. {
  2622. title: 'Justify',
  2623. icon: 'alignjustify',
  2624. format: 'alignjustify'
  2625. }
  2626. ]
  2627. }
  2628. ];
  2629. var defaults = [
  2630. 'undo',
  2631. 'bold',
  2632. 'italic',
  2633. 'link',
  2634. 'image',
  2635. 'bullist',
  2636. 'styleselect'
  2637. ];
  2638. var isSkinDisabled = function (editor) {
  2639. return editor.getParam('skin') === false;
  2640. };
  2641. var readOnlyOnInit = function (_editor) {
  2642. return false;
  2643. };
  2644. var getToolbar = function (editor) {
  2645. return editor.getParam('toolbar', defaults, 'array');
  2646. };
  2647. var getStyleFormats = function (editor) {
  2648. return editor.getParam('style_formats', DefaultStyleFormats, 'array');
  2649. };
  2650. var getSkinUrl = function (editor) {
  2651. return editor.getParam('skin_url');
  2652. };
  2653. var formatChanged = 'formatChanged';
  2654. var orientationChanged = 'orientationChanged';
  2655. var dropupDismissed = 'dropupDismissed';
  2656. var fromHtml$1 = function (html, scope) {
  2657. var doc = scope || document;
  2658. var div = doc.createElement('div');
  2659. div.innerHTML = html;
  2660. return children(SugarElement.fromDom(div));
  2661. };
  2662. var get$9 = function (element) {
  2663. return element.dom.innerHTML;
  2664. };
  2665. var set$7 = function (element, content) {
  2666. var owner = owner$2(element);
  2667. var docDom = owner.dom;
  2668. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2669. var contentElements = fromHtml$1(content, docDom);
  2670. append$1(fragment, contentElements);
  2671. empty(element);
  2672. append$2(element, fragment);
  2673. };
  2674. var getOuter = function (element) {
  2675. var container = SugarElement.fromTag('div');
  2676. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2677. append$2(container, clone);
  2678. return get$9(container);
  2679. };
  2680. var clone = function (original, isDeep) {
  2681. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2682. };
  2683. var shallow = function (original) {
  2684. return clone(original, false);
  2685. };
  2686. var getHtml = function (element) {
  2687. if (isShadowRoot(element)) {
  2688. return '#shadow-root';
  2689. } else {
  2690. var clone = shallow(element);
  2691. return getOuter(clone);
  2692. }
  2693. };
  2694. var element = function (elem) {
  2695. return getHtml(elem);
  2696. };
  2697. var chooseChannels = function (channels, message) {
  2698. return message.universal ? channels : filter$2(channels, function (ch) {
  2699. return contains$1(message.channels, ch);
  2700. });
  2701. };
  2702. var events$a = function (receiveConfig) {
  2703. return derive$3([run(receive$1(), function (component, message) {
  2704. var channelMap = receiveConfig.channels;
  2705. var channels = keys(channelMap);
  2706. var receivingData = message;
  2707. var targetChannels = chooseChannels(channels, receivingData);
  2708. each$1(targetChannels, function (ch) {
  2709. var channelInfo = channelMap[ch];
  2710. var channelSchema = channelInfo.schema;
  2711. var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  2712. channelInfo.onReceive(component, data);
  2713. });
  2714. })]);
  2715. };
  2716. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2717. __proto__: null,
  2718. events: events$a
  2719. });
  2720. var unknown = 'unknown';
  2721. var EventConfiguration;
  2722. (function (EventConfiguration) {
  2723. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2724. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2725. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2726. }(EventConfiguration || (EventConfiguration = {})));
  2727. var eventConfig = Cell({});
  2728. var makeEventLogger = function (eventName, initialTarget) {
  2729. var sequence = [];
  2730. var startTime = new Date().getTime();
  2731. return {
  2732. logEventCut: function (_name, target, purpose) {
  2733. sequence.push({
  2734. outcome: 'cut',
  2735. target: target,
  2736. purpose: purpose
  2737. });
  2738. },
  2739. logEventStopped: function (_name, target, purpose) {
  2740. sequence.push({
  2741. outcome: 'stopped',
  2742. target: target,
  2743. purpose: purpose
  2744. });
  2745. },
  2746. logNoParent: function (_name, target, purpose) {
  2747. sequence.push({
  2748. outcome: 'no-parent',
  2749. target: target,
  2750. purpose: purpose
  2751. });
  2752. },
  2753. logEventNoHandlers: function (_name, target) {
  2754. sequence.push({
  2755. outcome: 'no-handlers-left',
  2756. target: target
  2757. });
  2758. },
  2759. logEventResponse: function (_name, target, purpose) {
  2760. sequence.push({
  2761. outcome: 'response',
  2762. purpose: purpose,
  2763. target: target
  2764. });
  2765. },
  2766. write: function () {
  2767. var finishTime = new Date().getTime();
  2768. if (contains$1([
  2769. 'mousemove',
  2770. 'mouseover',
  2771. 'mouseout',
  2772. systemInit()
  2773. ], eventName)) {
  2774. return;
  2775. }
  2776. console.log(eventName, {
  2777. event: eventName,
  2778. time: finishTime - startTime,
  2779. target: initialTarget.dom,
  2780. sequence: map$2(sequence, function (s) {
  2781. if (!contains$1([
  2782. 'cut',
  2783. 'stopped',
  2784. 'response'
  2785. ], s.outcome)) {
  2786. return s.outcome;
  2787. } else {
  2788. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2789. }
  2790. })
  2791. });
  2792. }
  2793. };
  2794. };
  2795. var processEvent = function (eventName, initialTarget, f) {
  2796. var status = get$c(eventConfig.get(), eventName).orThunk(function () {
  2797. var patterns = keys(eventConfig.get());
  2798. return findMap(patterns, function (p) {
  2799. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  2800. });
  2801. }).getOr(EventConfiguration.NORMAL);
  2802. switch (status) {
  2803. case EventConfiguration.NORMAL:
  2804. return f(noLogger());
  2805. case EventConfiguration.LOGGING: {
  2806. var logger = makeEventLogger(eventName, initialTarget);
  2807. var output = f(logger);
  2808. logger.write();
  2809. return output;
  2810. }
  2811. case EventConfiguration.STOP:
  2812. return true;
  2813. }
  2814. };
  2815. var path = [
  2816. 'alloy/data/Fields',
  2817. 'alloy/debugging/Debugging'
  2818. ];
  2819. var getTrace = function () {
  2820. var err = new Error();
  2821. if (err.stack !== undefined) {
  2822. var lines = err.stack.split('\n');
  2823. return find$2(lines, function (line) {
  2824. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2825. return line.indexOf(p) > -1;
  2826. });
  2827. }).getOr(unknown);
  2828. } else {
  2829. return unknown;
  2830. }
  2831. };
  2832. var ignoreEvent = {
  2833. logEventCut: noop,
  2834. logEventStopped: noop,
  2835. logNoParent: noop,
  2836. logEventNoHandlers: noop,
  2837. logEventResponse: noop,
  2838. write: noop
  2839. };
  2840. var monitorEvent = function (eventName, initialTarget, f) {
  2841. return processEvent(eventName, initialTarget, f);
  2842. };
  2843. var noLogger = constant$1(ignoreEvent);
  2844. var menuFields = constant$1([
  2845. required$1('menu'),
  2846. required$1('selectedMenu')
  2847. ]);
  2848. var itemFields = constant$1([
  2849. required$1('item'),
  2850. required$1('selectedItem')
  2851. ]);
  2852. constant$1(objOf(itemFields().concat(menuFields())));
  2853. var itemSchema$1 = constant$1(objOf(itemFields()));
  2854. var _initSize = requiredObjOf('initSize', [
  2855. required$1('numColumns'),
  2856. required$1('numRows')
  2857. ]);
  2858. var itemMarkers = function () {
  2859. return requiredOf('markers', itemSchema$1());
  2860. };
  2861. var tieredMenuMarkers = function () {
  2862. return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2863. };
  2864. var markers = function (required) {
  2865. return requiredObjOf('markers', map$2(required, required$1));
  2866. };
  2867. var onPresenceHandler = function (label, fieldName, presence) {
  2868. getTrace();
  2869. return field$2(fieldName, fieldName, presence, valueOf(function (f) {
  2870. return Result.value(function () {
  2871. var args = [];
  2872. for (var _i = 0; _i < arguments.length; _i++) {
  2873. args[_i] = arguments[_i];
  2874. }
  2875. return f.apply(undefined, args);
  2876. });
  2877. }));
  2878. };
  2879. var onHandler = function (fieldName) {
  2880. return onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  2881. };
  2882. var onKeyboardHandler = function (fieldName) {
  2883. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  2884. };
  2885. var onStrictHandler = function (fieldName) {
  2886. return onPresenceHandler('onHandler', fieldName, required$2());
  2887. };
  2888. var onStrictKeyboardHandler = function (fieldName) {
  2889. return onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  2890. };
  2891. var output = function (name, value) {
  2892. return customField(name, constant$1(value));
  2893. };
  2894. var snapshot = function (name) {
  2895. return customField(name, identity);
  2896. };
  2897. var initSize = constant$1(_initSize);
  2898. var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  2899. onStrictHandler('onReceive'),
  2900. defaulted('schema', anyValue())
  2901. ])))];
  2902. var Receiving = create$5({
  2903. fields: ReceivingSchema,
  2904. name: 'receiving',
  2905. active: ActiveReceiving
  2906. });
  2907. var SetupBehaviourCellState = function (initialState) {
  2908. var init = function () {
  2909. var cell = Cell(initialState);
  2910. var get = function () {
  2911. return cell.get();
  2912. };
  2913. var set = function (newState) {
  2914. return cell.set(newState);
  2915. };
  2916. var clear = function () {
  2917. return cell.set(initialState);
  2918. };
  2919. var readState = function () {
  2920. return cell.get();
  2921. };
  2922. return {
  2923. get: get,
  2924. set: set,
  2925. clear: clear,
  2926. readState: readState
  2927. };
  2928. };
  2929. return { init: init };
  2930. };
  2931. var updateAriaState = function (component, toggleConfig, toggleState) {
  2932. var ariaInfo = toggleConfig.aria;
  2933. ariaInfo.update(component, ariaInfo, toggleState.get());
  2934. };
  2935. var updateClass = function (component, toggleConfig, toggleState) {
  2936. toggleConfig.toggleClass.each(function (toggleClass) {
  2937. if (toggleState.get()) {
  2938. add$1(component.element, toggleClass);
  2939. } else {
  2940. remove$3(component.element, toggleClass);
  2941. }
  2942. });
  2943. };
  2944. var toggle = function (component, toggleConfig, toggleState) {
  2945. set$6(component, toggleConfig, toggleState, !toggleState.get());
  2946. };
  2947. var on$1 = function (component, toggleConfig, toggleState) {
  2948. toggleState.set(true);
  2949. updateClass(component, toggleConfig, toggleState);
  2950. updateAriaState(component, toggleConfig, toggleState);
  2951. };
  2952. var off = function (component, toggleConfig, toggleState) {
  2953. toggleState.set(false);
  2954. updateClass(component, toggleConfig, toggleState);
  2955. updateAriaState(component, toggleConfig, toggleState);
  2956. };
  2957. var set$6 = function (component, toggleConfig, toggleState, state) {
  2958. var action = state ? on$1 : off;
  2959. action(component, toggleConfig, toggleState);
  2960. };
  2961. var isOn = function (component, toggleConfig, toggleState) {
  2962. return toggleState.get();
  2963. };
  2964. var onLoad$5 = function (component, toggleConfig, toggleState) {
  2965. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  2966. };
  2967. var ToggleApis = /*#__PURE__*/Object.freeze({
  2968. __proto__: null,
  2969. onLoad: onLoad$5,
  2970. toggle: toggle,
  2971. isOn: isOn,
  2972. on: on$1,
  2973. off: off,
  2974. set: set$6
  2975. });
  2976. var exhibit$5 = function () {
  2977. return nu$3({});
  2978. };
  2979. var events$9 = function (toggleConfig, toggleState) {
  2980. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2981. var load = loadEvent(toggleConfig, toggleState, onLoad$5);
  2982. return derive$3(flatten([
  2983. toggleConfig.toggleOnExecute ? [execute] : [],
  2984. [load]
  2985. ]));
  2986. };
  2987. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2988. __proto__: null,
  2989. exhibit: exhibit$5,
  2990. events: events$9
  2991. });
  2992. var updatePressed = function (component, ariaInfo, status) {
  2993. set$8(component.element, 'aria-pressed', status);
  2994. if (ariaInfo.syncWithExpanded) {
  2995. updateExpanded(component, ariaInfo, status);
  2996. }
  2997. };
  2998. var updateSelected = function (component, ariaInfo, status) {
  2999. set$8(component.element, 'aria-selected', status);
  3000. };
  3001. var updateChecked = function (component, ariaInfo, status) {
  3002. set$8(component.element, 'aria-checked', status);
  3003. };
  3004. var updateExpanded = function (component, ariaInfo, status) {
  3005. set$8(component.element, 'aria-expanded', status);
  3006. };
  3007. var ToggleSchema = [
  3008. defaulted('selected', false),
  3009. option('toggleClass'),
  3010. defaulted('toggleOnExecute', true),
  3011. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  3012. pressed: [
  3013. defaulted('syncWithExpanded', false),
  3014. output('update', updatePressed)
  3015. ],
  3016. checked: [output('update', updateChecked)],
  3017. expanded: [output('update', updateExpanded)],
  3018. selected: [output('update', updateSelected)],
  3019. none: [output('update', noop)]
  3020. }))
  3021. ];
  3022. var Toggling = create$5({
  3023. fields: ToggleSchema,
  3024. name: 'toggling',
  3025. active: ActiveToggle,
  3026. apis: ToggleApis,
  3027. state: SetupBehaviourCellState(false)
  3028. });
  3029. var format = function (command, update) {
  3030. return Receiving.config({
  3031. channels: wrap(formatChanged, {
  3032. onReceive: function (button, data) {
  3033. if (data.command === command) {
  3034. update(button, data.state);
  3035. }
  3036. }
  3037. })
  3038. });
  3039. };
  3040. var orientation = function (onReceive) {
  3041. return Receiving.config({ channels: wrap(orientationChanged, { onReceive: onReceive }) });
  3042. };
  3043. var receive = function (channel, onReceive) {
  3044. return {
  3045. key: channel,
  3046. value: { onReceive: onReceive }
  3047. };
  3048. };
  3049. var prefix$2 = 'tinymce-mobile';
  3050. var resolve = function (p) {
  3051. return prefix$2 + '-' + p;
  3052. };
  3053. var pointerEvents = function () {
  3054. var onClick = function (component, simulatedEvent) {
  3055. simulatedEvent.stop();
  3056. emitExecute(component);
  3057. };
  3058. return [
  3059. run(click(), onClick),
  3060. run(tap(), onClick),
  3061. cutter(touchstart()),
  3062. cutter(mousedown())
  3063. ];
  3064. };
  3065. var events$8 = function (optAction) {
  3066. var executeHandler = function (action) {
  3067. return runOnExecute(function (component, simulatedEvent) {
  3068. action(component);
  3069. simulatedEvent.stop();
  3070. });
  3071. };
  3072. return derive$3(flatten([
  3073. optAction.map(executeHandler).toArray(),
  3074. pointerEvents()
  3075. ]));
  3076. };
  3077. var focus$2 = function (component, focusConfig) {
  3078. if (!focusConfig.ignore) {
  3079. focus$3(component.element);
  3080. focusConfig.onFocus(component);
  3081. }
  3082. };
  3083. var blur = function (component, focusConfig) {
  3084. if (!focusConfig.ignore) {
  3085. blur$1(component.element);
  3086. }
  3087. };
  3088. var isFocused = function (component) {
  3089. return hasFocus(component.element);
  3090. };
  3091. var FocusApis = /*#__PURE__*/Object.freeze({
  3092. __proto__: null,
  3093. focus: focus$2,
  3094. blur: blur,
  3095. isFocused: isFocused
  3096. });
  3097. var exhibit$4 = function (base, focusConfig) {
  3098. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3099. return nu$3(mod);
  3100. };
  3101. var events$7 = function (focusConfig) {
  3102. return derive$3([run(focus$4(), function (component, simulatedEvent) {
  3103. focus$2(component, focusConfig);
  3104. simulatedEvent.stop();
  3105. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3106. simulatedEvent.event.prevent();
  3107. })] : []));
  3108. };
  3109. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3110. __proto__: null,
  3111. exhibit: exhibit$4,
  3112. events: events$7
  3113. });
  3114. var FocusSchema = [
  3115. onHandler('onFocus'),
  3116. defaulted('stopMousedown', false),
  3117. defaulted('ignore', false)
  3118. ];
  3119. var Focusing = create$5({
  3120. fields: FocusSchema,
  3121. name: 'focusing',
  3122. active: ActiveFocus,
  3123. apis: FocusApis
  3124. });
  3125. var isSupported = function (dom) {
  3126. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  3127. };
  3128. var internalSet = function (dom, property, value) {
  3129. if (!isString(value)) {
  3130. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3131. throw new Error('CSS value must be a string: ' + value);
  3132. }
  3133. if (isSupported(dom)) {
  3134. dom.style.setProperty(property, value);
  3135. }
  3136. };
  3137. var internalRemove = function (dom, property) {
  3138. if (isSupported(dom)) {
  3139. dom.style.removeProperty(property);
  3140. }
  3141. };
  3142. var set$5 = function (element, property, value) {
  3143. var dom = element.dom;
  3144. internalSet(dom, property, value);
  3145. };
  3146. var setAll = function (element, css) {
  3147. var dom = element.dom;
  3148. each(css, function (v, k) {
  3149. internalSet(dom, k, v);
  3150. });
  3151. };
  3152. var get$8 = function (element, property) {
  3153. var dom = element.dom;
  3154. var styles = window.getComputedStyle(dom);
  3155. var r = styles.getPropertyValue(property);
  3156. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3157. };
  3158. var getUnsafeProperty = function (dom, property) {
  3159. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  3160. };
  3161. var getRaw = function (element, property) {
  3162. var dom = element.dom;
  3163. var raw = getUnsafeProperty(dom, property);
  3164. return Optional.from(raw).filter(function (r) {
  3165. return r.length > 0;
  3166. });
  3167. };
  3168. var remove$2 = function (element, property) {
  3169. var dom = element.dom;
  3170. internalRemove(dom, property);
  3171. if (is(getOpt(element, 'style').map(trim), '')) {
  3172. remove$6(element, 'style');
  3173. }
  3174. };
  3175. var reflow = function (e) {
  3176. return e.dom.offsetWidth;
  3177. };
  3178. var Dimension = function (name, getOffset) {
  3179. var set = function (element, h) {
  3180. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3181. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3182. }
  3183. var dom = element.dom;
  3184. if (isSupported(dom)) {
  3185. dom.style[name] = h + 'px';
  3186. }
  3187. };
  3188. var get = function (element) {
  3189. var r = getOffset(element);
  3190. if (r <= 0 || r === null) {
  3191. var css = get$8(element, name);
  3192. return parseFloat(css) || 0;
  3193. }
  3194. return r;
  3195. };
  3196. var getOuter = get;
  3197. var aggregate = function (element, properties) {
  3198. return foldl(properties, function (acc, property) {
  3199. var val = get$8(element, property);
  3200. var value = val === undefined ? 0 : parseInt(val, 10);
  3201. return isNaN(value) ? acc : acc + value;
  3202. }, 0);
  3203. };
  3204. var max = function (element, value, properties) {
  3205. var cumulativeInclusions = aggregate(element, properties);
  3206. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3207. return absoluteMax;
  3208. };
  3209. return {
  3210. set: set,
  3211. get: get,
  3212. getOuter: getOuter,
  3213. aggregate: aggregate,
  3214. max: max
  3215. };
  3216. };
  3217. var api$3 = Dimension('height', function (element) {
  3218. var dom = element.dom;
  3219. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3220. });
  3221. var get$7 = function (element) {
  3222. return api$3.get(element);
  3223. };
  3224. var ancestors$1 = function (scope, predicate, isRoot) {
  3225. return filter$2(parents(scope, isRoot), predicate);
  3226. };
  3227. var siblings$1 = function (scope, predicate) {
  3228. return filter$2(siblings$2(scope), predicate);
  3229. };
  3230. var all = function (selector) {
  3231. return all$2(selector);
  3232. };
  3233. var ancestors = function (scope, selector, isRoot) {
  3234. return ancestors$1(scope, function (e) {
  3235. return is$1(e, selector);
  3236. }, isRoot);
  3237. };
  3238. var siblings = function (scope, selector) {
  3239. return siblings$1(scope, function (e) {
  3240. return is$1(e, selector);
  3241. });
  3242. };
  3243. var descendants = function (scope, selector) {
  3244. return all$2(selector, scope);
  3245. };
  3246. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3247. if (is(scope, a)) {
  3248. return Optional.some(scope);
  3249. } else if (isFunction(isRoot) && isRoot(scope)) {
  3250. return Optional.none();
  3251. } else {
  3252. return ancestor(scope, a, isRoot);
  3253. }
  3254. }
  3255. var ancestor$1 = function (scope, predicate, isRoot) {
  3256. var element = scope.dom;
  3257. var stop = isFunction(isRoot) ? isRoot : never;
  3258. while (element.parentNode) {
  3259. element = element.parentNode;
  3260. var el = SugarElement.fromDom(element);
  3261. if (predicate(el)) {
  3262. return Optional.some(el);
  3263. } else if (stop(el)) {
  3264. break;
  3265. }
  3266. }
  3267. return Optional.none();
  3268. };
  3269. var closest$2 = function (scope, predicate, isRoot) {
  3270. var is = function (s, test) {
  3271. return test(s);
  3272. };
  3273. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3274. };
  3275. var descendant$1 = function (scope, predicate) {
  3276. var descend = function (node) {
  3277. for (var i = 0; i < node.childNodes.length; i++) {
  3278. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3279. if (predicate(child_1)) {
  3280. return Optional.some(child_1);
  3281. }
  3282. var res = descend(node.childNodes[i]);
  3283. if (res.isSome()) {
  3284. return res;
  3285. }
  3286. }
  3287. return Optional.none();
  3288. };
  3289. return descend(scope.dom);
  3290. };
  3291. var first$1 = function (selector) {
  3292. return one(selector);
  3293. };
  3294. var ancestor = function (scope, selector, isRoot) {
  3295. return ancestor$1(scope, function (e) {
  3296. return is$1(e, selector);
  3297. }, isRoot);
  3298. };
  3299. var descendant = function (scope, selector) {
  3300. return one(selector, scope);
  3301. };
  3302. var closest$1 = function (scope, selector, isRoot) {
  3303. var is = function (element, selector) {
  3304. return is$1(element, selector);
  3305. };
  3306. return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
  3307. };
  3308. var BACKSPACE = [8];
  3309. var TAB = [9];
  3310. var ENTER = [13];
  3311. var ESCAPE = [27];
  3312. var SPACE = [32];
  3313. var LEFT = [37];
  3314. var UP = [38];
  3315. var RIGHT = [39];
  3316. var DOWN = [40];
  3317. var cyclePrev = function (values, index, predicate) {
  3318. var before = reverse(values.slice(0, index));
  3319. var after = reverse(values.slice(index + 1));
  3320. return find$2(before.concat(after), predicate);
  3321. };
  3322. var tryPrev = function (values, index, predicate) {
  3323. var before = reverse(values.slice(0, index));
  3324. return find$2(before, predicate);
  3325. };
  3326. var cycleNext = function (values, index, predicate) {
  3327. var before = values.slice(0, index);
  3328. var after = values.slice(index + 1);
  3329. return find$2(after.concat(before), predicate);
  3330. };
  3331. var tryNext = function (values, index, predicate) {
  3332. var after = values.slice(index + 1);
  3333. return find$2(after, predicate);
  3334. };
  3335. var inSet = function (keys) {
  3336. return function (event) {
  3337. var raw = event.raw;
  3338. return contains$1(keys, raw.which);
  3339. };
  3340. };
  3341. var and = function (preds) {
  3342. return function (event) {
  3343. return forall(preds, function (pred) {
  3344. return pred(event);
  3345. });
  3346. };
  3347. };
  3348. var isShift = function (event) {
  3349. var raw = event.raw;
  3350. return raw.shiftKey === true;
  3351. };
  3352. var isControl = function (event) {
  3353. var raw = event.raw;
  3354. return raw.ctrlKey === true;
  3355. };
  3356. var isNotShift = not(isShift);
  3357. var rule = function (matches, action) {
  3358. return {
  3359. matches: matches,
  3360. classification: action
  3361. };
  3362. };
  3363. var choose = function (transitions, event) {
  3364. var transition = find$2(transitions, function (t) {
  3365. return t.matches(event);
  3366. });
  3367. return transition.map(function (t) {
  3368. return t.classification;
  3369. });
  3370. };
  3371. var cycleBy = function (value, delta, min, max) {
  3372. var r = value + delta;
  3373. if (r > max) {
  3374. return min;
  3375. } else if (r < min) {
  3376. return max;
  3377. } else {
  3378. return r;
  3379. }
  3380. };
  3381. var clamp = function (value, min, max) {
  3382. return Math.min(Math.max(value, min), max);
  3383. };
  3384. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3385. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  3386. each$1(highlighted, function (h) {
  3387. if (!exists(skip, function (skipComp) {
  3388. return skipComp.element === h;
  3389. })) {
  3390. remove$3(h, hConfig.highlightClass);
  3391. component.getSystem().getByDom(h).each(function (target) {
  3392. hConfig.onDehighlight(component, target);
  3393. emit(target, dehighlight$1());
  3394. });
  3395. }
  3396. });
  3397. };
  3398. var dehighlightAll = function (component, hConfig, hState) {
  3399. return dehighlightAllExcept(component, hConfig, hState, []);
  3400. };
  3401. var dehighlight = function (component, hConfig, hState, target) {
  3402. if (isHighlighted(component, hConfig, hState, target)) {
  3403. remove$3(target.element, hConfig.highlightClass);
  3404. hConfig.onDehighlight(component, target);
  3405. emit(target, dehighlight$1());
  3406. }
  3407. };
  3408. var highlight = function (component, hConfig, hState, target) {
  3409. dehighlightAllExcept(component, hConfig, hState, [target]);
  3410. if (!isHighlighted(component, hConfig, hState, target)) {
  3411. add$1(target.element, hConfig.highlightClass);
  3412. hConfig.onHighlight(component, target);
  3413. emit(target, highlight$1());
  3414. }
  3415. };
  3416. var highlightFirst = function (component, hConfig, hState) {
  3417. getFirst(component, hConfig).each(function (firstComp) {
  3418. highlight(component, hConfig, hState, firstComp);
  3419. });
  3420. };
  3421. var highlightLast = function (component, hConfig, hState) {
  3422. getLast(component, hConfig).each(function (lastComp) {
  3423. highlight(component, hConfig, hState, lastComp);
  3424. });
  3425. };
  3426. var highlightAt = function (component, hConfig, hState, index) {
  3427. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3428. throw err;
  3429. }, function (firstComp) {
  3430. highlight(component, hConfig, hState, firstComp);
  3431. });
  3432. };
  3433. var highlightBy = function (component, hConfig, hState, predicate) {
  3434. var candidates = getCandidates(component, hConfig);
  3435. var targetComp = find$2(candidates, predicate);
  3436. targetComp.each(function (c) {
  3437. highlight(component, hConfig, hState, c);
  3438. });
  3439. };
  3440. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3441. return has(queryTarget.element, hConfig.highlightClass);
  3442. };
  3443. var getHighlighted = function (component, hConfig, _hState) {
  3444. return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  3445. return component.getSystem().getByDom(e).toOptional();
  3446. });
  3447. };
  3448. var getByIndex = function (component, hConfig, hState, index) {
  3449. var items = descendants(component.element, '.' + hConfig.itemClass);
  3450. return Optional.from(items[index]).fold(function () {
  3451. return Result.error(new Error('No element found with index ' + index));
  3452. }, component.getSystem().getByDom);
  3453. };
  3454. var getFirst = function (component, hConfig, _hState) {
  3455. return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) {
  3456. return component.getSystem().getByDom(e).toOptional();
  3457. });
  3458. };
  3459. var getLast = function (component, hConfig, _hState) {
  3460. var items = descendants(component.element, '.' + hConfig.itemClass);
  3461. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  3462. return last.bind(function (c) {
  3463. return component.getSystem().getByDom(c).toOptional();
  3464. });
  3465. };
  3466. var getDelta = function (component, hConfig, hState, delta) {
  3467. var items = descendants(component.element, '.' + hConfig.itemClass);
  3468. var current = findIndex$1(items, function (item) {
  3469. return has(item, hConfig.highlightClass);
  3470. });
  3471. return current.bind(function (selected) {
  3472. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3473. return component.getSystem().getByDom(items[dest]).toOptional();
  3474. });
  3475. };
  3476. var getPrevious = function (component, hConfig, hState) {
  3477. return getDelta(component, hConfig, hState, -1);
  3478. };
  3479. var getNext = function (component, hConfig, hState) {
  3480. return getDelta(component, hConfig, hState, +1);
  3481. };
  3482. var getCandidates = function (component, hConfig, _hState) {
  3483. var items = descendants(component.element, '.' + hConfig.itemClass);
  3484. return cat(map$2(items, function (i) {
  3485. return component.getSystem().getByDom(i).toOptional();
  3486. }));
  3487. };
  3488. var HighlightApis = /*#__PURE__*/Object.freeze({
  3489. __proto__: null,
  3490. dehighlightAll: dehighlightAll,
  3491. dehighlight: dehighlight,
  3492. highlight: highlight,
  3493. highlightFirst: highlightFirst,
  3494. highlightLast: highlightLast,
  3495. highlightAt: highlightAt,
  3496. highlightBy: highlightBy,
  3497. isHighlighted: isHighlighted,
  3498. getHighlighted: getHighlighted,
  3499. getFirst: getFirst,
  3500. getLast: getLast,
  3501. getPrevious: getPrevious,
  3502. getNext: getNext,
  3503. getCandidates: getCandidates
  3504. });
  3505. var HighlightSchema = [
  3506. required$1('highlightClass'),
  3507. required$1('itemClass'),
  3508. onHandler('onHighlight'),
  3509. onHandler('onDehighlight')
  3510. ];
  3511. var Highlighting = create$5({
  3512. fields: HighlightSchema,
  3513. name: 'highlighting',
  3514. apis: HighlightApis
  3515. });
  3516. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3517. var noChange = prevFocus.exists(function (p) {
  3518. return newFocus.exists(function (n) {
  3519. return eq(n, p);
  3520. });
  3521. });
  3522. if (!noChange) {
  3523. emitWith(component, focusShifted(), {
  3524. prevFocus: prevFocus,
  3525. newFocus: newFocus
  3526. });
  3527. }
  3528. };
  3529. var dom$2 = function () {
  3530. var get = function (component) {
  3531. return search(component.element);
  3532. };
  3533. var set = function (component, focusee) {
  3534. var prevFocus = get(component);
  3535. component.getSystem().triggerFocus(focusee, component.element);
  3536. var newFocus = get(component);
  3537. reportFocusShifting(component, prevFocus, newFocus);
  3538. };
  3539. return {
  3540. get: get,
  3541. set: set
  3542. };
  3543. };
  3544. var highlights = function () {
  3545. var get = function (component) {
  3546. return Highlighting.getHighlighted(component).map(function (item) {
  3547. return item.element;
  3548. });
  3549. };
  3550. var set = function (component, element) {
  3551. var prevFocus = get(component);
  3552. component.getSystem().getByDom(element).fold(noop, function (item) {
  3553. Highlighting.highlight(component, item);
  3554. });
  3555. var newFocus = get(component);
  3556. reportFocusShifting(component, prevFocus, newFocus);
  3557. };
  3558. return {
  3559. get: get,
  3560. set: set
  3561. };
  3562. };
  3563. var FocusInsideModes;
  3564. (function (FocusInsideModes) {
  3565. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3566. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3567. FocusInsideModes['OnApiMode'] = 'onApi';
  3568. }(FocusInsideModes || (FocusInsideModes = {})));
  3569. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3570. var schema = function () {
  3571. return infoSchema.concat([
  3572. defaulted('focusManager', dom$2()),
  3573. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3574. return contains$1([
  3575. 'onFocus',
  3576. 'onEnterOrSpace',
  3577. 'onApi'
  3578. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3579. })),
  3580. output('handler', me),
  3581. output('state', stateInit),
  3582. output('sendFocusIn', optFocusIn)
  3583. ]);
  3584. };
  3585. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3586. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3587. return choose(rules, simulatedEvent.event).bind(function (rule) {
  3588. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3589. });
  3590. };
  3591. var toEvents = function (keyingConfig, keyingState) {
  3592. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3593. return run(focus$4(), function (component, simulatedEvent) {
  3594. focusIn(component, keyingConfig, keyingState);
  3595. simulatedEvent.stop();
  3596. });
  3597. });
  3598. var tryGoInsideComponent = function (component, simulatedEvent) {
  3599. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  3600. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3601. optFocusIn(keyingConfig).each(function (focusIn) {
  3602. focusIn(component, keyingConfig, keyingState);
  3603. simulatedEvent.stop();
  3604. });
  3605. }
  3606. };
  3607. var keyboardEvents = [
  3608. run(keydown(), function (component, simulatedEvent) {
  3609. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3610. tryGoInsideComponent(component, simulatedEvent);
  3611. }, function (_) {
  3612. simulatedEvent.stop();
  3613. });
  3614. }),
  3615. run(keyup(), function (component, simulatedEvent) {
  3616. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3617. simulatedEvent.stop();
  3618. });
  3619. })
  3620. ];
  3621. return derive$3(onFocusHandler.toArray().concat(keyboardEvents));
  3622. };
  3623. var me = {
  3624. schema: schema,
  3625. processKey: processKey,
  3626. toEvents: toEvents
  3627. };
  3628. return me;
  3629. };
  3630. var create$4 = function (cyclicField) {
  3631. var schema = [
  3632. option('onEscape'),
  3633. option('onEnter'),
  3634. defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3635. defaulted('firstTabstop', 0),
  3636. defaulted('useTabstopAt', always),
  3637. option('visibilitySelector')
  3638. ].concat([cyclicField]);
  3639. var isVisible = function (tabbingConfig, element) {
  3640. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3641. return closest$1(element, sel);
  3642. }).getOr(element);
  3643. return get$7(target) > 0;
  3644. };
  3645. var findInitial = function (component, tabbingConfig) {
  3646. var tabstops = descendants(component.element, tabbingConfig.selector);
  3647. var visibles = filter$2(tabstops, function (elem) {
  3648. return isVisible(tabbingConfig, elem);
  3649. });
  3650. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  3651. };
  3652. var findCurrent = function (component, tabbingConfig) {
  3653. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3654. return closest$1(elem, tabbingConfig.selector);
  3655. });
  3656. };
  3657. var isTabstop = function (tabbingConfig, element) {
  3658. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3659. };
  3660. var focusIn = function (component, tabbingConfig, _tabbingState) {
  3661. findInitial(component, tabbingConfig).each(function (target) {
  3662. tabbingConfig.focusManager.set(component, target);
  3663. });
  3664. };
  3665. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3666. return cycle(tabstops, stopIndex, function (elem) {
  3667. return isTabstop(tabbingConfig, elem);
  3668. }).fold(function () {
  3669. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  3670. }, function (target) {
  3671. tabbingConfig.focusManager.set(component, target);
  3672. return Optional.some(true);
  3673. });
  3674. };
  3675. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  3676. var tabstops = descendants(component.element, tabbingConfig.selector);
  3677. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3678. var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  3679. return optStopIndex.bind(function (stopIndex) {
  3680. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3681. });
  3682. });
  3683. };
  3684. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  3685. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3686. return go(component, simulatedEvent, tabbingConfig, navigate);
  3687. };
  3688. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  3689. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3690. return go(component, simulatedEvent, tabbingConfig, navigate);
  3691. };
  3692. var execute = function (component, simulatedEvent, tabbingConfig) {
  3693. return tabbingConfig.onEnter.bind(function (f) {
  3694. return f(component, simulatedEvent);
  3695. });
  3696. };
  3697. var exit = function (component, simulatedEvent, tabbingConfig) {
  3698. return tabbingConfig.onEscape.bind(function (f) {
  3699. return f(component, simulatedEvent);
  3700. });
  3701. };
  3702. var getKeydownRules = constant$1([
  3703. rule(and([
  3704. isShift,
  3705. inSet(TAB)
  3706. ]), goBackwards),
  3707. rule(inSet(TAB), goForwards),
  3708. rule(inSet(ESCAPE), exit),
  3709. rule(and([
  3710. isNotShift,
  3711. inSet(ENTER)
  3712. ]), execute)
  3713. ]);
  3714. var getKeyupRules = constant$1([]);
  3715. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3716. return Optional.some(focusIn);
  3717. });
  3718. };
  3719. var AcyclicType = create$4(customField('cyclic', never));
  3720. var CyclicType = create$4(customField('cyclic', always));
  3721. var inside = function (target) {
  3722. return name$1(target) === 'input' && get$b(target, 'type') !== 'radio' || name$1(target) === 'textarea';
  3723. };
  3724. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  3725. dispatch(component, focused, execute$5());
  3726. return Optional.some(true);
  3727. };
  3728. var defaultExecute = function (component, simulatedEvent, focused) {
  3729. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  3730. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  3731. };
  3732. var stopEventForFirefox = function (_component, _simulatedEvent) {
  3733. return Optional.some(true);
  3734. };
  3735. var schema$f = [
  3736. defaulted('execute', defaultExecute),
  3737. defaulted('useSpace', false),
  3738. defaulted('useEnter', true),
  3739. defaulted('useControlEnter', false),
  3740. defaulted('useDown', false)
  3741. ];
  3742. var execute$4 = function (component, simulatedEvent, executeConfig) {
  3743. return executeConfig.execute(component, simulatedEvent, component.element);
  3744. };
  3745. var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  3746. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  3747. var enterExec = executeConfig.useEnter ? ENTER : [];
  3748. var downExec = executeConfig.useDown ? DOWN : [];
  3749. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3750. return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  3751. isControl,
  3752. inSet(ENTER)
  3753. ]), execute$4)] : []);
  3754. };
  3755. var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  3756. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  3757. };
  3758. var ExecutionType = typical(schema$f, NoState.init, getKeydownRules$5, getKeyupRules$5, function () {
  3759. return Optional.none();
  3760. });
  3761. var singleton$1 = function (doRevoke) {
  3762. var subject = Cell(Optional.none());
  3763. var revoke = function () {
  3764. return subject.get().each(doRevoke);
  3765. };
  3766. var clear = function () {
  3767. revoke();
  3768. subject.set(Optional.none());
  3769. };
  3770. var isSet = function () {
  3771. return subject.get().isSome();
  3772. };
  3773. var get = function () {
  3774. return subject.get();
  3775. };
  3776. var set = function (s) {
  3777. revoke();
  3778. subject.set(Optional.some(s));
  3779. };
  3780. return {
  3781. clear: clear,
  3782. isSet: isSet,
  3783. get: get,
  3784. set: set
  3785. };
  3786. };
  3787. var destroyable = function () {
  3788. return singleton$1(function (s) {
  3789. return s.destroy();
  3790. });
  3791. };
  3792. var api$2 = function () {
  3793. var subject = destroyable();
  3794. var run = function (f) {
  3795. return subject.get().each(f);
  3796. };
  3797. return __assign(__assign({}, subject), { run: run });
  3798. };
  3799. var value = function () {
  3800. var subject = singleton$1(noop);
  3801. var on = function (f) {
  3802. return subject.get().each(f);
  3803. };
  3804. return __assign(__assign({}, subject), { on: on });
  3805. };
  3806. var flatgrid$1 = function () {
  3807. var dimensions = value();
  3808. var setGridSize = function (numRows, numColumns) {
  3809. dimensions.set({
  3810. numRows: numRows,
  3811. numColumns: numColumns
  3812. });
  3813. };
  3814. var getNumRows = function () {
  3815. return dimensions.get().map(function (d) {
  3816. return d.numRows;
  3817. });
  3818. };
  3819. var getNumColumns = function () {
  3820. return dimensions.get().map(function (d) {
  3821. return d.numColumns;
  3822. });
  3823. };
  3824. return nu$2({
  3825. readState: function () {
  3826. return dimensions.get().map(function (d) {
  3827. return {
  3828. numRows: String(d.numRows),
  3829. numColumns: String(d.numColumns)
  3830. };
  3831. }).getOr({
  3832. numRows: '?',
  3833. numColumns: '?'
  3834. });
  3835. },
  3836. setGridSize: setGridSize,
  3837. getNumRows: getNumRows,
  3838. getNumColumns: getNumColumns
  3839. });
  3840. };
  3841. var init$5 = function (spec) {
  3842. return spec.state(spec);
  3843. };
  3844. var KeyingState = /*#__PURE__*/Object.freeze({
  3845. __proto__: null,
  3846. flatgrid: flatgrid$1,
  3847. init: init$5
  3848. });
  3849. var onDirection = function (isLtr, isRtl) {
  3850. return function (element) {
  3851. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3852. };
  3853. };
  3854. var getDirection = function (element) {
  3855. return get$8(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3856. };
  3857. var useH = function (movement) {
  3858. return function (component, simulatedEvent, config, state) {
  3859. var move = movement(component.element);
  3860. return use(move, component, simulatedEvent, config, state);
  3861. };
  3862. };
  3863. var west = function (moveLeft, moveRight) {
  3864. var movement = onDirection(moveLeft, moveRight);
  3865. return useH(movement);
  3866. };
  3867. var east = function (moveLeft, moveRight) {
  3868. var movement = onDirection(moveRight, moveLeft);
  3869. return useH(movement);
  3870. };
  3871. var useV = function (move) {
  3872. return function (component, simulatedEvent, config, state) {
  3873. return use(move, component, simulatedEvent, config, state);
  3874. };
  3875. };
  3876. var use = function (move, component, simulatedEvent, config, state) {
  3877. var outcome = config.focusManager.get(component).bind(function (focused) {
  3878. return move(component.element, focused, config, state);
  3879. });
  3880. return outcome.map(function (newFocus) {
  3881. config.focusManager.set(component, newFocus);
  3882. return true;
  3883. });
  3884. };
  3885. var north = useV;
  3886. var south = useV;
  3887. var move$1 = useV;
  3888. var isHidden = function (dom) {
  3889. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3890. };
  3891. var isVisible = function (element) {
  3892. return !isHidden(element.dom);
  3893. };
  3894. var locate = function (candidates, predicate) {
  3895. return findIndex$1(candidates, predicate).map(function (index) {
  3896. return {
  3897. index: index,
  3898. candidates: candidates
  3899. };
  3900. });
  3901. };
  3902. var locateVisible = function (container, current, selector) {
  3903. var predicate = function (x) {
  3904. return eq(x, current);
  3905. };
  3906. var candidates = descendants(container, selector);
  3907. var visible = filter$2(candidates, isVisible);
  3908. return locate(visible, predicate);
  3909. };
  3910. var findIndex = function (elements, target) {
  3911. return findIndex$1(elements, function (elem) {
  3912. return eq(target, elem);
  3913. });
  3914. };
  3915. var withGrid = function (values, index, numCols, f) {
  3916. var oldRow = Math.floor(index / numCols);
  3917. var oldColumn = index % numCols;
  3918. return f(oldRow, oldColumn).bind(function (address) {
  3919. var newIndex = address.row * numCols + address.column;
  3920. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  3921. });
  3922. };
  3923. var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) {
  3924. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3925. var onLastRow = oldRow === numRows - 1;
  3926. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3927. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3928. return Optional.some({
  3929. row: oldRow,
  3930. column: newColumn
  3931. });
  3932. });
  3933. };
  3934. var cycleVertical$1 = function (values, index, numRows, numCols, delta) {
  3935. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3936. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3937. var onLastRow = newRow === numRows - 1;
  3938. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3939. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  3940. return Optional.some({
  3941. row: newRow,
  3942. column: newCol
  3943. });
  3944. });
  3945. };
  3946. var cycleRight$1 = function (values, index, numRows, numCols) {
  3947. return cycleHorizontal$1(values, index, numRows, numCols, +1);
  3948. };
  3949. var cycleLeft$1 = function (values, index, numRows, numCols) {
  3950. return cycleHorizontal$1(values, index, numRows, numCols, -1);
  3951. };
  3952. var cycleUp$1 = function (values, index, numRows, numCols) {
  3953. return cycleVertical$1(values, index, numRows, numCols, -1);
  3954. };
  3955. var cycleDown$1 = function (values, index, numRows, numCols) {
  3956. return cycleVertical$1(values, index, numRows, numCols, +1);
  3957. };
  3958. var schema$e = [
  3959. required$1('selector'),
  3960. defaulted('execute', defaultExecute),
  3961. onKeyboardHandler('onEscape'),
  3962. defaulted('captureTab', false),
  3963. initSize()
  3964. ];
  3965. var focusIn$3 = function (component, gridConfig, _gridState) {
  3966. descendant(component.element, gridConfig.selector).each(function (first) {
  3967. gridConfig.focusManager.set(component, first);
  3968. });
  3969. };
  3970. var findCurrent$1 = function (component, gridConfig) {
  3971. return gridConfig.focusManager.get(component).bind(function (elem) {
  3972. return closest$1(elem, gridConfig.selector);
  3973. });
  3974. };
  3975. var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) {
  3976. return findCurrent$1(component, gridConfig).bind(function (focused) {
  3977. return gridConfig.execute(component, simulatedEvent, focused);
  3978. });
  3979. };
  3980. var doMove$2 = function (cycle) {
  3981. return function (element, focused, gridConfig, gridState) {
  3982. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3983. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3984. });
  3985. };
  3986. };
  3987. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  3988. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  3989. };
  3990. var doEscape$1 = function (component, simulatedEvent, gridConfig) {
  3991. return gridConfig.onEscape(component, simulatedEvent);
  3992. };
  3993. var moveLeft$3 = doMove$2(cycleLeft$1);
  3994. var moveRight$3 = doMove$2(cycleRight$1);
  3995. var moveNorth$1 = doMove$2(cycleUp$1);
  3996. var moveSouth$1 = doMove$2(cycleDown$1);
  3997. var getKeydownRules$4 = constant$1([
  3998. rule(inSet(LEFT), west(moveLeft$3, moveRight$3)),
  3999. rule(inSet(RIGHT), east(moveLeft$3, moveRight$3)),
  4000. rule(inSet(UP), north(moveNorth$1)),
  4001. rule(inSet(DOWN), south(moveSouth$1)),
  4002. rule(and([
  4003. isShift,
  4004. inSet(TAB)
  4005. ]), handleTab),
  4006. rule(and([
  4007. isNotShift,
  4008. inSet(TAB)
  4009. ]), handleTab),
  4010. rule(inSet(ESCAPE), doEscape$1),
  4011. rule(inSet(SPACE.concat(ENTER)), execute$3)
  4012. ]);
  4013. var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4014. var FlatgridType = typical(schema$e, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () {
  4015. return Optional.some(focusIn$3);
  4016. });
  4017. var horizontal = function (container, selector, current, delta) {
  4018. var isDisabledButton = function (candidate) {
  4019. return name$1(candidate) === 'button' && get$b(candidate, 'disabled') === 'disabled';
  4020. };
  4021. var tryCycle = function (initial, index, candidates) {
  4022. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  4023. if (newIndex === initial) {
  4024. return Optional.none();
  4025. } else {
  4026. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  4027. }
  4028. };
  4029. return locateVisible(container, current, selector).bind(function (identified) {
  4030. var index = identified.index;
  4031. var candidates = identified.candidates;
  4032. return tryCycle(index, index, candidates);
  4033. });
  4034. };
  4035. var schema$d = [
  4036. required$1('selector'),
  4037. defaulted('getInitial', Optional.none),
  4038. defaulted('execute', defaultExecute),
  4039. onKeyboardHandler('onEscape'),
  4040. defaulted('executeOnMove', false),
  4041. defaulted('allowVertical', true)
  4042. ];
  4043. var findCurrent = function (component, flowConfig) {
  4044. return flowConfig.focusManager.get(component).bind(function (elem) {
  4045. return closest$1(elem, flowConfig.selector);
  4046. });
  4047. };
  4048. var execute$2 = function (component, simulatedEvent, flowConfig) {
  4049. return findCurrent(component, flowConfig).bind(function (focused) {
  4050. return flowConfig.execute(component, simulatedEvent, focused);
  4051. });
  4052. };
  4053. var focusIn$2 = function (component, flowConfig, _state) {
  4054. flowConfig.getInitial(component).orThunk(function () {
  4055. return descendant(component.element, flowConfig.selector);
  4056. }).each(function (first) {
  4057. flowConfig.focusManager.set(component, first);
  4058. });
  4059. };
  4060. var moveLeft$2 = function (element, focused, info) {
  4061. return horizontal(element, info.selector, focused, -1);
  4062. };
  4063. var moveRight$2 = function (element, focused, info) {
  4064. return horizontal(element, info.selector, focused, +1);
  4065. };
  4066. var doMove$1 = function (movement) {
  4067. return function (component, simulatedEvent, flowConfig, flowState) {
  4068. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  4069. return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
  4070. });
  4071. };
  4072. };
  4073. var doEscape = function (component, simulatedEvent, flowConfig) {
  4074. return flowConfig.onEscape(component, simulatedEvent);
  4075. };
  4076. var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) {
  4077. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  4078. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  4079. return [
  4080. rule(inSet(westMovers), doMove$1(west(moveLeft$2, moveRight$2))),
  4081. rule(inSet(eastMovers), doMove$1(east(moveLeft$2, moveRight$2))),
  4082. rule(inSet(ENTER), execute$2),
  4083. rule(inSet(SPACE), execute$2),
  4084. rule(inSet(ESCAPE), doEscape)
  4085. ];
  4086. };
  4087. var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4088. var FlowType = typical(schema$d, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4089. return Optional.some(focusIn$2);
  4090. });
  4091. var toCell = function (matrix, rowIndex, columnIndex) {
  4092. return Optional.from(matrix[rowIndex]).bind(function (row) {
  4093. return Optional.from(row[columnIndex]).map(function (cell) {
  4094. return {
  4095. rowIndex: rowIndex,
  4096. columnIndex: columnIndex,
  4097. cell: cell
  4098. };
  4099. });
  4100. });
  4101. };
  4102. var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4103. var row = matrix[rowIndex];
  4104. var colsInRow = row.length;
  4105. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  4106. return toCell(matrix, rowIndex, newColIndex);
  4107. };
  4108. var cycleVertical = function (matrix, colIndex, startRow, deltaRow) {
  4109. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  4110. var colsInNextRow = matrix[nextRowIndex].length;
  4111. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4112. return toCell(matrix, nextRowIndex, nextColIndex);
  4113. };
  4114. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4115. var row = matrix[rowIndex];
  4116. var colsInRow = row.length;
  4117. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  4118. return toCell(matrix, rowIndex, newColIndex);
  4119. };
  4120. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  4121. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  4122. var colsInNextRow = matrix[nextRowIndex].length;
  4123. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4124. return toCell(matrix, nextRowIndex, nextColIndex);
  4125. };
  4126. var cycleRight = function (matrix, startRow, startCol) {
  4127. return cycleHorizontal(matrix, startRow, startCol, +1);
  4128. };
  4129. var cycleLeft = function (matrix, startRow, startCol) {
  4130. return cycleHorizontal(matrix, startRow, startCol, -1);
  4131. };
  4132. var cycleUp = function (matrix, startRow, startCol) {
  4133. return cycleVertical(matrix, startCol, startRow, -1);
  4134. };
  4135. var cycleDown = function (matrix, startRow, startCol) {
  4136. return cycleVertical(matrix, startCol, startRow, +1);
  4137. };
  4138. var moveLeft$1 = function (matrix, startRow, startCol) {
  4139. return moveHorizontal(matrix, startRow, startCol, -1);
  4140. };
  4141. var moveRight$1 = function (matrix, startRow, startCol) {
  4142. return moveHorizontal(matrix, startRow, startCol, +1);
  4143. };
  4144. var moveUp$1 = function (matrix, startRow, startCol) {
  4145. return moveVertical(matrix, startCol, startRow, -1);
  4146. };
  4147. var moveDown$1 = function (matrix, startRow, startCol) {
  4148. return moveVertical(matrix, startCol, startRow, +1);
  4149. };
  4150. var schema$c = [
  4151. requiredObjOf('selectors', [
  4152. required$1('row'),
  4153. required$1('cell')
  4154. ]),
  4155. defaulted('cycles', true),
  4156. defaulted('previousSelector', Optional.none),
  4157. defaulted('execute', defaultExecute)
  4158. ];
  4159. var focusIn$1 = function (component, matrixConfig, _state) {
  4160. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4161. var selectors = matrixConfig.selectors;
  4162. return descendant(component.element, selectors.cell);
  4163. });
  4164. focused.each(function (cell) {
  4165. matrixConfig.focusManager.set(component, cell);
  4166. });
  4167. };
  4168. var execute$1 = function (component, simulatedEvent, matrixConfig) {
  4169. return search(component.element).bind(function (focused) {
  4170. return matrixConfig.execute(component, simulatedEvent, focused);
  4171. });
  4172. };
  4173. var toMatrix = function (rows, matrixConfig) {
  4174. return map$2(rows, function (row) {
  4175. return descendants(row, matrixConfig.selectors.cell);
  4176. });
  4177. };
  4178. var doMove = function (ifCycle, ifMove) {
  4179. return function (element, focused, matrixConfig) {
  4180. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4181. return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4182. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4183. return findIndex(cellsInRow, focused).bind(function (colIndex) {
  4184. var allRows = descendants(element, matrixConfig.selectors.row);
  4185. return findIndex(allRows, inRow).bind(function (rowIndex) {
  4186. var matrix = toMatrix(allRows, matrixConfig);
  4187. return move(matrix, rowIndex, colIndex).map(function (next) {
  4188. return next.cell;
  4189. });
  4190. });
  4191. });
  4192. });
  4193. };
  4194. };
  4195. var moveLeft = doMove(cycleLeft, moveLeft$1);
  4196. var moveRight = doMove(cycleRight, moveRight$1);
  4197. var moveNorth = doMove(cycleUp, moveUp$1);
  4198. var moveSouth = doMove(cycleDown, moveDown$1);
  4199. var getKeydownRules$2 = constant$1([
  4200. rule(inSet(LEFT), west(moveLeft, moveRight)),
  4201. rule(inSet(RIGHT), east(moveLeft, moveRight)),
  4202. rule(inSet(UP), north(moveNorth)),
  4203. rule(inSet(DOWN), south(moveSouth)),
  4204. rule(inSet(SPACE.concat(ENTER)), execute$1)
  4205. ]);
  4206. var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4207. var MatrixType = typical(schema$c, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  4208. return Optional.some(focusIn$1);
  4209. });
  4210. var schema$b = [
  4211. required$1('selector'),
  4212. defaulted('execute', defaultExecute),
  4213. defaulted('moveOnTab', false)
  4214. ];
  4215. var execute = function (component, simulatedEvent, menuConfig) {
  4216. return menuConfig.focusManager.get(component).bind(function (focused) {
  4217. return menuConfig.execute(component, simulatedEvent, focused);
  4218. });
  4219. };
  4220. var focusIn = function (component, menuConfig, _state) {
  4221. descendant(component.element, menuConfig.selector).each(function (first) {
  4222. menuConfig.focusManager.set(component, first);
  4223. });
  4224. };
  4225. var moveUp = function (element, focused, info) {
  4226. return horizontal(element, info.selector, focused, -1);
  4227. };
  4228. var moveDown = function (element, focused, info) {
  4229. return horizontal(element, info.selector, focused, +1);
  4230. };
  4231. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  4232. return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4233. };
  4234. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  4235. return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4236. };
  4237. var getKeydownRules$1 = constant$1([
  4238. rule(inSet(UP), move$1(moveUp)),
  4239. rule(inSet(DOWN), move$1(moveDown)),
  4240. rule(and([
  4241. isShift,
  4242. inSet(TAB)
  4243. ]), fireShiftTab),
  4244. rule(and([
  4245. isNotShift,
  4246. inSet(TAB)
  4247. ]), fireTab),
  4248. rule(inSet(ENTER), execute),
  4249. rule(inSet(SPACE), execute)
  4250. ]);
  4251. var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4252. var MenuType = typical(schema$b, NoState.init, getKeydownRules$1, getKeyupRules$1, function () {
  4253. return Optional.some(focusIn);
  4254. });
  4255. var schema$a = [
  4256. onKeyboardHandler('onSpace'),
  4257. onKeyboardHandler('onEnter'),
  4258. onKeyboardHandler('onShiftEnter'),
  4259. onKeyboardHandler('onLeft'),
  4260. onKeyboardHandler('onRight'),
  4261. onKeyboardHandler('onTab'),
  4262. onKeyboardHandler('onShiftTab'),
  4263. onKeyboardHandler('onUp'),
  4264. onKeyboardHandler('onDown'),
  4265. onKeyboardHandler('onEscape'),
  4266. defaulted('stopSpaceKeyup', false),
  4267. option('focusIn')
  4268. ];
  4269. var getKeydownRules = function (component, simulatedEvent, specialInfo) {
  4270. return [
  4271. rule(inSet(SPACE), specialInfo.onSpace),
  4272. rule(and([
  4273. isNotShift,
  4274. inSet(ENTER)
  4275. ]), specialInfo.onEnter),
  4276. rule(and([
  4277. isShift,
  4278. inSet(ENTER)
  4279. ]), specialInfo.onShiftEnter),
  4280. rule(and([
  4281. isShift,
  4282. inSet(TAB)
  4283. ]), specialInfo.onShiftTab),
  4284. rule(and([
  4285. isNotShift,
  4286. inSet(TAB)
  4287. ]), specialInfo.onTab),
  4288. rule(inSet(UP), specialInfo.onUp),
  4289. rule(inSet(DOWN), specialInfo.onDown),
  4290. rule(inSet(LEFT), specialInfo.onLeft),
  4291. rule(inSet(RIGHT), specialInfo.onRight),
  4292. rule(inSet(SPACE), specialInfo.onSpace),
  4293. rule(inSet(ESCAPE), specialInfo.onEscape)
  4294. ];
  4295. };
  4296. var getKeyupRules = function (component, simulatedEvent, specialInfo) {
  4297. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  4298. };
  4299. var SpecialType = typical(schema$a, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) {
  4300. return specialInfo.focusIn;
  4301. });
  4302. var acyclic = AcyclicType.schema();
  4303. var cyclic = CyclicType.schema();
  4304. var flow = FlowType.schema();
  4305. var flatgrid = FlatgridType.schema();
  4306. var matrix = MatrixType.schema();
  4307. var execution = ExecutionType.schema();
  4308. var menu = MenuType.schema();
  4309. var special = SpecialType.schema();
  4310. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4311. __proto__: null,
  4312. acyclic: acyclic,
  4313. cyclic: cyclic,
  4314. flow: flow,
  4315. flatgrid: flatgrid,
  4316. matrix: matrix,
  4317. execution: execution,
  4318. menu: menu,
  4319. special: special
  4320. });
  4321. var isFlatgridState = function (keyState) {
  4322. return hasNonNullableKey(keyState, 'setGridSize');
  4323. };
  4324. var Keying = createModes({
  4325. branchKey: 'mode',
  4326. branches: KeyboardBranches,
  4327. name: 'keying',
  4328. active: {
  4329. events: function (keyingConfig, keyingState) {
  4330. var handler = keyingConfig.handler;
  4331. return handler.toEvents(keyingConfig, keyingState);
  4332. }
  4333. },
  4334. apis: {
  4335. focusIn: function (component, keyConfig, keyState) {
  4336. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4337. component.getSystem().triggerFocus(component.element, component.element);
  4338. }, function (sendFocusIn) {
  4339. sendFocusIn(component, keyConfig, keyState);
  4340. });
  4341. },
  4342. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4343. if (!isFlatgridState(keyState)) {
  4344. console.error('Layout does not support setGridSize');
  4345. } else {
  4346. keyState.setGridSize(numRows, numColumns);
  4347. }
  4348. }
  4349. },
  4350. state: KeyingState
  4351. });
  4352. var field$1 = function (name, forbidden) {
  4353. return defaultedObjOf(name, {}, map$2(forbidden, function (f) {
  4354. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4355. }).concat([customField('dump', identity)]));
  4356. };
  4357. var get$6 = function (data) {
  4358. return data.dump;
  4359. };
  4360. var augment = function (data, original) {
  4361. return __assign(__assign({}, derive$2(original)), data.dump);
  4362. };
  4363. var SketchBehaviours = {
  4364. field: field$1,
  4365. augment: augment,
  4366. get: get$6
  4367. };
  4368. var _placeholder = 'placeholder';
  4369. var adt$5 = Adt.generate([
  4370. {
  4371. single: [
  4372. 'required',
  4373. 'valueThunk'
  4374. ]
  4375. },
  4376. {
  4377. multiple: [
  4378. 'required',
  4379. 'valueThunks'
  4380. ]
  4381. }
  4382. ]);
  4383. var isSubstituted = function (spec) {
  4384. return has$2(spec, 'uiType');
  4385. };
  4386. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4387. if (owner.exists(function (o) {
  4388. return o !== compSpec.owner;
  4389. })) {
  4390. return adt$5.single(true, constant$1(compSpec));
  4391. }
  4392. return get$c(placeholders, compSpec.name).fold(function () {
  4393. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4394. }, function (newSpec) {
  4395. return newSpec.replace();
  4396. });
  4397. };
  4398. var scan = function (owner, detail, compSpec, placeholders) {
  4399. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  4400. return subPlaceholder(owner, detail, compSpec, placeholders);
  4401. } else {
  4402. return adt$5.single(false, constant$1(compSpec));
  4403. }
  4404. };
  4405. var substitute = function (owner, detail, compSpec, placeholders) {
  4406. var base = scan(owner, detail, compSpec, placeholders);
  4407. return base.fold(function (req, valueThunk) {
  4408. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  4409. var childSpecs = get$c(value, 'components').getOr([]);
  4410. var substituted = bind$3(childSpecs, function (c) {
  4411. return substitute(owner, detail, c, placeholders);
  4412. });
  4413. return [__assign(__assign({}, value), { components: substituted })];
  4414. }, function (req, valuesThunk) {
  4415. if (isSubstituted(compSpec)) {
  4416. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4417. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4418. return preprocessor(values);
  4419. } else {
  4420. return valuesThunk(detail);
  4421. }
  4422. });
  4423. };
  4424. var substituteAll = function (owner, detail, components, placeholders) {
  4425. return bind$3(components, function (c) {
  4426. return substitute(owner, detail, c, placeholders);
  4427. });
  4428. };
  4429. var oneReplace = function (label, replacements) {
  4430. var called = false;
  4431. var used = function () {
  4432. return called;
  4433. };
  4434. var replace = function () {
  4435. if (called) {
  4436. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4437. }
  4438. called = true;
  4439. return replacements;
  4440. };
  4441. var required = function () {
  4442. return replacements.fold(function (req, _) {
  4443. return req;
  4444. }, function (req, _) {
  4445. return req;
  4446. });
  4447. };
  4448. return {
  4449. name: constant$1(label),
  4450. required: required,
  4451. used: used,
  4452. replace: replace
  4453. };
  4454. };
  4455. var substitutePlaces = function (owner, detail, components, placeholders) {
  4456. var ps = map$1(placeholders, function (ph, name) {
  4457. return oneReplace(name, ph);
  4458. });
  4459. var outcome = substituteAll(owner, detail, components, ps);
  4460. each(ps, function (p) {
  4461. if (p.used() === false && p.required()) {
  4462. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4463. }
  4464. });
  4465. return outcome;
  4466. };
  4467. var single$2 = adt$5.single;
  4468. var multiple = adt$5.multiple;
  4469. var placeholder = constant$1(_placeholder);
  4470. var unique = 0;
  4471. var generate$4 = function (prefix) {
  4472. var date = new Date();
  4473. var time = date.getTime();
  4474. var random = Math.floor(Math.random() * 1000000000);
  4475. unique++;
  4476. return prefix + '_' + random + unique + String(time);
  4477. };
  4478. var adt$4 = Adt.generate([
  4479. { required: ['data'] },
  4480. { external: ['data'] },
  4481. { optional: ['data'] },
  4482. { group: ['data'] }
  4483. ]);
  4484. var fFactory = defaulted('factory', { sketch: identity });
  4485. var fSchema = defaulted('schema', []);
  4486. var fName = required$1('name');
  4487. var fPname = field$2('pname', 'pname', defaultedThunk(function (typeSpec) {
  4488. return '<alloy.' + generate$4(typeSpec.name) + '>';
  4489. }), anyValue());
  4490. var fGroupSchema = customField('schema', function () {
  4491. return [option('preprocess')];
  4492. });
  4493. var fDefaults = defaulted('defaults', constant$1({}));
  4494. var fOverrides = defaulted('overrides', constant$1({}));
  4495. var requiredSpec = objOf([
  4496. fFactory,
  4497. fSchema,
  4498. fName,
  4499. fPname,
  4500. fDefaults,
  4501. fOverrides
  4502. ]);
  4503. var externalSpec = objOf([
  4504. fFactory,
  4505. fSchema,
  4506. fName,
  4507. fDefaults,
  4508. fOverrides
  4509. ]);
  4510. var optionalSpec = objOf([
  4511. fFactory,
  4512. fSchema,
  4513. fName,
  4514. fPname,
  4515. fDefaults,
  4516. fOverrides
  4517. ]);
  4518. var groupSpec = objOf([
  4519. fFactory,
  4520. fGroupSchema,
  4521. fName,
  4522. required$1('unit'),
  4523. fPname,
  4524. fDefaults,
  4525. fOverrides
  4526. ]);
  4527. var asNamedPart = function (part) {
  4528. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  4529. };
  4530. var name = function (part) {
  4531. var get = function (data) {
  4532. return data.name;
  4533. };
  4534. return part.fold(get, get, get, get);
  4535. };
  4536. var convert$1 = function (adtConstructor, partSchema) {
  4537. return function (spec) {
  4538. var data = asRawOrDie$1('Converting part type', partSchema, spec);
  4539. return adtConstructor(data);
  4540. };
  4541. };
  4542. var required = convert$1(adt$4.required, requiredSpec);
  4543. convert$1(adt$4.external, externalSpec);
  4544. var optional = convert$1(adt$4.optional, optionalSpec);
  4545. var group = convert$1(adt$4.group, groupSpec);
  4546. var original = constant$1('entirety');
  4547. var combine$2 = function (detail, data, partSpec, partValidated) {
  4548. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4549. };
  4550. var subs = function (owner, detail, parts) {
  4551. var internals = {};
  4552. var externals = {};
  4553. each$1(parts, function (part) {
  4554. part.fold(function (data) {
  4555. internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) {
  4556. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  4557. });
  4558. }, function (data) {
  4559. var partSpec = detail.parts[data.name];
  4560. externals[data.name] = constant$1(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  4561. }, function (data) {
  4562. internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) {
  4563. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  4564. });
  4565. }, function (data) {
  4566. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4567. var units = detail[data.name];
  4568. return map$2(units, function (u) {
  4569. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4570. });
  4571. });
  4572. });
  4573. });
  4574. return {
  4575. internals: constant$1(internals),
  4576. externals: constant$1(externals)
  4577. };
  4578. };
  4579. var generate$3 = function (owner, parts) {
  4580. var r = {};
  4581. each$1(parts, function (part) {
  4582. asNamedPart(part).each(function (np) {
  4583. var g = doGenerateOne(owner, np.pname);
  4584. r[np.name] = function (config) {
  4585. var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4586. return __assign(__assign({}, g), {
  4587. config: config,
  4588. validated: validated
  4589. });
  4590. };
  4591. });
  4592. });
  4593. return r;
  4594. };
  4595. var doGenerateOne = function (owner, pname) {
  4596. return {
  4597. uiType: placeholder(),
  4598. owner: owner,
  4599. name: pname
  4600. };
  4601. };
  4602. var generateOne = function (owner, pname, config) {
  4603. return {
  4604. uiType: placeholder(),
  4605. owner: owner,
  4606. name: pname,
  4607. config: config,
  4608. validated: {}
  4609. };
  4610. };
  4611. var schemas = function (parts) {
  4612. return bind$3(parts, function (part) {
  4613. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  4614. return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
  4615. }).toArray();
  4616. });
  4617. };
  4618. var names = function (parts) {
  4619. return map$2(parts, name);
  4620. };
  4621. var substitutes = function (owner, detail, parts) {
  4622. return subs(owner, detail, parts);
  4623. };
  4624. var components = function (owner, detail, internals) {
  4625. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  4626. };
  4627. var getPart = function (component, detail, partKey) {
  4628. var uid = detail.partUids[partKey];
  4629. return component.getSystem().getByUid(uid).toOptional();
  4630. };
  4631. var getPartOrDie = function (component, detail, partKey) {
  4632. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4633. };
  4634. var getAllParts = function (component, detail) {
  4635. var system = component.getSystem();
  4636. return map$1(detail.partUids, function (pUid, _k) {
  4637. return constant$1(system.getByUid(pUid));
  4638. });
  4639. };
  4640. var defaultUids = function (baseUid, partTypes) {
  4641. var partNames = names(partTypes);
  4642. return wrapAll(map$2(partNames, function (pn) {
  4643. return {
  4644. key: pn,
  4645. value: baseUid + '-' + pn
  4646. };
  4647. }));
  4648. };
  4649. var defaultUidsSchema = function (partTypes) {
  4650. return field$2('partUids', 'partUids', mergeWithThunk(function (spec) {
  4651. return defaultUids(spec.uid, partTypes);
  4652. }), anyValue());
  4653. };
  4654. var premadeTag = generate$4('alloy-premade');
  4655. var premade$1 = function (comp) {
  4656. return wrap(premadeTag, comp);
  4657. };
  4658. var getPremade = function (spec) {
  4659. return get$c(spec, premadeTag);
  4660. };
  4661. var makeApi = function (f) {
  4662. return markAsSketchApi(function (component) {
  4663. var rest = [];
  4664. for (var _i = 1; _i < arguments.length; _i++) {
  4665. rest[_i - 1] = arguments[_i];
  4666. }
  4667. return f.apply(void 0, __spreadArray([
  4668. component.getApis(),
  4669. component
  4670. ], rest, false));
  4671. }, f);
  4672. };
  4673. var prefix$1 = constant$1('alloy-id-');
  4674. var idAttr$1 = constant$1('data-alloy-id');
  4675. var prefix = prefix$1();
  4676. var idAttr = idAttr$1();
  4677. var write = function (label, elem) {
  4678. var id = generate$4(prefix + label);
  4679. writeOnly(elem, id);
  4680. return id;
  4681. };
  4682. var writeOnly = function (elem, uid) {
  4683. Object.defineProperty(elem.dom, idAttr, {
  4684. value: uid,
  4685. writable: true
  4686. });
  4687. };
  4688. var read = function (elem) {
  4689. var id = isElement(elem) ? elem.dom[idAttr] : null;
  4690. return Optional.from(id);
  4691. };
  4692. var generate$2 = function (prefix) {
  4693. return generate$4(prefix);
  4694. };
  4695. var base = function (partSchemas, partUidsSchemas) {
  4696. var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  4697. return ps.concat([
  4698. required$1('uid'),
  4699. defaulted('dom', {}),
  4700. defaulted('components', []),
  4701. snapshot('originalSpec'),
  4702. defaulted('debug.sketcher', {})
  4703. ]).concat(partUidsSchemas);
  4704. };
  4705. var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4706. var baseS = base(partSchemas, partUidsSchemas);
  4707. return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4708. };
  4709. var single$1 = function (owner, schema, factory, spec) {
  4710. var specWithUid = supplyUid(spec);
  4711. var detail = asRawOrDie(owner, schema, specWithUid, [], []);
  4712. return factory(detail, specWithUid);
  4713. };
  4714. var composite$1 = function (owner, schema, partTypes, factory, spec) {
  4715. var specWithUid = supplyUid(spec);
  4716. var partSchemas = schemas(partTypes);
  4717. var partUidsSchema = defaultUidsSchema(partTypes);
  4718. var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4719. var subs = substitutes(owner, detail, partTypes);
  4720. var components$1 = components(owner, detail, subs.internals());
  4721. return factory(detail, components$1, specWithUid, subs.externals());
  4722. };
  4723. var hasUid = function (spec) {
  4724. return has$2(spec, 'uid');
  4725. };
  4726. var supplyUid = function (spec) {
  4727. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  4728. };
  4729. var isSketchSpec$1 = function (spec) {
  4730. return spec.uid !== undefined;
  4731. };
  4732. var singleSchema = objOfOnly([
  4733. required$1('name'),
  4734. required$1('factory'),
  4735. required$1('configFields'),
  4736. defaulted('apis', {}),
  4737. defaulted('extraApis', {})
  4738. ]);
  4739. var compositeSchema = objOfOnly([
  4740. required$1('name'),
  4741. required$1('factory'),
  4742. required$1('configFields'),
  4743. required$1('partFields'),
  4744. defaulted('apis', {}),
  4745. defaulted('extraApis', {})
  4746. ]);
  4747. var single = function (rawConfig) {
  4748. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4749. var sketch = function (spec) {
  4750. return single$1(config.name, config.configFields, config.factory, spec);
  4751. };
  4752. var apis = map$1(config.apis, makeApi);
  4753. var extraApis = map$1(config.extraApis, function (f, k) {
  4754. return markAsExtraApi(f, k);
  4755. });
  4756. return __assign(__assign({
  4757. name: config.name,
  4758. configFields: config.configFields,
  4759. sketch: sketch
  4760. }, apis), extraApis);
  4761. };
  4762. var composite = function (rawConfig) {
  4763. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4764. var sketch = function (spec) {
  4765. return composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  4766. };
  4767. var parts = generate$3(config.name, config.partFields);
  4768. var apis = map$1(config.apis, makeApi);
  4769. var extraApis = map$1(config.extraApis, function (f, k) {
  4770. return markAsExtraApi(f, k);
  4771. });
  4772. return __assign(__assign({
  4773. name: config.name,
  4774. partFields: config.partFields,
  4775. configFields: config.configFields,
  4776. sketch: sketch,
  4777. parts: parts
  4778. }, apis), extraApis);
  4779. };
  4780. var factory$5 = function (detail) {
  4781. var events = events$8(detail.action);
  4782. var tag = detail.dom.tag;
  4783. var lookupAttr = function (attr) {
  4784. return get$c(detail.dom, 'attributes').bind(function (attrs) {
  4785. return get$c(attrs, attr);
  4786. });
  4787. };
  4788. var getModAttributes = function () {
  4789. if (tag === 'button') {
  4790. var type = lookupAttr('type').getOr('button');
  4791. var roleAttrs = lookupAttr('role').map(function (role) {
  4792. return { role: role };
  4793. }).getOr({});
  4794. return __assign({ type: type }, roleAttrs);
  4795. } else {
  4796. var role = lookupAttr('role').getOr('button');
  4797. return { role: role };
  4798. }
  4799. };
  4800. return {
  4801. uid: detail.uid,
  4802. dom: detail.dom,
  4803. components: detail.components,
  4804. events: events,
  4805. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4806. Focusing.config({}),
  4807. Keying.config({
  4808. mode: 'execution',
  4809. useSpace: true,
  4810. useEnter: true
  4811. })
  4812. ]),
  4813. domModification: { attributes: getModAttributes() },
  4814. eventOrder: detail.eventOrder
  4815. };
  4816. };
  4817. var Button = single({
  4818. name: 'Button',
  4819. factory: factory$5,
  4820. configFields: [
  4821. defaulted('uid', undefined),
  4822. required$1('dom'),
  4823. defaulted('components', []),
  4824. SketchBehaviours.field('buttonBehaviours', [
  4825. Focusing,
  4826. Keying
  4827. ]),
  4828. option('action'),
  4829. option('role'),
  4830. defaulted('eventOrder', {})
  4831. ]
  4832. });
  4833. var exhibit$3 = function () {
  4834. return nu$3({
  4835. styles: {
  4836. '-webkit-user-select': 'none',
  4837. 'user-select': 'none',
  4838. '-ms-user-select': 'none',
  4839. '-moz-user-select': '-moz-none'
  4840. },
  4841. attributes: { unselectable: 'on' }
  4842. });
  4843. };
  4844. var events$6 = function () {
  4845. return derive$3([abort(selectstart(), always)]);
  4846. };
  4847. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4848. __proto__: null,
  4849. events: events$6,
  4850. exhibit: exhibit$3
  4851. });
  4852. var Unselecting = create$5({
  4853. fields: [],
  4854. name: 'unselecting',
  4855. active: ActiveUnselecting
  4856. });
  4857. var getAttrs$1 = function (elem) {
  4858. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  4859. return foldl(attributes, function (b, attr) {
  4860. var _a;
  4861. if (attr.name === 'class') {
  4862. return b;
  4863. } else {
  4864. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4865. }
  4866. }, {});
  4867. };
  4868. var getClasses = function (elem) {
  4869. return Array.prototype.slice.call(elem.dom.classList, 0);
  4870. };
  4871. var fromHtml = function (html) {
  4872. var elem = SugarElement.fromHtml(html);
  4873. var children$1 = children(elem);
  4874. var attrs = getAttrs$1(elem);
  4875. var classes = getClasses(elem);
  4876. var contents = children$1.length === 0 ? {} : { innerHtml: get$9(elem) };
  4877. return __assign({
  4878. tag: name$1(elem),
  4879. classes: classes,
  4880. attributes: attrs
  4881. }, contents);
  4882. };
  4883. var dom$1 = function (rawHtml) {
  4884. var html = supplant(rawHtml, { prefix: prefix$2 });
  4885. return fromHtml(html);
  4886. };
  4887. var spec = function (rawHtml) {
  4888. return { dom: dom$1(rawHtml) };
  4889. };
  4890. var forToolbarCommand = function (editor, command) {
  4891. return forToolbar(command, function () {
  4892. editor.execCommand(command);
  4893. }, {}, editor);
  4894. };
  4895. var getToggleBehaviours = function (command) {
  4896. return derive$2([
  4897. Toggling.config({
  4898. toggleClass: resolve('toolbar-button-selected'),
  4899. toggleOnExecute: false,
  4900. aria: { mode: 'pressed' }
  4901. }),
  4902. format(command, function (button, status) {
  4903. var toggle = status ? Toggling.on : Toggling.off;
  4904. toggle(button);
  4905. })
  4906. ]);
  4907. };
  4908. var forToolbarStateCommand = function (editor, command) {
  4909. var extraBehaviours = getToggleBehaviours(command);
  4910. return forToolbar(command, function () {
  4911. editor.execCommand(command);
  4912. }, extraBehaviours, editor);
  4913. };
  4914. var forToolbarStateAction = function (editor, clazz, command, action) {
  4915. var extraBehaviours = getToggleBehaviours(command);
  4916. return forToolbar(clazz, action, extraBehaviours, editor);
  4917. };
  4918. var getToolbarIconButton = function (clazz, editor) {
  4919. var icons = editor.ui.registry.getAll().icons;
  4920. var optOxideIcon = Optional.from(icons[clazz]);
  4921. return optOxideIcon.fold(function () {
  4922. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4923. }, function (icon) {
  4924. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4925. });
  4926. };
  4927. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4928. return Button.sketch({
  4929. dom: getToolbarIconButton(clazz, editor),
  4930. action: action,
  4931. buttonBehaviours: deepMerge(derive$2([Unselecting.config({})]), extraBehaviours)
  4932. });
  4933. };
  4934. var labelPart = optional({
  4935. schema: [required$1('dom')],
  4936. name: 'label'
  4937. });
  4938. var edgePart = function (name) {
  4939. return optional({
  4940. name: '' + name + '-edge',
  4941. overrides: function (detail) {
  4942. var action = detail.model.manager.edgeActions[name];
  4943. return action.fold(function () {
  4944. return {};
  4945. }, function (a) {
  4946. return {
  4947. events: derive$3([
  4948. runActionExtra(touchstart(), function (comp, se, d) {
  4949. return a(comp, d);
  4950. }, [detail]),
  4951. runActionExtra(mousedown(), function (comp, se, d) {
  4952. return a(comp, d);
  4953. }, [detail]),
  4954. runActionExtra(mousemove(), function (comp, se, det) {
  4955. if (det.mouseIsDown.get()) {
  4956. a(comp, det);
  4957. }
  4958. }, [detail])
  4959. ])
  4960. };
  4961. });
  4962. }
  4963. });
  4964. };
  4965. var tlEdgePart = edgePart('top-left');
  4966. var tedgePart = edgePart('top');
  4967. var trEdgePart = edgePart('top-right');
  4968. var redgePart = edgePart('right');
  4969. var brEdgePart = edgePart('bottom-right');
  4970. var bedgePart = edgePart('bottom');
  4971. var blEdgePart = edgePart('bottom-left');
  4972. var ledgePart = edgePart('left');
  4973. var thumbPart = required({
  4974. name: 'thumb',
  4975. defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  4976. overrides: function (detail) {
  4977. return {
  4978. events: derive$3([
  4979. redirectToPart(touchstart(), detail, 'spectrum'),
  4980. redirectToPart(touchmove(), detail, 'spectrum'),
  4981. redirectToPart(touchend(), detail, 'spectrum'),
  4982. redirectToPart(mousedown(), detail, 'spectrum'),
  4983. redirectToPart(mousemove(), detail, 'spectrum'),
  4984. redirectToPart(mouseup(), detail, 'spectrum')
  4985. ])
  4986. };
  4987. }
  4988. });
  4989. var spectrumPart = required({
  4990. schema: [customField('mouseIsDown', function () {
  4991. return Cell(false);
  4992. })],
  4993. name: 'spectrum',
  4994. overrides: function (detail) {
  4995. var modelDetail = detail.model;
  4996. var model = modelDetail.manager;
  4997. var setValueFrom = function (component, simulatedEvent) {
  4998. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  4999. return model.setValueFrom(component, detail, value);
  5000. });
  5001. };
  5002. return {
  5003. behaviours: derive$2([
  5004. Keying.config({
  5005. mode: 'special',
  5006. onLeft: function (spectrum) {
  5007. return model.onLeft(spectrum, detail);
  5008. },
  5009. onRight: function (spectrum) {
  5010. return model.onRight(spectrum, detail);
  5011. },
  5012. onUp: function (spectrum) {
  5013. return model.onUp(spectrum, detail);
  5014. },
  5015. onDown: function (spectrum) {
  5016. return model.onDown(spectrum, detail);
  5017. }
  5018. }),
  5019. Focusing.config({})
  5020. ]),
  5021. events: derive$3([
  5022. run(touchstart(), setValueFrom),
  5023. run(touchmove(), setValueFrom),
  5024. run(mousedown(), setValueFrom),
  5025. run(mousemove(), function (spectrum, se) {
  5026. if (detail.mouseIsDown.get()) {
  5027. setValueFrom(spectrum, se);
  5028. }
  5029. })
  5030. ])
  5031. };
  5032. }
  5033. });
  5034. var SliderParts = [
  5035. labelPart,
  5036. ledgePart,
  5037. redgePart,
  5038. tedgePart,
  5039. bedgePart,
  5040. tlEdgePart,
  5041. trEdgePart,
  5042. blEdgePart,
  5043. brEdgePart,
  5044. thumbPart,
  5045. spectrumPart
  5046. ];
  5047. var onLoad$4 = function (component, repConfig, repState) {
  5048. repConfig.store.manager.onLoad(component, repConfig, repState);
  5049. };
  5050. var onUnload$2 = function (component, repConfig, repState) {
  5051. repConfig.store.manager.onUnload(component, repConfig, repState);
  5052. };
  5053. var setValue$3 = function (component, repConfig, repState, data) {
  5054. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5055. };
  5056. var getValue$4 = function (component, repConfig, repState) {
  5057. return repConfig.store.manager.getValue(component, repConfig, repState);
  5058. };
  5059. var getState$1 = function (component, repConfig, repState) {
  5060. return repState;
  5061. };
  5062. var RepresentApis = /*#__PURE__*/Object.freeze({
  5063. __proto__: null,
  5064. onLoad: onLoad$4,
  5065. onUnload: onUnload$2,
  5066. setValue: setValue$3,
  5067. getValue: getValue$4,
  5068. getState: getState$1
  5069. });
  5070. var events$5 = function (repConfig, repState) {
  5071. var es = repConfig.resetOnDom ? [
  5072. runOnAttached(function (comp, _se) {
  5073. onLoad$4(comp, repConfig, repState);
  5074. }),
  5075. runOnDetached(function (comp, _se) {
  5076. onUnload$2(comp, repConfig, repState);
  5077. })
  5078. ] : [loadEvent(repConfig, repState, onLoad$4)];
  5079. return derive$3(es);
  5080. };
  5081. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5082. __proto__: null,
  5083. events: events$5
  5084. });
  5085. var memory = function () {
  5086. var data = Cell(null);
  5087. var readState = function () {
  5088. return {
  5089. mode: 'memory',
  5090. value: data.get()
  5091. };
  5092. };
  5093. var isNotSet = function () {
  5094. return data.get() === null;
  5095. };
  5096. var clear = function () {
  5097. data.set(null);
  5098. };
  5099. return nu$2({
  5100. set: data.set,
  5101. get: data.get,
  5102. isNotSet: isNotSet,
  5103. clear: clear,
  5104. readState: readState
  5105. });
  5106. };
  5107. var manual = function () {
  5108. var readState = noop;
  5109. return nu$2({ readState: readState });
  5110. };
  5111. var dataset = function () {
  5112. var dataByValue = Cell({});
  5113. var dataByText = Cell({});
  5114. var readState = function () {
  5115. return {
  5116. mode: 'dataset',
  5117. dataByValue: dataByValue.get(),
  5118. dataByText: dataByText.get()
  5119. };
  5120. };
  5121. var clear = function () {
  5122. dataByValue.set({});
  5123. dataByText.set({});
  5124. };
  5125. var lookup = function (itemString) {
  5126. return get$c(dataByValue.get(), itemString).orThunk(function () {
  5127. return get$c(dataByText.get(), itemString);
  5128. });
  5129. };
  5130. var update = function (items) {
  5131. var currentDataByValue = dataByValue.get();
  5132. var currentDataByText = dataByText.get();
  5133. var newDataByValue = {};
  5134. var newDataByText = {};
  5135. each$1(items, function (item) {
  5136. newDataByValue[item.value] = item;
  5137. get$c(item, 'meta').each(function (meta) {
  5138. get$c(meta, 'text').each(function (text) {
  5139. newDataByText[text] = item;
  5140. });
  5141. });
  5142. });
  5143. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5144. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5145. };
  5146. return nu$2({
  5147. readState: readState,
  5148. lookup: lookup,
  5149. update: update,
  5150. clear: clear
  5151. });
  5152. };
  5153. var init$4 = function (spec) {
  5154. return spec.store.manager.state(spec);
  5155. };
  5156. var RepresentState = /*#__PURE__*/Object.freeze({
  5157. __proto__: null,
  5158. memory: memory,
  5159. dataset: dataset,
  5160. manual: manual,
  5161. init: init$4
  5162. });
  5163. var setValue$2 = function (component, repConfig, repState, data) {
  5164. var store = repConfig.store;
  5165. repState.update([data]);
  5166. store.setValue(component, data);
  5167. repConfig.onSetValue(component, data);
  5168. };
  5169. var getValue$3 = function (component, repConfig, repState) {
  5170. var store = repConfig.store;
  5171. var key = store.getDataKey(component);
  5172. return repState.lookup(key).getOrThunk(function () {
  5173. return store.getFallbackEntry(key);
  5174. });
  5175. };
  5176. var onLoad$3 = function (component, repConfig, repState) {
  5177. var store = repConfig.store;
  5178. store.initialValue.each(function (data) {
  5179. setValue$2(component, repConfig, repState, data);
  5180. });
  5181. };
  5182. var onUnload$1 = function (component, repConfig, repState) {
  5183. repState.clear();
  5184. };
  5185. var DatasetStore = [
  5186. option('initialValue'),
  5187. required$1('getFallbackEntry'),
  5188. required$1('getDataKey'),
  5189. required$1('setValue'),
  5190. output('manager', {
  5191. setValue: setValue$2,
  5192. getValue: getValue$3,
  5193. onLoad: onLoad$3,
  5194. onUnload: onUnload$1,
  5195. state: dataset
  5196. })
  5197. ];
  5198. var getValue$2 = function (component, repConfig, _repState) {
  5199. return repConfig.store.getValue(component);
  5200. };
  5201. var setValue$1 = function (component, repConfig, _repState, data) {
  5202. repConfig.store.setValue(component, data);
  5203. repConfig.onSetValue(component, data);
  5204. };
  5205. var onLoad$2 = function (component, repConfig, _repState) {
  5206. repConfig.store.initialValue.each(function (data) {
  5207. repConfig.store.setValue(component, data);
  5208. });
  5209. };
  5210. var ManualStore = [
  5211. required$1('getValue'),
  5212. defaulted('setValue', noop),
  5213. option('initialValue'),
  5214. output('manager', {
  5215. setValue: setValue$1,
  5216. getValue: getValue$2,
  5217. onLoad: onLoad$2,
  5218. onUnload: noop,
  5219. state: NoState.init
  5220. })
  5221. ];
  5222. var setValue = function (component, repConfig, repState, data) {
  5223. repState.set(data);
  5224. repConfig.onSetValue(component, data);
  5225. };
  5226. var getValue$1 = function (component, repConfig, repState) {
  5227. return repState.get();
  5228. };
  5229. var onLoad$1 = function (component, repConfig, repState) {
  5230. repConfig.store.initialValue.each(function (initVal) {
  5231. if (repState.isNotSet()) {
  5232. repState.set(initVal);
  5233. }
  5234. });
  5235. };
  5236. var onUnload = function (component, repConfig, repState) {
  5237. repState.clear();
  5238. };
  5239. var MemoryStore = [
  5240. option('initialValue'),
  5241. output('manager', {
  5242. setValue: setValue,
  5243. getValue: getValue$1,
  5244. onLoad: onLoad$1,
  5245. onUnload: onUnload,
  5246. state: memory
  5247. })
  5248. ];
  5249. var RepresentSchema = [
  5250. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5251. memory: MemoryStore,
  5252. manual: ManualStore,
  5253. dataset: DatasetStore
  5254. })),
  5255. onHandler('onSetValue'),
  5256. defaulted('resetOnDom', false)
  5257. ];
  5258. var Representing = create$5({
  5259. fields: RepresentSchema,
  5260. name: 'representing',
  5261. active: ActiveRepresenting,
  5262. apis: RepresentApis,
  5263. extra: {
  5264. setValueFrom: function (component, source) {
  5265. var value = Representing.getValue(source);
  5266. Representing.setValue(component, value);
  5267. }
  5268. },
  5269. state: RepresentState
  5270. });
  5271. var api$1 = Dimension('width', function (element) {
  5272. return element.dom.offsetWidth;
  5273. });
  5274. var set$4 = function (element, h) {
  5275. return api$1.set(element, h);
  5276. };
  5277. var get$5 = function (element) {
  5278. return api$1.get(element);
  5279. };
  5280. var r$1 = function (left, top) {
  5281. var translate = function (x, y) {
  5282. return r$1(left + x, top + y);
  5283. };
  5284. return {
  5285. left: left,
  5286. top: top,
  5287. translate: translate
  5288. };
  5289. };
  5290. var SugarPosition = r$1;
  5291. var _sliderChangeEvent = 'slider.change.value';
  5292. var sliderChangeEvent = constant$1(_sliderChangeEvent);
  5293. var isTouchEvent = function (evt) {
  5294. return evt.type.indexOf('touch') !== -1;
  5295. };
  5296. var getEventSource = function (simulatedEvent) {
  5297. var evt = simulatedEvent.event.raw;
  5298. if (isTouchEvent(evt)) {
  5299. var touchEvent = evt;
  5300. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  5301. return SugarPosition(t.clientX, t.clientY);
  5302. }) : Optional.none();
  5303. } else {
  5304. var mouseEvent = evt;
  5305. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  5306. return SugarPosition(me.clientX, me.clientY);
  5307. }) : Optional.none();
  5308. }
  5309. };
  5310. var t = 'top', r = 'right', b = 'bottom', l = 'left';
  5311. var minX = function (detail) {
  5312. return detail.model.minX;
  5313. };
  5314. var minY = function (detail) {
  5315. return detail.model.minY;
  5316. };
  5317. var min1X = function (detail) {
  5318. return detail.model.minX - 1;
  5319. };
  5320. var min1Y = function (detail) {
  5321. return detail.model.minY - 1;
  5322. };
  5323. var maxX = function (detail) {
  5324. return detail.model.maxX;
  5325. };
  5326. var maxY = function (detail) {
  5327. return detail.model.maxY;
  5328. };
  5329. var max1X = function (detail) {
  5330. return detail.model.maxX + 1;
  5331. };
  5332. var max1Y = function (detail) {
  5333. return detail.model.maxY + 1;
  5334. };
  5335. var range$1 = function (detail, max, min) {
  5336. return max(detail) - min(detail);
  5337. };
  5338. var xRange = function (detail) {
  5339. return range$1(detail, maxX, minX);
  5340. };
  5341. var yRange = function (detail) {
  5342. return range$1(detail, maxY, minY);
  5343. };
  5344. var halfX = function (detail) {
  5345. return xRange(detail) / 2;
  5346. };
  5347. var halfY = function (detail) {
  5348. return yRange(detail) / 2;
  5349. };
  5350. var step = function (detail) {
  5351. return detail.stepSize;
  5352. };
  5353. var snap = function (detail) {
  5354. return detail.snapToGrid;
  5355. };
  5356. var snapStart = function (detail) {
  5357. return detail.snapStart;
  5358. };
  5359. var rounded = function (detail) {
  5360. return detail.rounded;
  5361. };
  5362. var hasEdge = function (detail, edgeName) {
  5363. return detail[edgeName + '-edge'] !== undefined;
  5364. };
  5365. var hasLEdge = function (detail) {
  5366. return hasEdge(detail, l);
  5367. };
  5368. var hasREdge = function (detail) {
  5369. return hasEdge(detail, r);
  5370. };
  5371. var hasTEdge = function (detail) {
  5372. return hasEdge(detail, t);
  5373. };
  5374. var hasBEdge = function (detail) {
  5375. return hasEdge(detail, b);
  5376. };
  5377. var currentValue = function (detail) {
  5378. return detail.model.value.get();
  5379. };
  5380. var xValue = function (x) {
  5381. return { x: x };
  5382. };
  5383. var yValue = function (y) {
  5384. return { y: y };
  5385. };
  5386. var xyValue = function (x, y) {
  5387. return {
  5388. x: x,
  5389. y: y
  5390. };
  5391. };
  5392. var fireSliderChange$3 = function (component, value) {
  5393. emitWith(component, sliderChangeEvent(), { value: value });
  5394. };
  5395. var setToTLEdgeXY = function (edge, detail) {
  5396. fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  5397. };
  5398. var setToTEdge = function (edge, detail) {
  5399. fireSliderChange$3(edge, yValue(min1Y(detail)));
  5400. };
  5401. var setToTEdgeXY = function (edge, detail) {
  5402. fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  5403. };
  5404. var setToTREdgeXY = function (edge, detail) {
  5405. fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  5406. };
  5407. var setToREdge = function (edge, detail) {
  5408. fireSliderChange$3(edge, xValue(max1X(detail)));
  5409. };
  5410. var setToREdgeXY = function (edge, detail) {
  5411. fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  5412. };
  5413. var setToBREdgeXY = function (edge, detail) {
  5414. fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  5415. };
  5416. var setToBEdge = function (edge, detail) {
  5417. fireSliderChange$3(edge, yValue(max1Y(detail)));
  5418. };
  5419. var setToBEdgeXY = function (edge, detail) {
  5420. fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  5421. };
  5422. var setToBLEdgeXY = function (edge, detail) {
  5423. fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  5424. };
  5425. var setToLEdge = function (edge, detail) {
  5426. fireSliderChange$3(edge, xValue(min1X(detail)));
  5427. };
  5428. var setToLEdgeXY = function (edge, detail) {
  5429. fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  5430. };
  5431. var reduceBy = function (value, min, max, step) {
  5432. if (value < min) {
  5433. return value;
  5434. } else if (value > max) {
  5435. return max;
  5436. } else if (value === min) {
  5437. return min - 1;
  5438. } else {
  5439. return Math.max(min, value - step);
  5440. }
  5441. };
  5442. var increaseBy = function (value, min, max, step) {
  5443. if (value > max) {
  5444. return value;
  5445. } else if (value < min) {
  5446. return min;
  5447. } else if (value === max) {
  5448. return max + 1;
  5449. } else {
  5450. return Math.min(max, value + step);
  5451. }
  5452. };
  5453. var capValue = function (value, min, max) {
  5454. return Math.max(min, Math.min(max, value));
  5455. };
  5456. var snapValueOf = function (value, min, max, step, snapStart) {
  5457. return snapStart.fold(function () {
  5458. var initValue = value - min;
  5459. var extraValue = Math.round(initValue / step) * step;
  5460. return capValue(min + extraValue, min - 1, max + 1);
  5461. }, function (start) {
  5462. var remainder = (value - start) % step;
  5463. var adjustment = Math.round(remainder / step);
  5464. var rawSteps = Math.floor((value - start) / step);
  5465. var maxSteps = Math.floor((max - start) / step);
  5466. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5467. var r = start + numSteps * step;
  5468. return Math.max(start, r);
  5469. });
  5470. };
  5471. var findOffsetOf = function (value, min, max) {
  5472. return Math.min(max, Math.max(value, min)) - min;
  5473. };
  5474. var findValueOf = function (args) {
  5475. 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;
  5476. var capMin = hasMinEdge ? min - 1 : min;
  5477. var capMax = hasMaxEdge ? max + 1 : max;
  5478. if (value < minBound) {
  5479. return capMin;
  5480. } else if (value > maxBound) {
  5481. return capMax;
  5482. } else {
  5483. var offset = findOffsetOf(value, minBound, maxBound);
  5484. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5485. if (snap && newValue >= min && newValue <= max) {
  5486. return snapValueOf(newValue, min, max, step, snapStart);
  5487. } else if (rounded) {
  5488. return Math.round(newValue);
  5489. } else {
  5490. return newValue;
  5491. }
  5492. }
  5493. };
  5494. var findOffsetOfValue$2 = function (args) {
  5495. 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;
  5496. if (value < min) {
  5497. return hasMinEdge ? 0 : centerMinEdge;
  5498. } else if (value > max) {
  5499. return hasMaxEdge ? maxBound : centerMaxEdge;
  5500. } else {
  5501. return (value - min) / range * maxOffset;
  5502. }
  5503. };
  5504. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5505. var getBounds$1 = function (component) {
  5506. return component.element.dom.getBoundingClientRect();
  5507. };
  5508. var getBoundsProperty = function (bounds, property) {
  5509. return bounds[property];
  5510. };
  5511. var getMinXBounds = function (component) {
  5512. var bounds = getBounds$1(component);
  5513. return getBoundsProperty(bounds, left);
  5514. };
  5515. var getMaxXBounds = function (component) {
  5516. var bounds = getBounds$1(component);
  5517. return getBoundsProperty(bounds, right);
  5518. };
  5519. var getMinYBounds = function (component) {
  5520. var bounds = getBounds$1(component);
  5521. return getBoundsProperty(bounds, top);
  5522. };
  5523. var getMaxYBounds = function (component) {
  5524. var bounds = getBounds$1(component);
  5525. return getBoundsProperty(bounds, bottom);
  5526. };
  5527. var getXScreenRange = function (component) {
  5528. var bounds = getBounds$1(component);
  5529. return getBoundsProperty(bounds, width);
  5530. };
  5531. var getYScreenRange = function (component) {
  5532. var bounds = getBounds$1(component);
  5533. return getBoundsProperty(bounds, height);
  5534. };
  5535. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5536. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5537. };
  5538. var getXCenterOffSetOf = function (component, spectrum) {
  5539. var componentBounds = getBounds$1(component);
  5540. var spectrumBounds = getBounds$1(spectrum);
  5541. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5542. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5543. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5544. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5545. };
  5546. var getYCenterOffSetOf = function (component, spectrum) {
  5547. var componentBounds = getBounds$1(component);
  5548. var spectrumBounds = getBounds$1(spectrum);
  5549. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5550. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5551. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5552. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5553. };
  5554. var fireSliderChange$2 = function (spectrum, value) {
  5555. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5556. };
  5557. var sliderValue$2 = function (x) {
  5558. return { x: x };
  5559. };
  5560. var findValueOfOffset$1 = function (spectrum, detail, left) {
  5561. var args = {
  5562. min: minX(detail),
  5563. max: maxX(detail),
  5564. range: xRange(detail),
  5565. value: left,
  5566. step: step(detail),
  5567. snap: snap(detail),
  5568. snapStart: snapStart(detail),
  5569. rounded: rounded(detail),
  5570. hasMinEdge: hasLEdge(detail),
  5571. hasMaxEdge: hasREdge(detail),
  5572. minBound: getMinXBounds(spectrum),
  5573. maxBound: getMaxXBounds(spectrum),
  5574. screenRange: getXScreenRange(spectrum)
  5575. };
  5576. return findValueOf(args);
  5577. };
  5578. var setValueFrom$2 = function (spectrum, detail, value) {
  5579. var xValue = findValueOfOffset$1(spectrum, detail, value);
  5580. var sliderVal = sliderValue$2(xValue);
  5581. fireSliderChange$2(spectrum, sliderVal);
  5582. return xValue;
  5583. };
  5584. var setToMin$2 = function (spectrum, detail) {
  5585. var min = minX(detail);
  5586. fireSliderChange$2(spectrum, sliderValue$2(min));
  5587. };
  5588. var setToMax$2 = function (spectrum, detail) {
  5589. var max = maxX(detail);
  5590. fireSliderChange$2(spectrum, sliderValue$2(max));
  5591. };
  5592. var moveBy$2 = function (direction, spectrum, detail) {
  5593. var f = direction > 0 ? increaseBy : reduceBy;
  5594. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5595. fireSliderChange$2(spectrum, sliderValue$2(xValue));
  5596. return Optional.some(xValue);
  5597. };
  5598. var handleMovement$2 = function (direction) {
  5599. return function (spectrum, detail) {
  5600. return moveBy$2(direction, spectrum, detail).map(always);
  5601. };
  5602. };
  5603. var getValueFromEvent$2 = function (simulatedEvent) {
  5604. var pos = getEventSource(simulatedEvent);
  5605. return pos.map(function (p) {
  5606. return p.left;
  5607. });
  5608. };
  5609. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5610. var minOffset = 0;
  5611. var maxOffset = getXScreenRange(spectrum);
  5612. var centerMinEdge = minEdge.bind(function (edge) {
  5613. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5614. }).getOr(minOffset);
  5615. var centerMaxEdge = maxEdge.bind(function (edge) {
  5616. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5617. }).getOr(maxOffset);
  5618. var args = {
  5619. min: minX(detail),
  5620. max: maxX(detail),
  5621. range: xRange(detail),
  5622. value: value,
  5623. hasMinEdge: hasLEdge(detail),
  5624. hasMaxEdge: hasREdge(detail),
  5625. minBound: getMinXBounds(spectrum),
  5626. minOffset: minOffset,
  5627. maxBound: getMaxXBounds(spectrum),
  5628. maxOffset: maxOffset,
  5629. centerMinEdge: centerMinEdge,
  5630. centerMaxEdge: centerMaxEdge
  5631. };
  5632. return findOffsetOfValue$2(args);
  5633. };
  5634. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5635. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5636. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5637. };
  5638. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5639. var value = currentValue(detail);
  5640. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5641. var thumbRadius = get$5(thumb.element) / 2;
  5642. set$5(thumb.element, 'left', pos - thumbRadius + 'px');
  5643. };
  5644. var onLeft$2 = handleMovement$2(-1);
  5645. var onRight$2 = handleMovement$2(1);
  5646. var onUp$2 = Optional.none;
  5647. var onDown$2 = Optional.none;
  5648. var edgeActions$2 = {
  5649. 'top-left': Optional.none(),
  5650. 'top': Optional.none(),
  5651. 'top-right': Optional.none(),
  5652. 'right': Optional.some(setToREdge),
  5653. 'bottom-right': Optional.none(),
  5654. 'bottom': Optional.none(),
  5655. 'bottom-left': Optional.none(),
  5656. 'left': Optional.some(setToLEdge)
  5657. };
  5658. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5659. __proto__: null,
  5660. setValueFrom: setValueFrom$2,
  5661. setToMin: setToMin$2,
  5662. setToMax: setToMax$2,
  5663. findValueOfOffset: findValueOfOffset$1,
  5664. getValueFromEvent: getValueFromEvent$2,
  5665. findPositionOfValue: findPositionOfValue$1,
  5666. setPositionFromValue: setPositionFromValue$2,
  5667. onLeft: onLeft$2,
  5668. onRight: onRight$2,
  5669. onUp: onUp$2,
  5670. onDown: onDown$2,
  5671. edgeActions: edgeActions$2
  5672. });
  5673. var fireSliderChange$1 = function (spectrum, value) {
  5674. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5675. };
  5676. var sliderValue$1 = function (y) {
  5677. return { y: y };
  5678. };
  5679. var findValueOfOffset = function (spectrum, detail, top) {
  5680. var args = {
  5681. min: minY(detail),
  5682. max: maxY(detail),
  5683. range: yRange(detail),
  5684. value: top,
  5685. step: step(detail),
  5686. snap: snap(detail),
  5687. snapStart: snapStart(detail),
  5688. rounded: rounded(detail),
  5689. hasMinEdge: hasTEdge(detail),
  5690. hasMaxEdge: hasBEdge(detail),
  5691. minBound: getMinYBounds(spectrum),
  5692. maxBound: getMaxYBounds(spectrum),
  5693. screenRange: getYScreenRange(spectrum)
  5694. };
  5695. return findValueOf(args);
  5696. };
  5697. var setValueFrom$1 = function (spectrum, detail, value) {
  5698. var yValue = findValueOfOffset(spectrum, detail, value);
  5699. var sliderVal = sliderValue$1(yValue);
  5700. fireSliderChange$1(spectrum, sliderVal);
  5701. return yValue;
  5702. };
  5703. var setToMin$1 = function (spectrum, detail) {
  5704. var min = minY(detail);
  5705. fireSliderChange$1(spectrum, sliderValue$1(min));
  5706. };
  5707. var setToMax$1 = function (spectrum, detail) {
  5708. var max = maxY(detail);
  5709. fireSliderChange$1(spectrum, sliderValue$1(max));
  5710. };
  5711. var moveBy$1 = function (direction, spectrum, detail) {
  5712. var f = direction > 0 ? increaseBy : reduceBy;
  5713. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5714. fireSliderChange$1(spectrum, sliderValue$1(yValue));
  5715. return Optional.some(yValue);
  5716. };
  5717. var handleMovement$1 = function (direction) {
  5718. return function (spectrum, detail) {
  5719. return moveBy$1(direction, spectrum, detail).map(always);
  5720. };
  5721. };
  5722. var getValueFromEvent$1 = function (simulatedEvent) {
  5723. var pos = getEventSource(simulatedEvent);
  5724. return pos.map(function (p) {
  5725. return p.top;
  5726. });
  5727. };
  5728. var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) {
  5729. var minOffset = 0;
  5730. var maxOffset = getYScreenRange(spectrum);
  5731. var centerMinEdge = minEdge.bind(function (edge) {
  5732. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5733. }).getOr(minOffset);
  5734. var centerMaxEdge = maxEdge.bind(function (edge) {
  5735. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5736. }).getOr(maxOffset);
  5737. var args = {
  5738. min: minY(detail),
  5739. max: maxY(detail),
  5740. range: yRange(detail),
  5741. value: value,
  5742. hasMinEdge: hasTEdge(detail),
  5743. hasMaxEdge: hasBEdge(detail),
  5744. minBound: getMinYBounds(spectrum),
  5745. minOffset: minOffset,
  5746. maxBound: getMaxYBounds(spectrum),
  5747. maxOffset: maxOffset,
  5748. centerMinEdge: centerMinEdge,
  5749. centerMaxEdge: centerMaxEdge
  5750. };
  5751. return findOffsetOfValue$2(args);
  5752. };
  5753. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5754. var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  5755. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5756. };
  5757. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5758. var value = currentValue(detail);
  5759. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5760. var thumbRadius = get$7(thumb.element) / 2;
  5761. set$5(thumb.element, 'top', pos - thumbRadius + 'px');
  5762. };
  5763. var onLeft$1 = Optional.none;
  5764. var onRight$1 = Optional.none;
  5765. var onUp$1 = handleMovement$1(-1);
  5766. var onDown$1 = handleMovement$1(1);
  5767. var edgeActions$1 = {
  5768. 'top-left': Optional.none(),
  5769. 'top': Optional.some(setToTEdge),
  5770. 'top-right': Optional.none(),
  5771. 'right': Optional.none(),
  5772. 'bottom-right': Optional.none(),
  5773. 'bottom': Optional.some(setToBEdge),
  5774. 'bottom-left': Optional.none(),
  5775. 'left': Optional.none()
  5776. };
  5777. var VerticalModel = /*#__PURE__*/Object.freeze({
  5778. __proto__: null,
  5779. setValueFrom: setValueFrom$1,
  5780. setToMin: setToMin$1,
  5781. setToMax: setToMax$1,
  5782. findValueOfOffset: findValueOfOffset,
  5783. getValueFromEvent: getValueFromEvent$1,
  5784. findPositionOfValue: findPositionOfValue,
  5785. setPositionFromValue: setPositionFromValue$1,
  5786. onLeft: onLeft$1,
  5787. onRight: onRight$1,
  5788. onUp: onUp$1,
  5789. onDown: onDown$1,
  5790. edgeActions: edgeActions$1
  5791. });
  5792. var fireSliderChange = function (spectrum, value) {
  5793. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5794. };
  5795. var sliderValue = function (x, y) {
  5796. return {
  5797. x: x,
  5798. y: y
  5799. };
  5800. };
  5801. var setValueFrom = function (spectrum, detail, value) {
  5802. var xValue = findValueOfOffset$1(spectrum, detail, value.left);
  5803. var yValue = findValueOfOffset(spectrum, detail, value.top);
  5804. var val = sliderValue(xValue, yValue);
  5805. fireSliderChange(spectrum, val);
  5806. return val;
  5807. };
  5808. var moveBy = function (direction, isVerticalMovement, spectrum, detail) {
  5809. var f = direction > 0 ? increaseBy : reduceBy;
  5810. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5811. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5812. fireSliderChange(spectrum, sliderValue(xValue, yValue));
  5813. return Optional.some(xValue);
  5814. };
  5815. var handleMovement = function (direction, isVerticalMovement) {
  5816. return function (spectrum, detail) {
  5817. return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  5818. };
  5819. };
  5820. var setToMin = function (spectrum, detail) {
  5821. var mX = minX(detail);
  5822. var mY = minY(detail);
  5823. fireSliderChange(spectrum, sliderValue(mX, mY));
  5824. };
  5825. var setToMax = function (spectrum, detail) {
  5826. var mX = maxX(detail);
  5827. var mY = maxY(detail);
  5828. fireSliderChange(spectrum, sliderValue(mX, mY));
  5829. };
  5830. var getValueFromEvent = function (simulatedEvent) {
  5831. return getEventSource(simulatedEvent);
  5832. };
  5833. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5834. var value = currentValue(detail);
  5835. var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5836. var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5837. var thumbXRadius = get$5(thumb.element) / 2;
  5838. var thumbYRadius = get$7(thumb.element) / 2;
  5839. set$5(thumb.element, 'left', xPos - thumbXRadius + 'px');
  5840. set$5(thumb.element, 'top', yPos - thumbYRadius + 'px');
  5841. };
  5842. var onLeft = handleMovement(-1, false);
  5843. var onRight = handleMovement(1, false);
  5844. var onUp = handleMovement(-1, true);
  5845. var onDown = handleMovement(1, true);
  5846. var edgeActions = {
  5847. 'top-left': Optional.some(setToTLEdgeXY),
  5848. 'top': Optional.some(setToTEdgeXY),
  5849. 'top-right': Optional.some(setToTREdgeXY),
  5850. 'right': Optional.some(setToREdgeXY),
  5851. 'bottom-right': Optional.some(setToBREdgeXY),
  5852. 'bottom': Optional.some(setToBEdgeXY),
  5853. 'bottom-left': Optional.some(setToBLEdgeXY),
  5854. 'left': Optional.some(setToLEdgeXY)
  5855. };
  5856. var TwoDModel = /*#__PURE__*/Object.freeze({
  5857. __proto__: null,
  5858. setValueFrom: setValueFrom,
  5859. setToMin: setToMin,
  5860. setToMax: setToMax,
  5861. getValueFromEvent: getValueFromEvent,
  5862. setPositionFromValue: setPositionFromValue,
  5863. onLeft: onLeft,
  5864. onRight: onRight,
  5865. onUp: onUp,
  5866. onDown: onDown,
  5867. edgeActions: edgeActions
  5868. });
  5869. var SliderSchema = [
  5870. defaulted('stepSize', 1),
  5871. defaulted('onChange', noop),
  5872. defaulted('onChoose', noop),
  5873. defaulted('onInit', noop),
  5874. defaulted('onDragStart', noop),
  5875. defaulted('onDragEnd', noop),
  5876. defaulted('snapToGrid', false),
  5877. defaulted('rounded', true),
  5878. option('snapStart'),
  5879. requiredOf('model', choose$1('mode', {
  5880. x: [
  5881. defaulted('minX', 0),
  5882. defaulted('maxX', 100),
  5883. customField('value', function (spec) {
  5884. return Cell(spec.mode.minX);
  5885. }),
  5886. required$1('getInitialValue'),
  5887. output('manager', HorizontalModel)
  5888. ],
  5889. y: [
  5890. defaulted('minY', 0),
  5891. defaulted('maxY', 100),
  5892. customField('value', function (spec) {
  5893. return Cell(spec.mode.minY);
  5894. }),
  5895. required$1('getInitialValue'),
  5896. output('manager', VerticalModel)
  5897. ],
  5898. xy: [
  5899. defaulted('minX', 0),
  5900. defaulted('maxX', 100),
  5901. defaulted('minY', 0),
  5902. defaulted('maxY', 100),
  5903. customField('value', function (spec) {
  5904. return Cell({
  5905. x: spec.mode.minX,
  5906. y: spec.mode.minY
  5907. });
  5908. }),
  5909. required$1('getInitialValue'),
  5910. output('manager', TwoDModel)
  5911. ]
  5912. })),
  5913. field$1('sliderBehaviours', [
  5914. Keying,
  5915. Representing
  5916. ]),
  5917. customField('mouseIsDown', function () {
  5918. return Cell(false);
  5919. })
  5920. ];
  5921. var mouseReleased = constant$1('mouse.released');
  5922. var sketch$9 = function (detail, components, _spec, _externals) {
  5923. var _a;
  5924. var getThumb = function (component) {
  5925. return getPartOrDie(component, detail, 'thumb');
  5926. };
  5927. var getSpectrum = function (component) {
  5928. return getPartOrDie(component, detail, 'spectrum');
  5929. };
  5930. var getLeftEdge = function (component) {
  5931. return getPart(component, detail, 'left-edge');
  5932. };
  5933. var getRightEdge = function (component) {
  5934. return getPart(component, detail, 'right-edge');
  5935. };
  5936. var getTopEdge = function (component) {
  5937. return getPart(component, detail, 'top-edge');
  5938. };
  5939. var getBottomEdge = function (component) {
  5940. return getPart(component, detail, 'bottom-edge');
  5941. };
  5942. var modelDetail = detail.model;
  5943. var model = modelDetail.manager;
  5944. var refresh = function (slider, thumb) {
  5945. model.setPositionFromValue(slider, thumb, detail, {
  5946. getLeftEdge: getLeftEdge,
  5947. getRightEdge: getRightEdge,
  5948. getTopEdge: getTopEdge,
  5949. getBottomEdge: getBottomEdge,
  5950. getSpectrum: getSpectrum
  5951. });
  5952. };
  5953. var setValue = function (slider, newValue) {
  5954. modelDetail.value.set(newValue);
  5955. var thumb = getThumb(slider);
  5956. refresh(slider, thumb);
  5957. };
  5958. var changeValue = function (slider, newValue) {
  5959. setValue(slider, newValue);
  5960. var thumb = getThumb(slider);
  5961. detail.onChange(slider, thumb, newValue);
  5962. return Optional.some(true);
  5963. };
  5964. var resetToMin = function (slider) {
  5965. model.setToMin(slider, detail);
  5966. };
  5967. var resetToMax = function (slider) {
  5968. model.setToMax(slider, detail);
  5969. };
  5970. var choose = function (slider) {
  5971. var fireOnChoose = function () {
  5972. getPart(slider, detail, 'thumb').each(function (thumb) {
  5973. var value = modelDetail.value.get();
  5974. detail.onChoose(slider, thumb, value);
  5975. });
  5976. };
  5977. var wasDown = detail.mouseIsDown.get();
  5978. detail.mouseIsDown.set(false);
  5979. if (wasDown) {
  5980. fireOnChoose();
  5981. }
  5982. };
  5983. var onDragStart = function (slider, simulatedEvent) {
  5984. simulatedEvent.stop();
  5985. detail.mouseIsDown.set(true);
  5986. detail.onDragStart(slider, getThumb(slider));
  5987. };
  5988. var onDragEnd = function (slider, simulatedEvent) {
  5989. simulatedEvent.stop();
  5990. detail.onDragEnd(slider, getThumb(slider));
  5991. choose(slider);
  5992. };
  5993. return {
  5994. uid: detail.uid,
  5995. dom: detail.dom,
  5996. components: components,
  5997. behaviours: augment(detail.sliderBehaviours, [
  5998. Keying.config({
  5999. mode: 'special',
  6000. focusIn: function (slider) {
  6001. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  6002. }
  6003. }),
  6004. Representing.config({
  6005. store: {
  6006. mode: 'manual',
  6007. getValue: function (_) {
  6008. return modelDetail.value.get();
  6009. }
  6010. }
  6011. }),
  6012. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  6013. ]),
  6014. events: derive$3([
  6015. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  6016. changeValue(slider, simulatedEvent.event.value);
  6017. }),
  6018. runOnAttached(function (slider, _simulatedEvent) {
  6019. var getInitial = modelDetail.getInitialValue();
  6020. modelDetail.value.set(getInitial);
  6021. var thumb = getThumb(slider);
  6022. refresh(slider, thumb);
  6023. var spectrum = getSpectrum(slider);
  6024. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  6025. }),
  6026. run(touchstart(), onDragStart),
  6027. run(touchend(), onDragEnd),
  6028. run(mousedown(), onDragStart),
  6029. run(mouseup(), onDragEnd)
  6030. ]),
  6031. apis: {
  6032. resetToMin: resetToMin,
  6033. resetToMax: resetToMax,
  6034. setValue: setValue,
  6035. refresh: refresh
  6036. },
  6037. domModification: { styles: { position: 'relative' } }
  6038. };
  6039. };
  6040. var Slider = composite({
  6041. name: 'Slider',
  6042. configFields: SliderSchema,
  6043. partFields: SliderParts,
  6044. factory: sketch$9,
  6045. apis: {
  6046. setValue: function (apis, slider, value) {
  6047. apis.setValue(slider, value);
  6048. },
  6049. resetToMin: function (apis, slider) {
  6050. apis.resetToMin(slider);
  6051. },
  6052. resetToMax: function (apis, slider) {
  6053. apis.resetToMax(slider);
  6054. },
  6055. refresh: function (apis, slider) {
  6056. apis.refresh(slider);
  6057. }
  6058. }
  6059. });
  6060. var button = function (realm, clazz, makeItems, editor) {
  6061. return forToolbar(clazz, function () {
  6062. var items = makeItems();
  6063. realm.setContextToolbar([{
  6064. label: clazz + ' group',
  6065. items: items
  6066. }]);
  6067. }, {}, editor);
  6068. };
  6069. var BLACK = -1;
  6070. var makeSlider$1 = function (spec$1) {
  6071. var getColor = function (hue) {
  6072. if (hue < 0) {
  6073. return 'black';
  6074. } else if (hue > 360) {
  6075. return 'white';
  6076. } else {
  6077. return 'hsl(' + hue + ', 100%, 50%)';
  6078. }
  6079. };
  6080. var onInit = function (slider, thumb, spectrum, value) {
  6081. var color = getColor(value.x());
  6082. set$5(thumb.element, 'background-color', color);
  6083. };
  6084. var onChange = function (slider, thumb, value) {
  6085. var color = getColor(value.x());
  6086. set$5(thumb.element, 'background-color', color);
  6087. spec$1.onChange(slider, thumb, color);
  6088. };
  6089. return Slider.sketch({
  6090. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  6091. components: [
  6092. Slider.parts['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  6093. Slider.parts.spectrum({
  6094. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  6095. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  6096. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6097. }),
  6098. Slider.parts['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  6099. Slider.parts.thumb({
  6100. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6101. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6102. })
  6103. ],
  6104. onChange: onChange,
  6105. onDragStart: function (slider, thumb) {
  6106. Toggling.on(thumb);
  6107. },
  6108. onDragEnd: function (slider, thumb) {
  6109. Toggling.off(thumb);
  6110. },
  6111. onInit: onInit,
  6112. stepSize: 10,
  6113. model: {
  6114. mode: 'x',
  6115. minX: 0,
  6116. maxX: 360,
  6117. getInitialValue: function () {
  6118. return { x: spec$1.getInitialValue() };
  6119. }
  6120. },
  6121. sliderBehaviours: derive$2([orientation(Slider.refresh)])
  6122. });
  6123. };
  6124. var makeItems$1 = function (spec) {
  6125. return [makeSlider$1(spec)];
  6126. };
  6127. var sketch$8 = function (realm, editor) {
  6128. var spec = {
  6129. onChange: function (slider, thumb, color) {
  6130. editor.undoManager.transact(function () {
  6131. editor.formatter.apply('forecolor', { value: color });
  6132. editor.nodeChanged();
  6133. });
  6134. },
  6135. getInitialValue: constant$1(BLACK)
  6136. };
  6137. return button(realm, 'color-levels', function () {
  6138. return makeItems$1(spec);
  6139. }, editor);
  6140. };
  6141. var candidatesArray = [
  6142. '9px',
  6143. '10px',
  6144. '11px',
  6145. '12px',
  6146. '14px',
  6147. '16px',
  6148. '18px',
  6149. '20px',
  6150. '24px',
  6151. '32px',
  6152. '36px'
  6153. ];
  6154. var defaultSize = 'medium';
  6155. var defaultIndex = 2;
  6156. var indexToSize = function (index) {
  6157. return Optional.from(candidatesArray[index]);
  6158. };
  6159. var sizeToIndex = function (size) {
  6160. return findIndex$1(candidatesArray, function (v) {
  6161. return v === size;
  6162. });
  6163. };
  6164. var getRawOrComputed = function (isRoot, rawStart) {
  6165. var optStart = isElement(rawStart) ? Optional.some(rawStart) : parent(rawStart).filter(isElement);
  6166. return optStart.map(function (start) {
  6167. var inline = closest$2(start, function (elem) {
  6168. return getRaw(elem, 'font-size').isSome();
  6169. }, isRoot).bind(function (elem) {
  6170. return getRaw(elem, 'font-size');
  6171. });
  6172. return inline.getOrThunk(function () {
  6173. return get$8(start, 'font-size');
  6174. });
  6175. }).getOr('');
  6176. };
  6177. var getSize = function (editor) {
  6178. var node = editor.selection.getStart();
  6179. var elem = SugarElement.fromDom(node);
  6180. var root = SugarElement.fromDom(editor.getBody());
  6181. var isRoot = function (e) {
  6182. return eq(root, e);
  6183. };
  6184. var elemSize = getRawOrComputed(isRoot, elem);
  6185. return find$2(candidatesArray, function (size) {
  6186. return elemSize === size;
  6187. }).getOr(defaultSize);
  6188. };
  6189. var applySize = function (editor, value) {
  6190. var currentValue = getSize(editor);
  6191. if (currentValue !== value) {
  6192. editor.execCommand('fontSize', false, value);
  6193. }
  6194. };
  6195. var get$4 = function (editor) {
  6196. var size = getSize(editor);
  6197. return sizeToIndex(size).getOr(defaultIndex);
  6198. };
  6199. var apply = function (editor, index) {
  6200. indexToSize(index).each(function (size) {
  6201. applySize(editor, size);
  6202. });
  6203. };
  6204. var candidates = constant$1(candidatesArray);
  6205. var schema$9 = objOfOnly([
  6206. required$1('getInitialValue'),
  6207. required$1('onChange'),
  6208. required$1('category'),
  6209. required$1('sizes')
  6210. ]);
  6211. var sketch$7 = function (rawSpec) {
  6212. var spec$1 = asRawOrDie$1('SizeSlider', schema$9, rawSpec);
  6213. var isValidValue = function (valueIndex) {
  6214. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6215. };
  6216. var onChange = function (slider, thumb, valueIndex) {
  6217. var index = valueIndex.x();
  6218. if (isValidValue(index)) {
  6219. spec$1.onChange(index);
  6220. }
  6221. };
  6222. return Slider.sketch({
  6223. dom: {
  6224. tag: 'div',
  6225. classes: [
  6226. resolve('slider-' + spec$1.category + '-size-container'),
  6227. resolve('slider'),
  6228. resolve('slider-size-container')
  6229. ]
  6230. },
  6231. onChange: onChange,
  6232. onDragStart: function (slider, thumb) {
  6233. Toggling.on(thumb);
  6234. },
  6235. onDragEnd: function (slider, thumb) {
  6236. Toggling.off(thumb);
  6237. },
  6238. model: {
  6239. mode: 'x',
  6240. minX: 0,
  6241. maxX: spec$1.sizes.length - 1,
  6242. getInitialValue: function () {
  6243. return { x: spec$1.getInitialValue() };
  6244. }
  6245. },
  6246. stepSize: 1,
  6247. snapToGrid: true,
  6248. sliderBehaviours: derive$2([orientation(Slider.refresh)]),
  6249. components: [
  6250. Slider.parts.spectrum({
  6251. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6252. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  6253. }),
  6254. Slider.parts.thumb({
  6255. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6256. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6257. })
  6258. ]
  6259. });
  6260. };
  6261. var sizes = candidates();
  6262. var makeSlider = function (spec) {
  6263. return sketch$7({
  6264. onChange: spec.onChange,
  6265. sizes: sizes,
  6266. category: 'font',
  6267. getInitialValue: spec.getInitialValue
  6268. });
  6269. };
  6270. var makeItems = function (spec$1) {
  6271. return [
  6272. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6273. makeSlider(spec$1),
  6274. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6275. ];
  6276. };
  6277. var sketch$6 = function (realm, editor) {
  6278. var spec = {
  6279. onChange: function (value) {
  6280. apply(editor, value);
  6281. },
  6282. getInitialValue: function () {
  6283. return get$4(editor);
  6284. }
  6285. };
  6286. return button(realm, 'font-size', function () {
  6287. return makeItems(spec);
  6288. }, editor);
  6289. };
  6290. var record = function (spec) {
  6291. var uid = isSketchSpec$1(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento');
  6292. var get = function (anyInSystem) {
  6293. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6294. };
  6295. var getOpt = function (anyInSystem) {
  6296. return anyInSystem.getSystem().getByUid(uid).toOptional();
  6297. };
  6298. var asSpec = function () {
  6299. return __assign(__assign({}, spec), { uid: uid });
  6300. };
  6301. return {
  6302. get: get,
  6303. getOpt: getOpt,
  6304. asSpec: asSpec
  6305. };
  6306. };
  6307. var exports$1 = {}, module = { exports: exports$1 };
  6308. (function (define, exports, module, require) {
  6309. (function (global, factory) {
  6310. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  6311. }(this, function () {
  6312. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  6313. var promise = { exports: {} };
  6314. (function (module) {
  6315. (function (root) {
  6316. var setTimeoutFunc = setTimeout;
  6317. function noop() {
  6318. }
  6319. function bind(fn, thisArg) {
  6320. return function () {
  6321. fn.apply(thisArg, arguments);
  6322. };
  6323. }
  6324. function Promise(fn) {
  6325. if (typeof this !== 'object')
  6326. throw new TypeError('Promises must be constructed via new');
  6327. if (typeof fn !== 'function')
  6328. throw new TypeError('not a function');
  6329. this._state = 0;
  6330. this._handled = false;
  6331. this._value = undefined;
  6332. this._deferreds = [];
  6333. doResolve(fn, this);
  6334. }
  6335. function handle(self, deferred) {
  6336. while (self._state === 3) {
  6337. self = self._value;
  6338. }
  6339. if (self._state === 0) {
  6340. self._deferreds.push(deferred);
  6341. return;
  6342. }
  6343. self._handled = true;
  6344. Promise._immediateFn(function () {
  6345. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  6346. if (cb === null) {
  6347. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  6348. return;
  6349. }
  6350. var ret;
  6351. try {
  6352. ret = cb(self._value);
  6353. } catch (e) {
  6354. reject(deferred.promise, e);
  6355. return;
  6356. }
  6357. resolve(deferred.promise, ret);
  6358. });
  6359. }
  6360. function resolve(self, newValue) {
  6361. try {
  6362. if (newValue === self)
  6363. throw new TypeError('A promise cannot be resolved with itself.');
  6364. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6365. var then = newValue.then;
  6366. if (newValue instanceof Promise) {
  6367. self._state = 3;
  6368. self._value = newValue;
  6369. finale(self);
  6370. return;
  6371. } else if (typeof then === 'function') {
  6372. doResolve(bind(then, newValue), self);
  6373. return;
  6374. }
  6375. }
  6376. self._state = 1;
  6377. self._value = newValue;
  6378. finale(self);
  6379. } catch (e) {
  6380. reject(self, e);
  6381. }
  6382. }
  6383. function reject(self, newValue) {
  6384. self._state = 2;
  6385. self._value = newValue;
  6386. finale(self);
  6387. }
  6388. function finale(self) {
  6389. if (self._state === 2 && self._deferreds.length === 0) {
  6390. Promise._immediateFn(function () {
  6391. if (!self._handled) {
  6392. Promise._unhandledRejectionFn(self._value);
  6393. }
  6394. });
  6395. }
  6396. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  6397. handle(self, self._deferreds[i]);
  6398. }
  6399. self._deferreds = null;
  6400. }
  6401. function Handler(onFulfilled, onRejected, promise) {
  6402. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6403. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6404. this.promise = promise;
  6405. }
  6406. function doResolve(fn, self) {
  6407. var done = false;
  6408. try {
  6409. fn(function (value) {
  6410. if (done)
  6411. return;
  6412. done = true;
  6413. resolve(self, value);
  6414. }, function (reason) {
  6415. if (done)
  6416. return;
  6417. done = true;
  6418. reject(self, reason);
  6419. });
  6420. } catch (ex) {
  6421. if (done)
  6422. return;
  6423. done = true;
  6424. reject(self, ex);
  6425. }
  6426. }
  6427. Promise.prototype['catch'] = function (onRejected) {
  6428. return this.then(null, onRejected);
  6429. };
  6430. Promise.prototype.then = function (onFulfilled, onRejected) {
  6431. var prom = new this.constructor(noop);
  6432. handle(this, new Handler(onFulfilled, onRejected, prom));
  6433. return prom;
  6434. };
  6435. Promise.all = function (arr) {
  6436. var args = Array.prototype.slice.call(arr);
  6437. return new Promise(function (resolve, reject) {
  6438. if (args.length === 0)
  6439. return resolve([]);
  6440. var remaining = args.length;
  6441. function res(i, val) {
  6442. try {
  6443. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6444. var then = val.then;
  6445. if (typeof then === 'function') {
  6446. then.call(val, function (val) {
  6447. res(i, val);
  6448. }, reject);
  6449. return;
  6450. }
  6451. }
  6452. args[i] = val;
  6453. if (--remaining === 0) {
  6454. resolve(args);
  6455. }
  6456. } catch (ex) {
  6457. reject(ex);
  6458. }
  6459. }
  6460. for (var i = 0; i < args.length; i++) {
  6461. res(i, args[i]);
  6462. }
  6463. });
  6464. };
  6465. Promise.resolve = function (value) {
  6466. if (value && typeof value === 'object' && value.constructor === Promise) {
  6467. return value;
  6468. }
  6469. return new Promise(function (resolve) {
  6470. resolve(value);
  6471. });
  6472. };
  6473. Promise.reject = function (value) {
  6474. return new Promise(function (resolve, reject) {
  6475. reject(value);
  6476. });
  6477. };
  6478. Promise.race = function (values) {
  6479. return new Promise(function (resolve, reject) {
  6480. for (var i = 0, len = values.length; i < len; i++) {
  6481. values[i].then(resolve, reject);
  6482. }
  6483. });
  6484. };
  6485. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  6486. setImmediate(fn);
  6487. } : function (fn) {
  6488. setTimeoutFunc(fn, 0);
  6489. };
  6490. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  6491. if (typeof console !== 'undefined' && console) {
  6492. console.warn('Possible Unhandled Promise Rejection:', err);
  6493. }
  6494. };
  6495. Promise._setImmediateFn = function _setImmediateFn(fn) {
  6496. Promise._immediateFn = fn;
  6497. };
  6498. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  6499. Promise._unhandledRejectionFn = fn;
  6500. };
  6501. if (module.exports) {
  6502. module.exports = Promise;
  6503. } else if (!root.Promise) {
  6504. root.Promise = Promise;
  6505. }
  6506. }(commonjsGlobal));
  6507. }(promise));
  6508. var promisePolyfill = promise.exports;
  6509. var Global = function () {
  6510. if (typeof window !== 'undefined') {
  6511. return window;
  6512. } else {
  6513. return Function('return this;')();
  6514. }
  6515. }();
  6516. var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  6517. return promisePolyfill_1;
  6518. }));
  6519. }(undefined, exports$1, module));
  6520. var Promise$1 = module.exports.boltExport;
  6521. var blobToDataUri = function (blob) {
  6522. return new Promise$1(function (resolve) {
  6523. var reader = new FileReader();
  6524. reader.onloadend = function () {
  6525. resolve(reader.result);
  6526. };
  6527. reader.readAsDataURL(blob);
  6528. });
  6529. };
  6530. var blobToBase64$1 = function (blob) {
  6531. return blobToDataUri(blob).then(function (dataUri) {
  6532. return dataUri.split(',')[1];
  6533. });
  6534. };
  6535. var blobToBase64 = function (blob) {
  6536. return blobToBase64$1(blob);
  6537. };
  6538. var addImage = function (editor, blob) {
  6539. blobToBase64(blob).then(function (base64) {
  6540. editor.undoManager.transact(function () {
  6541. var cache = editor.editorUpload.blobCache;
  6542. var info = cache.create(generate$4('mceu'), blob, base64);
  6543. cache.add(info);
  6544. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6545. editor.insertContent(img);
  6546. });
  6547. });
  6548. };
  6549. var extractBlob = function (simulatedEvent) {
  6550. var event = simulatedEvent.event.raw;
  6551. var files = event.target.files || event.dataTransfer.files;
  6552. return Optional.from(files[0]);
  6553. };
  6554. var sketch$5 = function (editor) {
  6555. var pickerDom = {
  6556. tag: 'input',
  6557. attributes: {
  6558. accept: 'image/*',
  6559. type: 'file',
  6560. title: ''
  6561. },
  6562. styles: {
  6563. visibility: 'hidden',
  6564. position: 'absolute'
  6565. }
  6566. };
  6567. var memPicker = record({
  6568. dom: pickerDom,
  6569. events: derive$3([
  6570. cutter(click()),
  6571. run(change(), function (picker, simulatedEvent) {
  6572. extractBlob(simulatedEvent).each(function (blob) {
  6573. addImage(editor, blob);
  6574. });
  6575. })
  6576. ])
  6577. });
  6578. return Button.sketch({
  6579. dom: getToolbarIconButton('image', editor),
  6580. components: [memPicker.asSpec()],
  6581. action: function (button) {
  6582. var picker = memPicker.get(button);
  6583. picker.element.dom.click();
  6584. }
  6585. });
  6586. };
  6587. var get$3 = function (element) {
  6588. return element.dom.textContent;
  6589. };
  6590. var set$3 = function (element, value) {
  6591. element.dom.textContent = value;
  6592. };
  6593. var isNotEmpty = function (val) {
  6594. return val.length > 0;
  6595. };
  6596. var defaultToEmpty = function (str) {
  6597. return str === undefined || str === null ? '' : str;
  6598. };
  6599. var noLink = function (editor) {
  6600. var text = editor.selection.getContent({ format: 'text' });
  6601. return {
  6602. url: '',
  6603. text: text,
  6604. title: '',
  6605. target: '',
  6606. link: Optional.none()
  6607. };
  6608. };
  6609. var fromLink = function (link) {
  6610. var text = get$3(link);
  6611. var url = get$b(link, 'href');
  6612. var title = get$b(link, 'title');
  6613. var target = get$b(link, 'target');
  6614. return {
  6615. url: defaultToEmpty(url),
  6616. text: text !== url ? defaultToEmpty(text) : '',
  6617. title: defaultToEmpty(title),
  6618. target: defaultToEmpty(target),
  6619. link: Optional.some(link)
  6620. };
  6621. };
  6622. var getInfo = function (editor) {
  6623. return query(editor).fold(function () {
  6624. return noLink(editor);
  6625. }, function (link) {
  6626. return fromLink(link);
  6627. });
  6628. };
  6629. var wasSimple = function (link) {
  6630. var prevHref = get$b(link, 'href');
  6631. var prevText = get$3(link);
  6632. return prevHref === prevText;
  6633. };
  6634. var getTextToApply = function (link, url, info) {
  6635. return info.text.toOptional().filter(isNotEmpty).fold(function () {
  6636. return wasSimple(link) ? Optional.some(url) : Optional.none();
  6637. }, Optional.some);
  6638. };
  6639. var unlinkIfRequired = function (editor, info) {
  6640. var activeLink = info.link.bind(identity);
  6641. activeLink.each(function (_link) {
  6642. editor.execCommand('unlink');
  6643. });
  6644. };
  6645. var getAttrs = function (url, info) {
  6646. var attrs = {};
  6647. attrs.href = url;
  6648. info.title.toOptional().filter(isNotEmpty).each(function (title) {
  6649. attrs.title = title;
  6650. });
  6651. info.target.toOptional().filter(isNotEmpty).each(function (target) {
  6652. attrs.target = target;
  6653. });
  6654. return attrs;
  6655. };
  6656. var applyInfo = function (editor, info) {
  6657. info.url.toOptional().filter(isNotEmpty).fold(function () {
  6658. unlinkIfRequired(editor, info);
  6659. }, function (url) {
  6660. var attrs = getAttrs(url, info);
  6661. var activeLink = info.link.bind(identity);
  6662. activeLink.fold(function () {
  6663. var text = info.text.toOptional().filter(isNotEmpty).getOr(url);
  6664. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6665. }, function (link) {
  6666. var text = getTextToApply(link, url, info);
  6667. setAll$1(link, attrs);
  6668. text.each(function (newText) {
  6669. set$3(link, newText);
  6670. });
  6671. });
  6672. });
  6673. };
  6674. var query = function (editor) {
  6675. var start = SugarElement.fromDom(editor.selection.getStart());
  6676. return closest$1(start, 'a');
  6677. };
  6678. var platform = detect$1();
  6679. var preserve$1 = function (f, editor) {
  6680. var rng = editor.selection.getRng();
  6681. f();
  6682. editor.selection.setRng(rng);
  6683. };
  6684. var forAndroid = function (editor, f) {
  6685. var wrapper = platform.os.isAndroid() ? preserve$1 : apply$1;
  6686. wrapper(f, editor);
  6687. };
  6688. var events$4 = function (name, eventHandlers) {
  6689. var events = derive$3(eventHandlers);
  6690. return create$5({
  6691. fields: [required$1('enabled')],
  6692. name: name,
  6693. active: { events: constant$1(events) }
  6694. });
  6695. };
  6696. var config = function (name, eventHandlers) {
  6697. var me = events$4(name, eventHandlers);
  6698. return {
  6699. key: name,
  6700. value: {
  6701. config: {},
  6702. me: me,
  6703. configAsRaw: constant$1({}),
  6704. initialConfig: {},
  6705. state: NoState
  6706. }
  6707. };
  6708. };
  6709. var getCurrent = function (component, composeConfig, _composeState) {
  6710. return composeConfig.find(component);
  6711. };
  6712. var ComposeApis = /*#__PURE__*/Object.freeze({
  6713. __proto__: null,
  6714. getCurrent: getCurrent
  6715. });
  6716. var ComposeSchema = [required$1('find')];
  6717. var Composing = create$5({
  6718. fields: ComposeSchema,
  6719. name: 'composing',
  6720. apis: ComposeApis
  6721. });
  6722. var factory$4 = function (detail) {
  6723. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6724. return {
  6725. uid: detail.uid,
  6726. dom: __assign({
  6727. tag: 'div',
  6728. attributes: __assign({ role: 'presentation' }, attributes)
  6729. }, domWithoutAttributes),
  6730. components: detail.components,
  6731. behaviours: get$6(detail.containerBehaviours),
  6732. events: detail.events,
  6733. domModification: detail.domModification,
  6734. eventOrder: detail.eventOrder
  6735. };
  6736. };
  6737. var Container = single({
  6738. name: 'Container',
  6739. factory: factory$4,
  6740. configFields: [
  6741. defaulted('components', []),
  6742. field$1('containerBehaviours', []),
  6743. defaulted('events', {}),
  6744. defaulted('domModification', {}),
  6745. defaulted('eventOrder', {})
  6746. ]
  6747. });
  6748. var factory$3 = function (detail) {
  6749. return {
  6750. uid: detail.uid,
  6751. dom: detail.dom,
  6752. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6753. Representing.config({
  6754. store: {
  6755. mode: 'memory',
  6756. initialValue: detail.getInitialValue()
  6757. }
  6758. }),
  6759. Composing.config({ find: Optional.some })
  6760. ]),
  6761. events: derive$3([runOnAttached(function (component, _simulatedEvent) {
  6762. Representing.setValue(component, detail.getInitialValue());
  6763. })])
  6764. };
  6765. };
  6766. var DataField = single({
  6767. name: 'DataField',
  6768. factory: factory$3,
  6769. configFields: [
  6770. required$1('uid'),
  6771. required$1('dom'),
  6772. required$1('getInitialValue'),
  6773. SketchBehaviours.field('dataBehaviours', [
  6774. Representing,
  6775. Composing
  6776. ])
  6777. ]
  6778. });
  6779. var get$2 = function (element) {
  6780. return element.dom.value;
  6781. };
  6782. var set$2 = function (element, value) {
  6783. if (value === undefined) {
  6784. throw new Error('Value.set was undefined');
  6785. }
  6786. element.dom.value = value;
  6787. };
  6788. var schema$8 = constant$1([
  6789. option('data'),
  6790. defaulted('inputAttributes', {}),
  6791. defaulted('inputStyles', {}),
  6792. defaulted('tag', 'input'),
  6793. defaulted('inputClasses', []),
  6794. onHandler('onSetValue'),
  6795. defaulted('styles', {}),
  6796. defaulted('eventOrder', {}),
  6797. field$1('inputBehaviours', [
  6798. Representing,
  6799. Focusing
  6800. ]),
  6801. defaulted('selectOnFocus', true)
  6802. ]);
  6803. var focusBehaviours = function (detail) {
  6804. return derive$2([Focusing.config({
  6805. onFocus: !detail.selectOnFocus ? noop : function (component) {
  6806. var input = component.element;
  6807. var value = get$2(input);
  6808. input.dom.setSelectionRange(0, value.length);
  6809. }
  6810. })]);
  6811. };
  6812. var behaviours = function (detail) {
  6813. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6814. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  6815. return { initialValue: data };
  6816. }).getOr({})), {
  6817. getValue: function (input) {
  6818. return get$2(input.element);
  6819. },
  6820. setValue: function (input, data) {
  6821. var current = get$2(input.element);
  6822. if (current !== data) {
  6823. set$2(input.element, data);
  6824. }
  6825. }
  6826. }),
  6827. onSetValue: detail.onSetValue
  6828. })]));
  6829. };
  6830. var dom = function (detail) {
  6831. return {
  6832. tag: detail.tag,
  6833. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6834. styles: detail.inputStyles,
  6835. classes: detail.inputClasses
  6836. };
  6837. };
  6838. var factory$2 = function (detail, _spec) {
  6839. return {
  6840. uid: detail.uid,
  6841. dom: dom(detail),
  6842. components: [],
  6843. behaviours: behaviours(detail),
  6844. eventOrder: detail.eventOrder
  6845. };
  6846. };
  6847. var Input = single({
  6848. name: 'Input',
  6849. configFields: schema$8(),
  6850. factory: factory$2
  6851. });
  6852. var exhibit$2 = function (base, tabConfig) {
  6853. return nu$3({
  6854. attributes: wrapAll([{
  6855. key: tabConfig.tabAttr,
  6856. value: 'true'
  6857. }])
  6858. });
  6859. };
  6860. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6861. __proto__: null,
  6862. exhibit: exhibit$2
  6863. });
  6864. var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  6865. var Tabstopping = create$5({
  6866. fields: TabstopSchema,
  6867. name: 'tabstopping',
  6868. active: ActiveTabstopping
  6869. });
  6870. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6871. var clearInputBehaviour = 'input-clearing';
  6872. var field = function (name, placeholder) {
  6873. var inputSpec = record(Input.sketch({
  6874. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6875. onSetValue: function (input, _data) {
  6876. emit(input, input$1());
  6877. },
  6878. inputBehaviours: derive$2([
  6879. Composing.config({ find: Optional.some }),
  6880. Tabstopping.config({}),
  6881. Keying.config({ mode: 'execution' })
  6882. ]),
  6883. selectOnFocus: false
  6884. }));
  6885. var buttonSpec = record(Button.sketch({
  6886. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6887. action: function (button) {
  6888. var input = inputSpec.get(button);
  6889. Representing.setValue(input, '');
  6890. }
  6891. }));
  6892. return {
  6893. name: name,
  6894. spec: Container.sketch({
  6895. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6896. components: [
  6897. inputSpec.asSpec(),
  6898. buttonSpec.asSpec()
  6899. ],
  6900. containerBehaviours: derive$2([
  6901. Toggling.config({ toggleClass: resolve('input-container-empty') }),
  6902. Composing.config({
  6903. find: function (comp) {
  6904. return Optional.some(inputSpec.get(comp));
  6905. }
  6906. }),
  6907. config(clearInputBehaviour, [run(input$1(), function (iContainer) {
  6908. var input = inputSpec.get(iContainer);
  6909. var val = Representing.getValue(input);
  6910. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6911. f(iContainer);
  6912. })])
  6913. ])
  6914. })
  6915. };
  6916. };
  6917. var hidden = function (name) {
  6918. return {
  6919. name: name,
  6920. spec: DataField.sketch({
  6921. dom: {
  6922. tag: 'span',
  6923. styles: { display: 'none' }
  6924. },
  6925. getInitialValue: function () {
  6926. return Optional.none();
  6927. }
  6928. })
  6929. };
  6930. };
  6931. var nativeDisabled = [
  6932. 'input',
  6933. 'button',
  6934. 'textarea',
  6935. 'select'
  6936. ];
  6937. var onLoad = function (component, disableConfig, disableState) {
  6938. var f = disableConfig.disabled() ? disable : enable;
  6939. f(component, disableConfig);
  6940. };
  6941. var hasNative = function (component, config) {
  6942. return config.useNative === true && contains$1(nativeDisabled, name$1(component.element));
  6943. };
  6944. var nativeIsDisabled = function (component) {
  6945. return has$1(component.element, 'disabled');
  6946. };
  6947. var nativeDisable = function (component) {
  6948. set$8(component.element, 'disabled', 'disabled');
  6949. };
  6950. var nativeEnable = function (component) {
  6951. remove$6(component.element, 'disabled');
  6952. };
  6953. var ariaIsDisabled = function (component) {
  6954. return get$b(component.element, 'aria-disabled') === 'true';
  6955. };
  6956. var ariaDisable = function (component) {
  6957. set$8(component.element, 'aria-disabled', 'true');
  6958. };
  6959. var ariaEnable = function (component) {
  6960. set$8(component.element, 'aria-disabled', 'false');
  6961. };
  6962. var disable = function (component, disableConfig, _disableState) {
  6963. disableConfig.disableClass.each(function (disableClass) {
  6964. add$1(component.element, disableClass);
  6965. });
  6966. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6967. f(component);
  6968. disableConfig.onDisabled(component);
  6969. };
  6970. var enable = function (component, disableConfig, _disableState) {
  6971. disableConfig.disableClass.each(function (disableClass) {
  6972. remove$3(component.element, disableClass);
  6973. });
  6974. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6975. f(component);
  6976. disableConfig.onEnabled(component);
  6977. };
  6978. var isDisabled = function (component, disableConfig) {
  6979. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6980. };
  6981. var set$1 = function (component, disableConfig, disableState, disabled) {
  6982. var f = disabled ? disable : enable;
  6983. f(component, disableConfig);
  6984. };
  6985. var DisableApis = /*#__PURE__*/Object.freeze({
  6986. __proto__: null,
  6987. enable: enable,
  6988. disable: disable,
  6989. isDisabled: isDisabled,
  6990. onLoad: onLoad,
  6991. set: set$1
  6992. });
  6993. var exhibit$1 = function (base, disableConfig) {
  6994. return nu$3({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6995. };
  6996. var events$3 = function (disableConfig, disableState) {
  6997. return derive$3([
  6998. abort(execute$5(), function (component, _simulatedEvent) {
  6999. return isDisabled(component, disableConfig);
  7000. }),
  7001. loadEvent(disableConfig, disableState, onLoad)
  7002. ]);
  7003. };
  7004. var ActiveDisable = /*#__PURE__*/Object.freeze({
  7005. __proto__: null,
  7006. exhibit: exhibit$1,
  7007. events: events$3
  7008. });
  7009. var DisableSchema = [
  7010. defaultedFunction('disabled', never),
  7011. defaulted('useNative', true),
  7012. option('disableClass'),
  7013. onHandler('onDisabled'),
  7014. onHandler('onEnabled')
  7015. ];
  7016. var Disabling = create$5({
  7017. fields: DisableSchema,
  7018. name: 'disabling',
  7019. active: ActiveDisable,
  7020. apis: DisableApis
  7021. });
  7022. var owner$1 = 'form';
  7023. var schema$7 = [field$1('formBehaviours', [Representing])];
  7024. var getPartName = function (name) {
  7025. return '<alloy.field.' + name + '>';
  7026. };
  7027. var sketch$4 = function (fSpec) {
  7028. var parts = function () {
  7029. var record = [];
  7030. var field = function (name, config) {
  7031. record.push(name);
  7032. return generateOne(owner$1, getPartName(name), config);
  7033. };
  7034. return {
  7035. field: field,
  7036. record: constant$1(record)
  7037. };
  7038. }();
  7039. var spec = fSpec(parts);
  7040. var partNames = parts.record();
  7041. var fieldParts = map$2(partNames, function (n) {
  7042. return required({
  7043. name: n,
  7044. pname: getPartName(n)
  7045. });
  7046. });
  7047. return composite$1(owner$1, schema$7, fieldParts, make$4, spec);
  7048. };
  7049. var toResult = function (o, e) {
  7050. return o.fold(function () {
  7051. return Result.error(e);
  7052. }, Result.value);
  7053. };
  7054. var make$4 = function (detail, components) {
  7055. return {
  7056. uid: detail.uid,
  7057. dom: detail.dom,
  7058. components: components,
  7059. behaviours: augment(detail.formBehaviours, [Representing.config({
  7060. store: {
  7061. mode: 'manual',
  7062. getValue: function (form) {
  7063. var resPs = getAllParts(form, detail);
  7064. return map$1(resPs, function (resPThunk, pName) {
  7065. return resPThunk().bind(function (v) {
  7066. var opt = Composing.getCurrent(v);
  7067. return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  7068. }).map(Representing.getValue);
  7069. });
  7070. },
  7071. setValue: function (form, values) {
  7072. each(values, function (newValue, key) {
  7073. getPart(form, detail, key).each(function (wrapper) {
  7074. Composing.getCurrent(wrapper).each(function (field) {
  7075. Representing.setValue(field, newValue);
  7076. });
  7077. });
  7078. });
  7079. }
  7080. }
  7081. })]),
  7082. apis: {
  7083. getField: function (form, key) {
  7084. return getPart(form, detail, key).bind(Composing.getCurrent);
  7085. }
  7086. }
  7087. };
  7088. };
  7089. var Form = {
  7090. getField: makeApi(function (apis, component, key) {
  7091. return apis.getField(component, key);
  7092. }),
  7093. sketch: sketch$4
  7094. };
  7095. var SWIPING_LEFT = 1;
  7096. var SWIPING_RIGHT = -1;
  7097. var SWIPING_NONE = 0;
  7098. var init$3 = function (xValue) {
  7099. return {
  7100. xValue: xValue,
  7101. points: []
  7102. };
  7103. };
  7104. var move = function (model, xValue) {
  7105. if (xValue === model.xValue) {
  7106. return model;
  7107. }
  7108. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7109. var newPoint = {
  7110. direction: currentDirection,
  7111. xValue: xValue
  7112. };
  7113. var priorPoints = function () {
  7114. if (model.points.length === 0) {
  7115. return [];
  7116. } else {
  7117. var prev = model.points[model.points.length - 1];
  7118. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7119. }
  7120. }();
  7121. return {
  7122. xValue: xValue,
  7123. points: priorPoints.concat([newPoint])
  7124. };
  7125. };
  7126. var complete = function (model) {
  7127. if (model.points.length === 0) {
  7128. return SWIPING_NONE;
  7129. } else {
  7130. var firstDirection = model.points[0].direction;
  7131. var lastDirection = model.points[model.points.length - 1].direction;
  7132. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7133. }
  7134. };
  7135. var sketch$3 = function (rawSpec) {
  7136. var navigateEvent = 'navigateEvent';
  7137. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7138. var formAdhocEvents = 'form-events';
  7139. var schema = objOf([
  7140. required$1('fields'),
  7141. defaulted('maxFieldIndex', rawSpec.fields.length - 1),
  7142. required$1('onExecute'),
  7143. required$1('getInitialValue'),
  7144. customField('state', function () {
  7145. return {
  7146. dialogSwipeState: value(),
  7147. currentScreen: Cell(0)
  7148. };
  7149. })
  7150. ]);
  7151. var spec$1 = asRawOrDie$1('SerialisedDialog', schema, rawSpec);
  7152. var navigationButton = function (direction, directionName, enabled) {
  7153. return Button.sketch({
  7154. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7155. action: function (button) {
  7156. emitWith(button, navigateEvent, { direction: direction });
  7157. },
  7158. buttonBehaviours: derive$2([Disabling.config({
  7159. disableClass: resolve('toolbar-navigation-disabled'),
  7160. disabled: function () {
  7161. return !enabled;
  7162. }
  7163. })])
  7164. });
  7165. };
  7166. var reposition = function (dialog, message) {
  7167. descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7168. set$5(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  7169. });
  7170. };
  7171. var navigate = function (dialog, direction) {
  7172. var screens = descendants(dialog.element, '.' + resolve('serialised-dialog-screen'));
  7173. descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7174. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  7175. getRaw(parent, 'left').each(function (left) {
  7176. var currentLeft = parseInt(left, 10);
  7177. var w = get$5(screens[0]);
  7178. set$5(parent, 'left', currentLeft - direction * w + 'px');
  7179. });
  7180. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  7181. }
  7182. });
  7183. };
  7184. var focusInput = function (dialog) {
  7185. var inputs = descendants(dialog.element, 'input');
  7186. var optInput = Optional.from(inputs[spec$1.state.currentScreen.get()]);
  7187. optInput.each(function (input) {
  7188. dialog.getSystem().getByDom(input).each(function (inputComp) {
  7189. dispatchFocus(dialog, inputComp.element);
  7190. });
  7191. });
  7192. var dotitems = memDots.get(dialog);
  7193. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  7194. };
  7195. var resetState = function () {
  7196. spec$1.state.currentScreen.set(0);
  7197. spec$1.state.dialogSwipeState.clear();
  7198. };
  7199. var memForm = record(Form.sketch(function (parts) {
  7200. return {
  7201. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  7202. components: [Container.sketch({
  7203. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  7204. components: map$2(spec$1.fields, function (field, i) {
  7205. return i <= spec$1.maxFieldIndex ? Container.sketch({
  7206. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  7207. components: [
  7208. navigationButton(-1, 'previous', i > 0),
  7209. parts.field(field.name, field.spec),
  7210. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  7211. ]
  7212. }) : parts.field(field.name, field.spec);
  7213. })
  7214. })],
  7215. formBehaviours: derive$2([
  7216. orientation(function (dialog, message) {
  7217. reposition(dialog, message);
  7218. }),
  7219. Keying.config({
  7220. mode: 'special',
  7221. focusIn: function (dialog, _specialInfo) {
  7222. focusInput(dialog);
  7223. },
  7224. onTab: function (dialog, _specialInfo) {
  7225. navigate(dialog, +1);
  7226. return Optional.some(true);
  7227. },
  7228. onShiftTab: function (dialog, _specialInfo) {
  7229. navigate(dialog, -1);
  7230. return Optional.some(true);
  7231. }
  7232. }),
  7233. config(formAdhocEvents, [
  7234. runOnAttached(function (dialog, _simulatedEvent) {
  7235. resetState();
  7236. var dotitems = memDots.get(dialog);
  7237. Highlighting.highlightFirst(dotitems);
  7238. spec$1.getInitialValue(dialog).each(function (v) {
  7239. Representing.setValue(dialog, v);
  7240. });
  7241. }),
  7242. runOnExecute(spec$1.onExecute),
  7243. run(transitionend(), function (dialog, simulatedEvent) {
  7244. var event = simulatedEvent.event;
  7245. if (event.raw.propertyName === 'left') {
  7246. focusInput(dialog);
  7247. }
  7248. }),
  7249. run(navigateEvent, function (dialog, simulatedEvent) {
  7250. var event = simulatedEvent.event;
  7251. var direction = event.direction;
  7252. navigate(dialog, direction);
  7253. })
  7254. ])
  7255. ])
  7256. };
  7257. }));
  7258. var memDots = record({
  7259. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7260. behaviours: derive$2([Highlighting.config({
  7261. highlightClass: resolve('dot-active'),
  7262. itemClass: resolve('dot-item')
  7263. })]),
  7264. components: bind$3(spec$1.fields, function (_f, i) {
  7265. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7266. })
  7267. });
  7268. return {
  7269. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7270. components: [
  7271. memForm.asSpec(),
  7272. memDots.asSpec()
  7273. ],
  7274. behaviours: derive$2([
  7275. Keying.config({
  7276. mode: 'special',
  7277. focusIn: function (wrapper) {
  7278. var form = memForm.get(wrapper);
  7279. Keying.focusIn(form);
  7280. }
  7281. }),
  7282. config(wrapperAdhocEvents, [
  7283. run(touchstart(), function (_wrapper, simulatedEvent) {
  7284. var event = simulatedEvent.event;
  7285. spec$1.state.dialogSwipeState.set(init$3(event.raw.touches[0].clientX));
  7286. }),
  7287. run(touchmove(), function (_wrapper, simulatedEvent) {
  7288. var event = simulatedEvent.event;
  7289. spec$1.state.dialogSwipeState.on(function (state) {
  7290. simulatedEvent.event.prevent();
  7291. spec$1.state.dialogSwipeState.set(move(state, event.raw.touches[0].clientX));
  7292. });
  7293. }),
  7294. run(touchend(), function (wrapper, _simulatedEvent) {
  7295. spec$1.state.dialogSwipeState.on(function (state) {
  7296. var dialog = memForm.get(wrapper);
  7297. var direction = -1 * complete(state);
  7298. navigate(dialog, direction);
  7299. });
  7300. })
  7301. ])
  7302. ])
  7303. };
  7304. };
  7305. var getGroups = cached(function (realm, editor) {
  7306. return [{
  7307. label: 'the link group',
  7308. items: [sketch$3({
  7309. fields: [
  7310. field('url', 'Type or paste URL'),
  7311. field('text', 'Link text'),
  7312. field('title', 'Link title'),
  7313. field('target', 'Link target'),
  7314. hidden('link')
  7315. ],
  7316. maxFieldIndex: [
  7317. 'url',
  7318. 'text',
  7319. 'title',
  7320. 'target'
  7321. ].length - 1,
  7322. getInitialValue: function () {
  7323. return Optional.some(getInfo(editor));
  7324. },
  7325. onExecute: function (dialog, _simulatedEvent) {
  7326. var info = Representing.getValue(dialog);
  7327. applyInfo(editor, info);
  7328. realm.restoreToolbar();
  7329. editor.focus();
  7330. }
  7331. })]
  7332. }];
  7333. });
  7334. var sketch$2 = function (realm, editor) {
  7335. return forToolbarStateAction(editor, 'link', 'link', function () {
  7336. var groups = getGroups(realm, editor);
  7337. realm.setContextToolbar(groups);
  7338. forAndroid(editor, function () {
  7339. realm.focusToolbar();
  7340. });
  7341. query(editor).each(function (link) {
  7342. editor.selection.select(link.dom);
  7343. });
  7344. });
  7345. };
  7346. var isRecursive = function (component, originator, target) {
  7347. return eq(originator, component.element) && !eq(originator, target);
  7348. };
  7349. var events$2 = derive$3([can(focus$4(), function (component, simulatedEvent) {
  7350. var event = simulatedEvent.event;
  7351. var originator = event.originator;
  7352. var target = event.target;
  7353. if (isRecursive(component, originator, target)) {
  7354. console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  7355. return false;
  7356. } else {
  7357. return true;
  7358. }
  7359. })]);
  7360. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7361. __proto__: null,
  7362. events: events$2
  7363. });
  7364. var make$3 = identity;
  7365. var NoContextApi = function (getComp) {
  7366. var getMessage = function (event) {
  7367. return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  7368. };
  7369. var fail = function (event) {
  7370. return function () {
  7371. throw new Error(getMessage(event));
  7372. };
  7373. };
  7374. var warn = function (event) {
  7375. return function () {
  7376. console.warn(getMessage(event));
  7377. };
  7378. };
  7379. return {
  7380. debugInfo: constant$1('fake'),
  7381. triggerEvent: warn('triggerEvent'),
  7382. triggerFocus: warn('triggerFocus'),
  7383. triggerEscape: warn('triggerEscape'),
  7384. broadcast: warn('broadcast'),
  7385. broadcastOn: warn('broadcastOn'),
  7386. broadcastEvent: warn('broadcastEvent'),
  7387. build: fail('build'),
  7388. addToWorld: fail('addToWorld'),
  7389. removeFromWorld: fail('removeFromWorld'),
  7390. addToGui: fail('addToGui'),
  7391. removeFromGui: fail('removeFromGui'),
  7392. getByUid: fail('getByUid'),
  7393. getByDom: fail('getByDom'),
  7394. isConnected: never
  7395. };
  7396. };
  7397. var singleton = NoContextApi();
  7398. var generateFrom$1 = function (spec, all) {
  7399. var schema = map$2(all, function (a) {
  7400. return optionObjOf(a.name(), [
  7401. required$1('config'),
  7402. defaulted('state', NoState)
  7403. ]);
  7404. });
  7405. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7406. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7407. }, identity);
  7408. return {
  7409. list: all,
  7410. data: map$1(validated, function (optBlobThunk) {
  7411. var output = optBlobThunk.map(function (blob) {
  7412. return {
  7413. config: blob.config,
  7414. state: blob.state.init(blob.config)
  7415. };
  7416. });
  7417. return constant$1(output);
  7418. })
  7419. };
  7420. };
  7421. var getBehaviours$1 = function (bData) {
  7422. return bData.list;
  7423. };
  7424. var getData = function (bData) {
  7425. return bData.data;
  7426. };
  7427. var byInnerKey = function (data, tuple) {
  7428. var r = {};
  7429. each(data, function (detail, key) {
  7430. each(detail, function (value, indexKey) {
  7431. var chain = get$c(r, indexKey).getOr([]);
  7432. r[indexKey] = chain.concat([tuple(key, value)]);
  7433. });
  7434. });
  7435. return r;
  7436. };
  7437. var combine$1 = function (info, baseMod, behaviours, base) {
  7438. var modsByBehaviour = __assign({}, baseMod);
  7439. each$1(behaviours, function (behaviour) {
  7440. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7441. });
  7442. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  7443. return {
  7444. name: name,
  7445. modification: modification
  7446. };
  7447. });
  7448. var combineObjects = function (objects) {
  7449. return foldr(objects, function (b, a) {
  7450. return __assign(__assign({}, a.modification), b);
  7451. }, {});
  7452. };
  7453. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7454. return a.modification.concat(b);
  7455. }, []);
  7456. var combinedAttributes = combineObjects(byAspect.attributes);
  7457. var combinedStyles = combineObjects(byAspect.styles);
  7458. return nu$3({
  7459. classes: combinedClasses,
  7460. attributes: combinedAttributes,
  7461. styles: combinedStyles
  7462. });
  7463. };
  7464. var sortKeys = function (label, keyName, array, order) {
  7465. try {
  7466. var sorted = sort(array, function (a, b) {
  7467. var aKey = a[keyName];
  7468. var bKey = b[keyName];
  7469. var aIndex = order.indexOf(aKey);
  7470. var bIndex = order.indexOf(bKey);
  7471. if (aIndex === -1) {
  7472. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7473. }
  7474. if (bIndex === -1) {
  7475. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7476. }
  7477. if (aIndex < bIndex) {
  7478. return -1;
  7479. } else if (bIndex < aIndex) {
  7480. return 1;
  7481. } else {
  7482. return 0;
  7483. }
  7484. });
  7485. return Result.value(sorted);
  7486. } catch (err) {
  7487. return Result.error([err]);
  7488. }
  7489. };
  7490. var uncurried = function (handler, purpose) {
  7491. return {
  7492. handler: handler,
  7493. purpose: purpose
  7494. };
  7495. };
  7496. var curried = function (handler, purpose) {
  7497. return {
  7498. cHandler: handler,
  7499. purpose: purpose
  7500. };
  7501. };
  7502. var curryArgs = function (descHandler, extraArgs) {
  7503. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  7504. };
  7505. var getCurried = function (descHandler) {
  7506. return descHandler.cHandler;
  7507. };
  7508. var behaviourTuple = function (name, handler) {
  7509. return {
  7510. name: name,
  7511. handler: handler
  7512. };
  7513. };
  7514. var nameToHandlers = function (behaviours, info) {
  7515. var r = {};
  7516. each$1(behaviours, function (behaviour) {
  7517. r[behaviour.name()] = behaviour.handlers(info);
  7518. });
  7519. return r;
  7520. };
  7521. var groupByEvents = function (info, behaviours, base) {
  7522. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7523. return byInnerKey(behaviourEvents, behaviourTuple);
  7524. };
  7525. var combine = function (info, eventOrder, behaviours, base) {
  7526. var byEventName = groupByEvents(info, behaviours, base);
  7527. return combineGroups(byEventName, eventOrder);
  7528. };
  7529. var assemble = function (rawHandler) {
  7530. var handler = read$1(rawHandler);
  7531. return function (component, simulatedEvent) {
  7532. var rest = [];
  7533. for (var _i = 2; _i < arguments.length; _i++) {
  7534. rest[_i - 2] = arguments[_i];
  7535. }
  7536. var args = [
  7537. component,
  7538. simulatedEvent
  7539. ].concat(rest);
  7540. if (handler.abort.apply(undefined, args)) {
  7541. simulatedEvent.stop();
  7542. } else if (handler.can.apply(undefined, args)) {
  7543. handler.run.apply(undefined, args);
  7544. }
  7545. };
  7546. };
  7547. var missingOrderError = function (eventName, tuples) {
  7548. 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$2(tuples, function (c) {
  7549. return c.name;
  7550. }), null, 2)]);
  7551. };
  7552. var fuse = function (tuples, eventOrder, eventName) {
  7553. var order = eventOrder[eventName];
  7554. if (!order) {
  7555. return missingOrderError(eventName, tuples);
  7556. } else {
  7557. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7558. var handlers = map$2(sortedTuples, function (tuple) {
  7559. return tuple.handler;
  7560. });
  7561. return fuse$1(handlers);
  7562. });
  7563. }
  7564. };
  7565. var combineGroups = function (byEventName, eventOrder) {
  7566. var r = mapToArray(byEventName, function (tuples, eventName) {
  7567. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  7568. return combined.map(function (handler) {
  7569. var assembled = assemble(handler);
  7570. var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) {
  7571. return exists(tuples, function (t) {
  7572. return t.name === o;
  7573. });
  7574. }).join(' > ') : tuples[0].name;
  7575. return wrap(eventName, uncurried(assembled, purpose));
  7576. });
  7577. });
  7578. return consolidate(r, {});
  7579. };
  7580. var _a;
  7581. var baseBehaviour = 'alloy.base.behaviour';
  7582. var schema$6 = objOf([
  7583. field$2('dom', 'dom', required$2(), objOf([
  7584. required$1('tag'),
  7585. defaulted('styles', {}),
  7586. defaulted('classes', []),
  7587. defaulted('attributes', {}),
  7588. option('value'),
  7589. option('innerHtml')
  7590. ])),
  7591. required$1('components'),
  7592. required$1('uid'),
  7593. defaulted('events', {}),
  7594. defaulted('apis', {}),
  7595. field$2('eventOrder', 'eventOrder', mergeWith((_a = {}, _a[execute$5()] = [
  7596. 'disabling',
  7597. baseBehaviour,
  7598. 'toggling',
  7599. 'typeaheadevents'
  7600. ], _a[focus$4()] = [
  7601. baseBehaviour,
  7602. 'focusing',
  7603. 'keying'
  7604. ], _a[systemInit()] = [
  7605. baseBehaviour,
  7606. 'disabling',
  7607. 'toggling',
  7608. 'representing'
  7609. ], _a[input$1()] = [
  7610. baseBehaviour,
  7611. 'representing',
  7612. 'streaming',
  7613. 'invalidating'
  7614. ], _a[detachedFromDom()] = [
  7615. baseBehaviour,
  7616. 'representing',
  7617. 'item-events',
  7618. 'tooltipping'
  7619. ], _a[mousedown()] = [
  7620. 'focusing',
  7621. baseBehaviour,
  7622. 'item-type-events'
  7623. ], _a[touchstart()] = [
  7624. 'focusing',
  7625. baseBehaviour,
  7626. 'item-type-events'
  7627. ], _a[mouseover()] = [
  7628. 'item-type-events',
  7629. 'tooltipping'
  7630. ], _a[receive$1()] = [
  7631. 'receiving',
  7632. 'reflecting',
  7633. 'tooltipping'
  7634. ], _a)), anyValue()),
  7635. option('domModification')
  7636. ]);
  7637. var toInfo = function (spec) {
  7638. return asRaw('custom.definition', schema$6, spec);
  7639. };
  7640. var toDefinition = function (detail) {
  7641. return __assign(__assign({}, detail.dom), {
  7642. uid: detail.uid,
  7643. domChildren: map$2(detail.components, function (comp) {
  7644. return comp.element;
  7645. })
  7646. });
  7647. };
  7648. var toModification = function (detail) {
  7649. return detail.domModification.fold(function () {
  7650. return nu$3({});
  7651. }, nu$3);
  7652. };
  7653. var toEvents = function (info) {
  7654. return info.events;
  7655. };
  7656. var add = function (element, classes) {
  7657. each$1(classes, function (x) {
  7658. add$1(element, x);
  7659. });
  7660. };
  7661. var remove$1 = function (element, classes) {
  7662. each$1(classes, function (x) {
  7663. remove$3(element, x);
  7664. });
  7665. };
  7666. var renderToDom = function (definition) {
  7667. var subject = SugarElement.fromTag(definition.tag);
  7668. setAll$1(subject, definition.attributes);
  7669. add(subject, definition.classes);
  7670. setAll(subject, definition.styles);
  7671. definition.innerHtml.each(function (html) {
  7672. return set$7(subject, html);
  7673. });
  7674. var children = definition.domChildren;
  7675. append$1(subject, children);
  7676. definition.value.each(function (value) {
  7677. set$2(subject, value);
  7678. });
  7679. if (!definition.uid) {
  7680. debugger;
  7681. }
  7682. writeOnly(subject, definition.uid);
  7683. return subject;
  7684. };
  7685. var getBehaviours = function (spec) {
  7686. var behaviours = get$c(spec, 'behaviours').getOr({});
  7687. return bind$3(keys(behaviours), function (name) {
  7688. var behaviour = behaviours[name];
  7689. return isNonNullable(behaviour) ? [behaviour.me] : [];
  7690. });
  7691. };
  7692. var generateFrom = function (spec, all) {
  7693. return generateFrom$1(spec, all);
  7694. };
  7695. var generate$1 = function (spec) {
  7696. var all = getBehaviours(spec);
  7697. return generateFrom(spec, all);
  7698. };
  7699. var getDomDefinition = function (info, bList, bData) {
  7700. var definition = toDefinition(info);
  7701. var infoModification = toModification(info);
  7702. var baseModification = { 'alloy.base.modification': infoModification };
  7703. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7704. return merge(definition, modification);
  7705. };
  7706. var getEvents = function (info, bList, bData) {
  7707. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7708. return combine(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7709. };
  7710. var build$2 = function (spec) {
  7711. var getMe = function () {
  7712. return me;
  7713. };
  7714. var systemApi = Cell(singleton);
  7715. var info = getOrDie(toInfo(spec));
  7716. var bBlob = generate$1(spec);
  7717. var bList = getBehaviours$1(bBlob);
  7718. var bData = getData(bBlob);
  7719. var modDefinition = getDomDefinition(info, bList, bData);
  7720. var item = renderToDom(modDefinition);
  7721. var events = getEvents(info, bList, bData);
  7722. var subcomponents = Cell(info.components);
  7723. var connect = function (newApi) {
  7724. systemApi.set(newApi);
  7725. };
  7726. var disconnect = function () {
  7727. systemApi.set(NoContextApi(getMe));
  7728. };
  7729. var syncComponents = function () {
  7730. var children$1 = children(item);
  7731. var subs = bind$3(children$1, function (child) {
  7732. return systemApi.get().getByDom(child).fold(function () {
  7733. return [];
  7734. }, pure$2);
  7735. });
  7736. subcomponents.set(subs);
  7737. };
  7738. var config = function (behaviour) {
  7739. var b = bData;
  7740. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7741. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7742. };
  7743. return f();
  7744. };
  7745. var hasConfigured = function (behaviour) {
  7746. return isFunction(bData[behaviour.name()]);
  7747. };
  7748. var getApis = function () {
  7749. return info.apis;
  7750. };
  7751. var readState = function (behaviourName) {
  7752. return bData[behaviourName]().map(function (b) {
  7753. return b.state.readState();
  7754. }).getOr('not enabled');
  7755. };
  7756. var me = {
  7757. uid: spec.uid,
  7758. getSystem: systemApi.get,
  7759. config: config,
  7760. hasConfigured: hasConfigured,
  7761. spec: spec,
  7762. readState: readState,
  7763. getApis: getApis,
  7764. connect: connect,
  7765. disconnect: disconnect,
  7766. element: item,
  7767. syncComponents: syncComponents,
  7768. components: subcomponents.get,
  7769. events: events
  7770. };
  7771. return me;
  7772. };
  7773. var buildSubcomponents = function (spec) {
  7774. var components = get$c(spec, 'components').getOr([]);
  7775. return map$2(components, build$1);
  7776. };
  7777. var buildFromSpec = function (userSpec) {
  7778. var _a = make$3(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7779. var components = buildSubcomponents(spec);
  7780. var completeSpec = __assign(__assign({}, spec), {
  7781. events: __assign(__assign({}, DefaultEvents), specEvents),
  7782. components: components
  7783. });
  7784. return Result.value(build$2(completeSpec));
  7785. };
  7786. var text = function (textContent) {
  7787. var element = SugarElement.fromText(textContent);
  7788. return external({ element: element });
  7789. };
  7790. var external = function (spec) {
  7791. var extSpec = asRawOrDie$1('external.component', objOfOnly([
  7792. required$1('element'),
  7793. option('uid')
  7794. ]), spec);
  7795. var systemApi = Cell(NoContextApi());
  7796. var connect = function (newApi) {
  7797. systemApi.set(newApi);
  7798. };
  7799. var disconnect = function () {
  7800. systemApi.set(NoContextApi(function () {
  7801. return me;
  7802. }));
  7803. };
  7804. var uid = extSpec.uid.getOrThunk(function () {
  7805. return generate$2('external');
  7806. });
  7807. writeOnly(extSpec.element, uid);
  7808. var me = {
  7809. uid: uid,
  7810. getSystem: systemApi.get,
  7811. config: Optional.none,
  7812. hasConfigured: never,
  7813. connect: connect,
  7814. disconnect: disconnect,
  7815. getApis: function () {
  7816. return {};
  7817. },
  7818. element: extSpec.element,
  7819. spec: spec,
  7820. readState: constant$1('No state'),
  7821. syncComponents: noop,
  7822. components: constant$1([]),
  7823. events: {}
  7824. };
  7825. return premade$1(me);
  7826. };
  7827. var uids = generate$2;
  7828. var isSketchSpec = function (spec) {
  7829. return has$2(spec, 'uid');
  7830. };
  7831. var build$1 = function (spec) {
  7832. return getPremade(spec).getOrThunk(function () {
  7833. var userSpecWithUid = isSketchSpec(spec) ? spec : __assign({ uid: uids('') }, spec);
  7834. return buildFromSpec(userSpecWithUid).getOrDie();
  7835. });
  7836. };
  7837. var premade = premade$1;
  7838. var hoverEvent = 'alloy.item-hover';
  7839. var focusEvent = 'alloy.item-focus';
  7840. var onHover = function (item) {
  7841. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7842. if (!Focusing.isFocused(item)) {
  7843. Focusing.focus(item);
  7844. }
  7845. emitWith(item, hoverEvent, { item: item });
  7846. }
  7847. };
  7848. var onFocus = function (item) {
  7849. emitWith(item, focusEvent, { item: item });
  7850. };
  7851. var hover = constant$1(hoverEvent);
  7852. var focus$1 = constant$1(focusEvent);
  7853. var builder$2 = function (detail) {
  7854. return {
  7855. dom: detail.dom,
  7856. 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 } : {}) }),
  7857. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7858. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7859. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7860. }),
  7861. Focusing.config({
  7862. ignore: detail.ignoreFocus,
  7863. stopMousedown: detail.ignoreFocus,
  7864. onFocus: function (component) {
  7865. onFocus(component);
  7866. }
  7867. }),
  7868. Keying.config({ mode: 'execution' }),
  7869. Representing.config({
  7870. store: {
  7871. mode: 'memory',
  7872. initialValue: detail.data
  7873. }
  7874. }),
  7875. config('item-type-events', __spreadArray(__spreadArray([], pointerEvents(), true), [
  7876. run(mouseover(), onHover),
  7877. run(focusItem(), Focusing.focus)
  7878. ], false))
  7879. ]),
  7880. components: detail.components,
  7881. eventOrder: detail.eventOrder
  7882. };
  7883. };
  7884. var schema$5 = [
  7885. required$1('data'),
  7886. required$1('components'),
  7887. required$1('dom'),
  7888. defaulted('hasSubmenu', false),
  7889. option('toggling'),
  7890. SketchBehaviours.field('itemBehaviours', [
  7891. Toggling,
  7892. Focusing,
  7893. Keying,
  7894. Representing
  7895. ]),
  7896. defaulted('ignoreFocus', false),
  7897. defaulted('domModification', {}),
  7898. output('builder', builder$2),
  7899. defaulted('eventOrder', {})
  7900. ];
  7901. var builder$1 = function (detail) {
  7902. return {
  7903. dom: detail.dom,
  7904. components: detail.components,
  7905. events: derive$3([stopper(focusItem())])
  7906. };
  7907. };
  7908. var schema$4 = [
  7909. required$1('dom'),
  7910. required$1('components'),
  7911. output('builder', builder$1)
  7912. ];
  7913. var owner = constant$1('item-widget');
  7914. var parts$3 = constant$1([required({
  7915. name: 'widget',
  7916. overrides: function (detail) {
  7917. return {
  7918. behaviours: derive$2([Representing.config({
  7919. store: {
  7920. mode: 'manual',
  7921. getValue: function (_component) {
  7922. return detail.data;
  7923. },
  7924. setValue: noop
  7925. }
  7926. })])
  7927. };
  7928. }
  7929. })]);
  7930. var builder = function (detail) {
  7931. var subs = substitutes(owner(), detail, parts$3());
  7932. var components$1 = components(owner(), detail, subs.internals());
  7933. var focusWidget = function (component) {
  7934. return getPart(component, detail, 'widget').map(function (widget) {
  7935. Keying.focusIn(widget);
  7936. return widget;
  7937. });
  7938. };
  7939. var onHorizontalArrow = function (component, simulatedEvent) {
  7940. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  7941. if (detail.autofocus) {
  7942. simulatedEvent.setSource(component.element);
  7943. return Optional.none();
  7944. } else {
  7945. return Optional.none();
  7946. }
  7947. }();
  7948. };
  7949. return {
  7950. dom: detail.dom,
  7951. components: components$1,
  7952. domModification: detail.domModification,
  7953. events: derive$3([
  7954. runOnExecute(function (component, simulatedEvent) {
  7955. focusWidget(component).each(function (_widget) {
  7956. simulatedEvent.stop();
  7957. });
  7958. }),
  7959. run(mouseover(), onHover),
  7960. run(focusItem(), function (component, _simulatedEvent) {
  7961. if (detail.autofocus) {
  7962. focusWidget(component);
  7963. } else {
  7964. Focusing.focus(component);
  7965. }
  7966. })
  7967. ]),
  7968. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7969. Representing.config({
  7970. store: {
  7971. mode: 'memory',
  7972. initialValue: detail.data
  7973. }
  7974. }),
  7975. Focusing.config({
  7976. ignore: detail.ignoreFocus,
  7977. onFocus: function (component) {
  7978. onFocus(component);
  7979. }
  7980. }),
  7981. Keying.config({
  7982. mode: 'special',
  7983. focusIn: detail.autofocus ? function (component) {
  7984. focusWidget(component);
  7985. } : revoke(),
  7986. onLeft: onHorizontalArrow,
  7987. onRight: onHorizontalArrow,
  7988. onEscape: function (component, simulatedEvent) {
  7989. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7990. Focusing.focus(component);
  7991. return Optional.some(true);
  7992. } else if (detail.autofocus) {
  7993. simulatedEvent.setSource(component.element);
  7994. return Optional.none();
  7995. } else {
  7996. return Optional.none();
  7997. }
  7998. }
  7999. })
  8000. ])
  8001. };
  8002. };
  8003. var schema$3 = [
  8004. required$1('uid'),
  8005. required$1('data'),
  8006. required$1('components'),
  8007. required$1('dom'),
  8008. defaulted('autofocus', false),
  8009. defaulted('ignoreFocus', false),
  8010. SketchBehaviours.field('widgetBehaviours', [
  8011. Representing,
  8012. Focusing,
  8013. Keying
  8014. ]),
  8015. defaulted('domModification', {}),
  8016. defaultUidsSchema(parts$3()),
  8017. output('builder', builder)
  8018. ];
  8019. var itemSchema = choose$1('type', {
  8020. widget: schema$3,
  8021. item: schema$5,
  8022. separator: schema$4
  8023. });
  8024. var configureGrid = function (detail, movementInfo) {
  8025. return {
  8026. mode: 'flatgrid',
  8027. selector: '.' + detail.markers.item,
  8028. initSize: {
  8029. numColumns: movementInfo.initSize.numColumns,
  8030. numRows: movementInfo.initSize.numRows
  8031. },
  8032. focusManager: detail.focusManager
  8033. };
  8034. };
  8035. var configureMatrix = function (detail, movementInfo) {
  8036. return {
  8037. mode: 'matrix',
  8038. selectors: {
  8039. row: movementInfo.rowSelector,
  8040. cell: '.' + detail.markers.item
  8041. },
  8042. focusManager: detail.focusManager
  8043. };
  8044. };
  8045. var configureMenu = function (detail, movementInfo) {
  8046. return {
  8047. mode: 'menu',
  8048. selector: '.' + detail.markers.item,
  8049. moveOnTab: movementInfo.moveOnTab,
  8050. focusManager: detail.focusManager
  8051. };
  8052. };
  8053. var parts$2 = constant$1([group({
  8054. factory: {
  8055. sketch: function (spec) {
  8056. var itemInfo = asRawOrDie$1('menu.spec item', itemSchema, spec);
  8057. return itemInfo.builder(itemInfo);
  8058. }
  8059. },
  8060. name: 'items',
  8061. unit: 'item',
  8062. defaults: function (detail, u) {
  8063. return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  8064. },
  8065. overrides: function (detail, u) {
  8066. return {
  8067. type: u.type,
  8068. ignoreFocus: detail.fakeFocus,
  8069. domModification: { classes: [detail.markers.item] }
  8070. };
  8071. }
  8072. })]);
  8073. var schema$2 = constant$1([
  8074. required$1('value'),
  8075. required$1('items'),
  8076. required$1('dom'),
  8077. required$1('components'),
  8078. defaulted('eventOrder', {}),
  8079. field$1('menuBehaviours', [
  8080. Highlighting,
  8081. Representing,
  8082. Composing,
  8083. Keying
  8084. ]),
  8085. defaultedOf('movement', {
  8086. mode: 'menu',
  8087. moveOnTab: true
  8088. }, choose$1('mode', {
  8089. grid: [
  8090. initSize(),
  8091. output('config', configureGrid)
  8092. ],
  8093. matrix: [
  8094. output('config', configureMatrix),
  8095. required$1('rowSelector')
  8096. ],
  8097. menu: [
  8098. defaulted('moveOnTab', true),
  8099. output('config', configureMenu)
  8100. ]
  8101. })),
  8102. itemMarkers(),
  8103. defaulted('fakeFocus', false),
  8104. defaulted('focusManager', dom$2()),
  8105. onHandler('onHighlight')
  8106. ]);
  8107. var focus = constant$1('alloy.menu-focus');
  8108. var make$2 = function (detail, components, _spec, _externals) {
  8109. return {
  8110. uid: detail.uid,
  8111. dom: detail.dom,
  8112. markers: detail.markers,
  8113. behaviours: augment(detail.menuBehaviours, [
  8114. Highlighting.config({
  8115. highlightClass: detail.markers.selectedItem,
  8116. itemClass: detail.markers.item,
  8117. onHighlight: detail.onHighlight
  8118. }),
  8119. Representing.config({
  8120. store: {
  8121. mode: 'memory',
  8122. initialValue: detail.value
  8123. }
  8124. }),
  8125. Composing.config({ find: Optional.some }),
  8126. Keying.config(detail.movement.config(detail, detail.movement))
  8127. ]),
  8128. events: derive$3([
  8129. run(focus$1(), function (menu, simulatedEvent) {
  8130. var event = simulatedEvent.event;
  8131. menu.getSystem().getByDom(event.target).each(function (item) {
  8132. Highlighting.highlight(menu, item);
  8133. simulatedEvent.stop();
  8134. emitWith(menu, focus(), {
  8135. menu: menu,
  8136. item: item
  8137. });
  8138. });
  8139. }),
  8140. run(hover(), function (menu, simulatedEvent) {
  8141. var item = simulatedEvent.event.item;
  8142. Highlighting.highlight(menu, item);
  8143. })
  8144. ]),
  8145. components: components,
  8146. eventOrder: detail.eventOrder,
  8147. domModification: { attributes: { role: 'menu' } }
  8148. };
  8149. };
  8150. var Menu = composite({
  8151. name: 'Menu',
  8152. configFields: schema$2(),
  8153. partFields: parts$2(),
  8154. factory: make$2
  8155. });
  8156. var preserve = function (f, container) {
  8157. var dos = getRootNode(container);
  8158. var refocus = active(dos).bind(function (focused) {
  8159. var hasFocus = function (elem) {
  8160. return eq(focused, elem);
  8161. };
  8162. return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  8163. });
  8164. var result = f(container);
  8165. refocus.each(function (oldFocus) {
  8166. active(dos).filter(function (newFocus) {
  8167. return eq(newFocus, oldFocus);
  8168. }).fold(function () {
  8169. focus$3(oldFocus);
  8170. }, noop);
  8171. });
  8172. return result;
  8173. };
  8174. var set = function (component, replaceConfig, replaceState, data) {
  8175. preserve(function () {
  8176. var newChildren = map$2(data, component.getSystem().build);
  8177. replaceChildren(component, newChildren);
  8178. }, component.element);
  8179. };
  8180. var insert = function (component, replaceConfig, insertion, childSpec) {
  8181. var child = component.getSystem().build(childSpec);
  8182. attachWith(component, child, insertion);
  8183. };
  8184. var append = function (component, replaceConfig, replaceState, appendee) {
  8185. insert(component, replaceConfig, append$2, appendee);
  8186. };
  8187. var prepend = function (component, replaceConfig, replaceState, prependee) {
  8188. insert(component, replaceConfig, prepend$1, prependee);
  8189. };
  8190. var remove = function (component, replaceConfig, replaceState, removee) {
  8191. var children = contents(component);
  8192. var foundChild = find$2(children, function (child) {
  8193. return eq(removee.element, child.element);
  8194. });
  8195. foundChild.each(detach);
  8196. };
  8197. var contents = function (component, _replaceConfig) {
  8198. return component.components();
  8199. };
  8200. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8201. var children = contents(component);
  8202. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  8203. remove(component, replaceConfig, replaceState, replacee);
  8204. replacer.each(function (r) {
  8205. insert(component, replaceConfig, function (p, c) {
  8206. appendAt(p, c, replaceeIndex);
  8207. }, r);
  8208. });
  8209. return replacee;
  8210. });
  8211. };
  8212. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8213. var children = contents(component);
  8214. return findIndex$1(children, replaceePred).bind(function (replaceeIndex) {
  8215. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8216. });
  8217. };
  8218. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8219. __proto__: null,
  8220. append: append,
  8221. prepend: prepend,
  8222. remove: remove,
  8223. replaceAt: replaceAt,
  8224. replaceBy: replaceBy,
  8225. set: set,
  8226. contents: contents
  8227. });
  8228. var Replacing = create$5({
  8229. fields: [],
  8230. name: 'replacing',
  8231. apis: ReplaceApis
  8232. });
  8233. var transpose = function (obj) {
  8234. return tupleMap(obj, function (v, k) {
  8235. return {
  8236. k: v,
  8237. v: k
  8238. };
  8239. });
  8240. };
  8241. var trace = function (items, byItem, byMenu, finish) {
  8242. return get$c(byMenu, finish).bind(function (triggerItem) {
  8243. return get$c(items, triggerItem).bind(function (triggerMenu) {
  8244. var rest = trace(items, byItem, byMenu, triggerMenu);
  8245. return Optional.some([triggerMenu].concat(rest));
  8246. });
  8247. }).getOr([]);
  8248. };
  8249. var generate = function (menus, expansions) {
  8250. var items = {};
  8251. each(menus, function (menuItems, menu) {
  8252. each$1(menuItems, function (item) {
  8253. items[item] = menu;
  8254. });
  8255. });
  8256. var byItem = expansions;
  8257. var byMenu = transpose(expansions);
  8258. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  8259. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8260. });
  8261. return map$1(items, function (menu) {
  8262. return get$c(menuPaths, menu).getOr([menu]);
  8263. });
  8264. };
  8265. var init$2 = function () {
  8266. var expansions = Cell({});
  8267. var menus = Cell({});
  8268. var paths = Cell({});
  8269. var primary = value();
  8270. var directory = Cell({});
  8271. var clear = function () {
  8272. expansions.set({});
  8273. menus.set({});
  8274. paths.set({});
  8275. primary.clear();
  8276. };
  8277. var isClear = function () {
  8278. return primary.get().isNone();
  8279. };
  8280. var setMenuBuilt = function (menuName, built) {
  8281. var _a;
  8282. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8283. type: 'prepared',
  8284. menu: built
  8285. }, _a)));
  8286. };
  8287. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8288. primary.set(sPrimary);
  8289. expansions.set(sExpansions);
  8290. menus.set(sMenus);
  8291. directory.set(dir);
  8292. var sPaths = generate(dir, sExpansions);
  8293. paths.set(sPaths);
  8294. };
  8295. var getTriggeringItem = function (menuValue) {
  8296. return find(expansions.get(), function (v, _k) {
  8297. return v === menuValue;
  8298. });
  8299. };
  8300. var getTriggerData = function (menuValue, getItemByValue, path) {
  8301. return getPreparedMenu(menuValue).bind(function (menu) {
  8302. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8303. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8304. return {
  8305. triggeredMenu: menu,
  8306. triggeringItem: triggeredItem,
  8307. triggeringPath: path
  8308. };
  8309. });
  8310. });
  8311. });
  8312. };
  8313. var getTriggeringPath = function (itemValue, getItemByValue) {
  8314. var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) {
  8315. return getPreparedMenu(menuValue).isSome();
  8316. });
  8317. return get$c(paths.get(), itemValue).bind(function (path) {
  8318. var revPath = reverse(extraPath.concat(path));
  8319. var triggers = bind$3(revPath, function (menuValue, menuIndex) {
  8320. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8321. return is(primary.get(), menuValue) ? [] : [Optional.none()];
  8322. }, function (data) {
  8323. return [Optional.some(data)];
  8324. });
  8325. });
  8326. return sequence(triggers);
  8327. });
  8328. };
  8329. var expand = function (itemValue) {
  8330. return get$c(expansions.get(), itemValue).map(function (menu) {
  8331. var current = get$c(paths.get(), itemValue).getOr([]);
  8332. return [menu].concat(current);
  8333. });
  8334. };
  8335. var collapse = function (itemValue) {
  8336. return get$c(paths.get(), itemValue).bind(function (path) {
  8337. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8338. });
  8339. };
  8340. var refresh = function (itemValue) {
  8341. return get$c(paths.get(), itemValue);
  8342. };
  8343. var getPreparedMenu = function (menuValue) {
  8344. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8345. };
  8346. var lookupMenu = function (menuValue) {
  8347. return get$c(menus.get(), menuValue);
  8348. };
  8349. var lookupItem = function (itemValue) {
  8350. return get$c(expansions.get(), itemValue);
  8351. };
  8352. var otherMenus = function (path) {
  8353. var menuValues = directory.get();
  8354. return difference(keys(menuValues), path);
  8355. };
  8356. var getPrimary = function () {
  8357. return primary.get().bind(getPreparedMenu);
  8358. };
  8359. var getMenus = function () {
  8360. return menus.get();
  8361. };
  8362. return {
  8363. setMenuBuilt: setMenuBuilt,
  8364. setContents: setContents,
  8365. expand: expand,
  8366. refresh: refresh,
  8367. collapse: collapse,
  8368. lookupMenu: lookupMenu,
  8369. lookupItem: lookupItem,
  8370. otherMenus: otherMenus,
  8371. getPrimary: getPrimary,
  8372. getMenus: getMenus,
  8373. clear: clear,
  8374. isClear: isClear,
  8375. getTriggeringPath: getTriggeringPath
  8376. };
  8377. };
  8378. var extractPreparedMenu = function (prep) {
  8379. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8380. };
  8381. var LayeredState = {
  8382. init: init$2,
  8383. extractPreparedMenu: extractPreparedMenu
  8384. };
  8385. var make$1 = function (detail, _rawUiSpec) {
  8386. var submenuParentItems = value();
  8387. var buildMenus = function (container, primaryName, menus) {
  8388. return map$1(menus, function (spec, name) {
  8389. var makeSketch = function () {
  8390. return Menu.sketch(__assign(__assign({}, spec), {
  8391. value: name,
  8392. markers: detail.markers,
  8393. fakeFocus: detail.fakeFocus,
  8394. onHighlight: detail.onHighlight,
  8395. focusManager: detail.fakeFocus ? highlights() : dom$2()
  8396. }));
  8397. };
  8398. return name === primaryName ? {
  8399. type: 'prepared',
  8400. menu: container.getSystem().build(makeSketch())
  8401. } : {
  8402. type: 'notbuilt',
  8403. nbMenu: makeSketch
  8404. };
  8405. });
  8406. };
  8407. var layeredState = LayeredState.init();
  8408. var setup = function (container) {
  8409. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8410. var directory = toDirectory();
  8411. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8412. return layeredState.getPrimary();
  8413. };
  8414. var getItemValue = function (item) {
  8415. return Representing.getValue(item).value;
  8416. };
  8417. var getItemByValue = function (_container, menus, itemValue) {
  8418. return findMap(menus, function (menu) {
  8419. if (!menu.getSystem().isConnected()) {
  8420. return Optional.none();
  8421. }
  8422. var candidates = Highlighting.getCandidates(menu);
  8423. return find$2(candidates, function (c) {
  8424. return getItemValue(c) === itemValue;
  8425. });
  8426. });
  8427. };
  8428. var toDirectory = function (_container) {
  8429. return map$1(detail.data.menus, function (data, _menuName) {
  8430. return bind$3(data.items, function (item) {
  8431. return item.type === 'separator' ? [] : [item.data.value];
  8432. });
  8433. });
  8434. };
  8435. var setActiveMenu = function (container, menu) {
  8436. Highlighting.highlight(container, menu);
  8437. Highlighting.getHighlighted(menu).orThunk(function () {
  8438. return Highlighting.getFirst(menu);
  8439. }).each(function (item) {
  8440. dispatch(container, item.element, focusItem());
  8441. });
  8442. };
  8443. var getMenus = function (state, menuValues) {
  8444. return cat(map$2(menuValues, function (mv) {
  8445. return state.lookupMenu(mv).bind(function (prep) {
  8446. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8447. });
  8448. }));
  8449. };
  8450. var closeOthers = function (container, state, path) {
  8451. var others = getMenus(state, state.otherMenus(path));
  8452. each$1(others, function (o) {
  8453. remove$1(o.element, [detail.markers.backgroundMenu]);
  8454. if (!detail.stayInDom) {
  8455. Replacing.remove(container, o);
  8456. }
  8457. });
  8458. };
  8459. var getSubmenuParents = function (container) {
  8460. return submenuParentItems.get().getOrThunk(function () {
  8461. var r = {};
  8462. var items = descendants(container.element, '.' + detail.markers.item);
  8463. var parentItems = filter$2(items, function (i) {
  8464. return get$b(i, 'aria-haspopup') === 'true';
  8465. });
  8466. each$1(parentItems, function (i) {
  8467. container.getSystem().getByDom(i).each(function (itemComp) {
  8468. var key = getItemValue(itemComp);
  8469. r[key] = itemComp;
  8470. });
  8471. });
  8472. submenuParentItems.set(r);
  8473. return r;
  8474. });
  8475. };
  8476. var updateAriaExpansions = function (container, path) {
  8477. var parentItems = getSubmenuParents(container);
  8478. each(parentItems, function (v, k) {
  8479. var expanded = contains$1(path, k);
  8480. set$8(v.element, 'aria-expanded', expanded);
  8481. });
  8482. };
  8483. var updateMenuPath = function (container, state, path) {
  8484. return Optional.from(path[0]).bind(function (latestMenuName) {
  8485. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8486. if (menuPrep.type === 'notbuilt') {
  8487. return Optional.none();
  8488. } else {
  8489. var activeMenu = menuPrep.menu;
  8490. var rest = getMenus(state, path.slice(1));
  8491. each$1(rest, function (r) {
  8492. add$1(r.element, detail.markers.backgroundMenu);
  8493. });
  8494. if (!inBody(activeMenu.element)) {
  8495. Replacing.append(container, premade(activeMenu));
  8496. }
  8497. remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
  8498. setActiveMenu(container, activeMenu);
  8499. closeOthers(container, state, path);
  8500. return Optional.some(activeMenu);
  8501. }
  8502. });
  8503. });
  8504. };
  8505. var ExpandHighlightDecision;
  8506. (function (ExpandHighlightDecision) {
  8507. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8508. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8509. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8510. var buildIfRequired = function (container, menuName, menuPrep) {
  8511. if (menuPrep.type === 'notbuilt') {
  8512. var menu = container.getSystem().build(menuPrep.nbMenu());
  8513. layeredState.setMenuBuilt(menuName, menu);
  8514. return menu;
  8515. } else {
  8516. return menuPrep.menu;
  8517. }
  8518. };
  8519. var expandRight = function (container, item, decision) {
  8520. if (decision === void 0) {
  8521. decision = ExpandHighlightDecision.HighlightSubmenu;
  8522. }
  8523. if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  8524. return Optional.some(item);
  8525. } else {
  8526. var value = getItemValue(item);
  8527. return layeredState.expand(value).bind(function (path) {
  8528. updateAriaExpansions(container, path);
  8529. return Optional.from(path[0]).bind(function (menuName) {
  8530. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8531. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8532. if (!inBody(activeMenu.element)) {
  8533. Replacing.append(container, premade(activeMenu));
  8534. }
  8535. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8536. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8537. Highlighting.highlightFirst(activeMenu);
  8538. return updateMenuPath(container, layeredState, path);
  8539. } else {
  8540. Highlighting.dehighlightAll(activeMenu);
  8541. return Optional.some(item);
  8542. }
  8543. });
  8544. });
  8545. });
  8546. }
  8547. };
  8548. var collapseLeft = function (container, item) {
  8549. var value = getItemValue(item);
  8550. return layeredState.collapse(value).bind(function (path) {
  8551. updateAriaExpansions(container, path);
  8552. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8553. detail.onCollapseMenu(container, item, activeMenu);
  8554. return activeMenu;
  8555. });
  8556. });
  8557. };
  8558. var updateView = function (container, item) {
  8559. var value = getItemValue(item);
  8560. return layeredState.refresh(value).bind(function (path) {
  8561. updateAriaExpansions(container, path);
  8562. return updateMenuPath(container, layeredState, path);
  8563. });
  8564. };
  8565. var onRight = function (container, item) {
  8566. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8567. };
  8568. var onLeft = function (container, item) {
  8569. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8570. };
  8571. var onEscape = function (container, item) {
  8572. return collapseLeft(container, item).orThunk(function () {
  8573. return detail.onEscape(container, item).map(function () {
  8574. return container;
  8575. });
  8576. });
  8577. };
  8578. var keyOnItem = function (f) {
  8579. return function (container, simulatedEvent) {
  8580. return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8581. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8582. return f(container, item).map(always);
  8583. });
  8584. });
  8585. };
  8586. };
  8587. var events = derive$3([
  8588. run(focus(), function (sandbox, simulatedEvent) {
  8589. var item = simulatedEvent.event.item;
  8590. layeredState.lookupItem(getItemValue(item)).each(function () {
  8591. var menu = simulatedEvent.event.menu;
  8592. Highlighting.highlight(sandbox, menu);
  8593. var value = getItemValue(simulatedEvent.event.item);
  8594. layeredState.refresh(value).each(function (path) {
  8595. return closeOthers(sandbox, layeredState, path);
  8596. });
  8597. });
  8598. }),
  8599. runOnExecute(function (component, simulatedEvent) {
  8600. var target = simulatedEvent.event.target;
  8601. component.getSystem().getByDom(target).each(function (item) {
  8602. var itemValue = getItemValue(item);
  8603. if (itemValue.indexOf('collapse-item') === 0) {
  8604. collapseLeft(component, item);
  8605. }
  8606. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8607. detail.onExecute(component, item);
  8608. }, noop);
  8609. });
  8610. }),
  8611. runOnAttached(function (container, _simulatedEvent) {
  8612. setup(container).each(function (primary) {
  8613. Replacing.append(container, premade(primary));
  8614. detail.onOpenMenu(container, primary);
  8615. if (detail.highlightImmediately) {
  8616. setActiveMenu(container, primary);
  8617. }
  8618. });
  8619. })
  8620. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8621. var item = simulatedEvent.event.item;
  8622. updateView(sandbox, item);
  8623. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8624. detail.onHover(sandbox, item);
  8625. })] : []));
  8626. var getActiveItem = function (container) {
  8627. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8628. };
  8629. var collapseMenuApi = function (container) {
  8630. getActiveItem(container).each(function (currentItem) {
  8631. collapseLeft(container, currentItem);
  8632. });
  8633. };
  8634. var highlightPrimary = function (container) {
  8635. layeredState.getPrimary().each(function (primary) {
  8636. setActiveMenu(container, primary);
  8637. });
  8638. };
  8639. var extractMenuFromContainer = function (container) {
  8640. return Optional.from(container.components()[0]).filter(function (comp) {
  8641. return get$b(comp.element, 'role') === 'menu';
  8642. });
  8643. };
  8644. var repositionMenus = function (container) {
  8645. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8646. return getActiveItem(container).bind(function (currentItem) {
  8647. var itemValue = getItemValue(currentItem);
  8648. var allMenus = values(layeredState.getMenus());
  8649. var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  8650. return layeredState.getTriggeringPath(itemValue, function (v) {
  8651. return getItemByValue(container, preparedMenus, v);
  8652. });
  8653. }).map(function (triggeringPath) {
  8654. return {
  8655. primary: primary,
  8656. triggeringPath: triggeringPath
  8657. };
  8658. });
  8659. });
  8660. maybeActivePrimary.fold(function () {
  8661. extractMenuFromContainer(container).each(function (primaryMenu) {
  8662. detail.onRepositionMenu(container, primaryMenu, []);
  8663. });
  8664. }, function (_a) {
  8665. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8666. detail.onRepositionMenu(container, primary, triggeringPath);
  8667. });
  8668. };
  8669. var apis = {
  8670. collapseMenu: collapseMenuApi,
  8671. highlightPrimary: highlightPrimary,
  8672. repositionMenus: repositionMenus
  8673. };
  8674. return {
  8675. uid: detail.uid,
  8676. dom: detail.dom,
  8677. markers: detail.markers,
  8678. behaviours: augment(detail.tmenuBehaviours, [
  8679. Keying.config({
  8680. mode: 'special',
  8681. onRight: keyOnItem(onRight),
  8682. onLeft: keyOnItem(onLeft),
  8683. onEscape: keyOnItem(onEscape),
  8684. focusIn: function (container, _keyInfo) {
  8685. layeredState.getPrimary().each(function (primary) {
  8686. dispatch(container, primary.element, focusItem());
  8687. });
  8688. }
  8689. }),
  8690. Highlighting.config({
  8691. highlightClass: detail.markers.selectedMenu,
  8692. itemClass: detail.markers.menu
  8693. }),
  8694. Composing.config({
  8695. find: function (container) {
  8696. return Highlighting.getHighlighted(container);
  8697. }
  8698. }),
  8699. Replacing.config({})
  8700. ]),
  8701. eventOrder: detail.eventOrder,
  8702. apis: apis,
  8703. events: events
  8704. };
  8705. };
  8706. var collapseItem$1 = constant$1('collapse-item');
  8707. var tieredData = function (primary, menus, expansions) {
  8708. return {
  8709. primary: primary,
  8710. menus: menus,
  8711. expansions: expansions
  8712. };
  8713. };
  8714. var singleData = function (name, menu) {
  8715. return {
  8716. primary: name,
  8717. menus: wrap(name, menu),
  8718. expansions: {}
  8719. };
  8720. };
  8721. var collapseItem = function (text) {
  8722. return {
  8723. value: generate$4(collapseItem$1()),
  8724. meta: { text: text }
  8725. };
  8726. };
  8727. var tieredMenu = single({
  8728. name: 'TieredMenu',
  8729. configFields: [
  8730. onStrictKeyboardHandler('onExecute'),
  8731. onStrictKeyboardHandler('onEscape'),
  8732. onStrictHandler('onOpenMenu'),
  8733. onStrictHandler('onOpenSubmenu'),
  8734. onHandler('onRepositionMenu'),
  8735. onHandler('onCollapseMenu'),
  8736. defaulted('highlightImmediately', true),
  8737. requiredObjOf('data', [
  8738. required$1('primary'),
  8739. required$1('menus'),
  8740. required$1('expansions')
  8741. ]),
  8742. defaulted('fakeFocus', false),
  8743. onHandler('onHighlight'),
  8744. onHandler('onHover'),
  8745. tieredMenuMarkers(),
  8746. required$1('dom'),
  8747. defaulted('navigateOnHover', true),
  8748. defaulted('stayInDom', false),
  8749. field$1('tmenuBehaviours', [
  8750. Keying,
  8751. Highlighting,
  8752. Composing,
  8753. Replacing
  8754. ]),
  8755. defaulted('eventOrder', {})
  8756. ],
  8757. apis: {
  8758. collapseMenu: function (apis, tmenu) {
  8759. apis.collapseMenu(tmenu);
  8760. },
  8761. highlightPrimary: function (apis, tmenu) {
  8762. apis.highlightPrimary(tmenu);
  8763. },
  8764. repositionMenus: function (apis, tmenu) {
  8765. apis.repositionMenus(tmenu);
  8766. }
  8767. },
  8768. factory: make$1,
  8769. extraApis: {
  8770. tieredData: tieredData,
  8771. singleData: singleData,
  8772. collapseItem: collapseItem
  8773. }
  8774. });
  8775. var findRoute = function (component, transConfig, transState, route) {
  8776. return get$c(transConfig.routes, route.start).bind(function (sConfig) {
  8777. return get$c(sConfig, route.destination);
  8778. });
  8779. };
  8780. var getTransition = function (comp, transConfig, transState) {
  8781. var route = getCurrentRoute(comp, transConfig);
  8782. return route.bind(function (r) {
  8783. return getTransitionOf(comp, transConfig, transState, r);
  8784. });
  8785. };
  8786. var getTransitionOf = function (comp, transConfig, transState, route) {
  8787. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8788. return r.transition.map(function (t) {
  8789. return {
  8790. transition: t,
  8791. route: r
  8792. };
  8793. });
  8794. });
  8795. };
  8796. var disableTransition = function (comp, transConfig, transState) {
  8797. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8798. var t = routeTransition.transition;
  8799. remove$3(comp.element, t.transitionClass);
  8800. remove$6(comp.element, transConfig.destinationAttr);
  8801. });
  8802. };
  8803. var getNewRoute = function (comp, transConfig, transState, destination) {
  8804. return {
  8805. start: get$b(comp.element, transConfig.stateAttr),
  8806. destination: destination
  8807. };
  8808. };
  8809. var getCurrentRoute = function (comp, transConfig, _transState) {
  8810. var el = comp.element;
  8811. return getOpt(el, transConfig.destinationAttr).map(function (destination) {
  8812. return {
  8813. start: get$b(comp.element, transConfig.stateAttr),
  8814. destination: destination
  8815. };
  8816. });
  8817. };
  8818. var jumpTo = function (comp, transConfig, transState, destination) {
  8819. disableTransition(comp, transConfig, transState);
  8820. if (has$1(comp.element, transConfig.stateAttr) && get$b(comp.element, transConfig.stateAttr) !== destination) {
  8821. transConfig.onFinish(comp, destination);
  8822. }
  8823. set$8(comp.element, transConfig.stateAttr, destination);
  8824. };
  8825. var fasttrack = function (comp, transConfig, _transState, _destination) {
  8826. if (has$1(comp.element, transConfig.destinationAttr)) {
  8827. getOpt(comp.element, transConfig.destinationAttr).each(function (destination) {
  8828. set$8(comp.element, transConfig.stateAttr, destination);
  8829. });
  8830. remove$6(comp.element, transConfig.destinationAttr);
  8831. }
  8832. };
  8833. var progressTo = function (comp, transConfig, transState, destination) {
  8834. fasttrack(comp, transConfig);
  8835. var route = getNewRoute(comp, transConfig, transState, destination);
  8836. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8837. jumpTo(comp, transConfig, transState, destination);
  8838. }, function (routeTransition) {
  8839. disableTransition(comp, transConfig, transState);
  8840. var t = routeTransition.transition;
  8841. add$1(comp.element, t.transitionClass);
  8842. set$8(comp.element, transConfig.destinationAttr, destination);
  8843. });
  8844. };
  8845. var getState = function (comp, transConfig, _transState) {
  8846. return getOpt(comp.element, transConfig.stateAttr);
  8847. };
  8848. var TransitionApis = /*#__PURE__*/Object.freeze({
  8849. __proto__: null,
  8850. findRoute: findRoute,
  8851. disableTransition: disableTransition,
  8852. getCurrentRoute: getCurrentRoute,
  8853. jumpTo: jumpTo,
  8854. progressTo: progressTo,
  8855. getState: getState
  8856. });
  8857. var events$1 = function (transConfig, transState) {
  8858. return derive$3([
  8859. run(transitionend(), function (component, simulatedEvent) {
  8860. var raw = simulatedEvent.event.raw;
  8861. getCurrentRoute(component, transConfig).each(function (route) {
  8862. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8863. rInfo.transition.each(function (rTransition) {
  8864. if (raw.propertyName === rTransition.property) {
  8865. jumpTo(component, transConfig, transState, route.destination);
  8866. transConfig.onTransition(component, route);
  8867. }
  8868. });
  8869. });
  8870. });
  8871. }),
  8872. runOnAttached(function (comp, _se) {
  8873. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8874. })
  8875. ]);
  8876. };
  8877. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8878. __proto__: null,
  8879. events: events$1
  8880. });
  8881. var TransitionSchema = [
  8882. defaulted('destinationAttr', 'data-transitioning-destination'),
  8883. defaulted('stateAttr', 'data-transitioning-state'),
  8884. required$1('initialState'),
  8885. onHandler('onTransition'),
  8886. onHandler('onFinish'),
  8887. requiredOf('routes', setOf(Result.value, setOf(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8888. required$1('property'),
  8889. required$1('transitionClass')
  8890. ])]))))
  8891. ];
  8892. var createRoutes = function (routes) {
  8893. var r = {};
  8894. each(routes, function (v, k) {
  8895. var waypoints = k.split('<->');
  8896. r[waypoints[0]] = wrap(waypoints[1], v);
  8897. r[waypoints[1]] = wrap(waypoints[0], v);
  8898. });
  8899. return r;
  8900. };
  8901. var createBistate = function (first, second, transitions) {
  8902. return wrapAll([
  8903. {
  8904. key: first,
  8905. value: wrap(second, transitions)
  8906. },
  8907. {
  8908. key: second,
  8909. value: wrap(first, transitions)
  8910. }
  8911. ]);
  8912. };
  8913. var createTristate = function (first, second, third, transitions) {
  8914. return wrapAll([
  8915. {
  8916. key: first,
  8917. value: wrapAll([
  8918. {
  8919. key: second,
  8920. value: transitions
  8921. },
  8922. {
  8923. key: third,
  8924. value: transitions
  8925. }
  8926. ])
  8927. },
  8928. {
  8929. key: second,
  8930. value: wrapAll([
  8931. {
  8932. key: first,
  8933. value: transitions
  8934. },
  8935. {
  8936. key: third,
  8937. value: transitions
  8938. }
  8939. ])
  8940. },
  8941. {
  8942. key: third,
  8943. value: wrapAll([
  8944. {
  8945. key: first,
  8946. value: transitions
  8947. },
  8948. {
  8949. key: second,
  8950. value: transitions
  8951. }
  8952. ])
  8953. }
  8954. ]);
  8955. };
  8956. var Transitioning = create$5({
  8957. fields: TransitionSchema,
  8958. name: 'transitioning',
  8959. active: ActiveTransitioning,
  8960. apis: TransitionApis,
  8961. extra: {
  8962. createRoutes: createRoutes,
  8963. createBistate: createBistate,
  8964. createTristate: createTristate
  8965. }
  8966. });
  8967. var scrollableStyle = resolve('scrollable');
  8968. var register$2 = function (element) {
  8969. add$1(element, scrollableStyle);
  8970. };
  8971. var deregister = function (element) {
  8972. remove$3(element, scrollableStyle);
  8973. };
  8974. var scrollable = scrollableStyle;
  8975. var getValue = function (item) {
  8976. return get$c(item, 'format').getOr(item.title);
  8977. };
  8978. var convert = function (formats, memMenuThunk) {
  8979. var mainMenu = makeMenu('Styles', [].concat(map$2(formats.items, function (k) {
  8980. return makeItem(getValue(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue(k)));
  8981. })), memMenuThunk, false);
  8982. var submenus = map$1(formats.menus, function (menuItems, menuName) {
  8983. var items = map$2(menuItems, function (item) {
  8984. return makeItem(getValue(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue(item)));
  8985. });
  8986. return makeMenu(menuName, items, memMenuThunk, true);
  8987. });
  8988. var menus = deepMerge(submenus, wrap('styles', mainMenu));
  8989. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  8990. return { tmenu: tmenu };
  8991. };
  8992. var makeItem = function (value, text, selected, preview, isMenu) {
  8993. return {
  8994. data: {
  8995. value: value,
  8996. text: text
  8997. },
  8998. type: 'item',
  8999. dom: {
  9000. tag: 'div',
  9001. classes: isMenu ? [resolve('styles-item-is-menu')] : []
  9002. },
  9003. toggling: {
  9004. toggleOnExecute: false,
  9005. toggleClass: resolve('format-matches'),
  9006. selected: selected
  9007. },
  9008. itemBehaviours: derive$2(isMenu ? [] : [format(value, function (comp, status) {
  9009. var toggle = status ? Toggling.on : Toggling.off;
  9010. toggle(comp);
  9011. })]),
  9012. components: [{
  9013. dom: {
  9014. tag: 'div',
  9015. attributes: { style: preview },
  9016. innerHtml: text
  9017. }
  9018. }]
  9019. };
  9020. };
  9021. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  9022. return {
  9023. value: value,
  9024. dom: { tag: 'div' },
  9025. components: [
  9026. Button.sketch({
  9027. dom: {
  9028. tag: 'div',
  9029. classes: [resolve('styles-collapser')]
  9030. },
  9031. components: collapsable ? [
  9032. {
  9033. dom: {
  9034. tag: 'span',
  9035. classes: [resolve('styles-collapse-icon')]
  9036. }
  9037. },
  9038. text(value)
  9039. ] : [text(value)],
  9040. action: function (item) {
  9041. if (collapsable) {
  9042. var comp = memMenuThunk().get(item);
  9043. tieredMenu.collapseMenu(comp);
  9044. }
  9045. }
  9046. }),
  9047. {
  9048. dom: {
  9049. tag: 'div',
  9050. classes: [resolve('styles-menu-items-container')]
  9051. },
  9052. components: [Menu.parts.items({})],
  9053. behaviours: derive$2([config('adhoc-scrollable-menu', [
  9054. runOnAttached(function (component, _simulatedEvent) {
  9055. set$5(component.element, 'overflow-y', 'auto');
  9056. set$5(component.element, '-webkit-overflow-scrolling', 'touch');
  9057. register$2(component.element);
  9058. }),
  9059. runOnDetached(function (component) {
  9060. remove$2(component.element, 'overflow-y');
  9061. remove$2(component.element, '-webkit-overflow-scrolling');
  9062. deregister(component.element);
  9063. })
  9064. ])])
  9065. }
  9066. ],
  9067. items: items,
  9068. menuBehaviours: derive$2([Transitioning.config({
  9069. initialState: 'after',
  9070. routes: Transitioning.createTristate('before', 'current', 'after', {
  9071. transition: {
  9072. property: 'transform',
  9073. transitionClass: 'transitioning'
  9074. }
  9075. })
  9076. })])
  9077. };
  9078. };
  9079. var sketch$1 = function (settings) {
  9080. var dataset = convert(settings.formats, function () {
  9081. return memMenu;
  9082. });
  9083. var memMenu = record(tieredMenu.sketch({
  9084. dom: {
  9085. tag: 'div',
  9086. classes: [resolve('styles-menu')]
  9087. },
  9088. components: [],
  9089. fakeFocus: true,
  9090. stayInDom: true,
  9091. onExecute: function (_tmenu, item) {
  9092. var v = Representing.getValue(item);
  9093. settings.handle(item, v.value);
  9094. return Optional.none();
  9095. },
  9096. onEscape: function () {
  9097. return Optional.none();
  9098. },
  9099. onOpenMenu: function (container, menu) {
  9100. var w = get$5(container.element);
  9101. set$4(menu.element, w);
  9102. Transitioning.jumpTo(menu, 'current');
  9103. },
  9104. onOpenSubmenu: function (container, item, submenu) {
  9105. var w = get$5(container.element);
  9106. var menu = ancestor(item.element, '[role="menu"]').getOrDie('hacky');
  9107. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9108. set$4(submenu.element, w);
  9109. Transitioning.progressTo(menuComp, 'before');
  9110. Transitioning.jumpTo(submenu, 'after');
  9111. Transitioning.progressTo(submenu, 'current');
  9112. },
  9113. onCollapseMenu: function (container, item, menu) {
  9114. var submenu = ancestor(item.element, '[role="menu"]').getOrDie('hacky');
  9115. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9116. Transitioning.progressTo(submenuComp, 'after');
  9117. Transitioning.progressTo(menu, 'current');
  9118. },
  9119. navigateOnHover: false,
  9120. highlightImmediately: true,
  9121. data: dataset.tmenu,
  9122. markers: {
  9123. backgroundMenu: resolve('styles-background-menu'),
  9124. menu: resolve('styles-menu'),
  9125. selectedMenu: resolve('styles-selected-menu'),
  9126. item: resolve('styles-item'),
  9127. selectedItem: resolve('styles-selected-item')
  9128. }
  9129. }));
  9130. return memMenu.asSpec();
  9131. };
  9132. var getFromExpandingItem = function (item) {
  9133. var newItem = deepMerge(exclude(item, ['items']), { menu: true });
  9134. var rest = expand(item.items);
  9135. var newMenus = deepMerge(rest.menus, wrap(item.title, rest.items));
  9136. var newExpansions = deepMerge(rest.expansions, wrap(item.title, item.title));
  9137. return {
  9138. item: newItem,
  9139. menus: newMenus,
  9140. expansions: newExpansions
  9141. };
  9142. };
  9143. var getFromItem = function (item) {
  9144. return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : {
  9145. item: item,
  9146. menus: {},
  9147. expansions: {}
  9148. };
  9149. };
  9150. var expand = function (items) {
  9151. return foldr(items, function (acc, item) {
  9152. var newData = getFromItem(item);
  9153. return {
  9154. menus: deepMerge(acc.menus, newData.menus),
  9155. items: [newData.item].concat(acc.items),
  9156. expansions: deepMerge(acc.expansions, newData.expansions)
  9157. };
  9158. }, {
  9159. menus: {},
  9160. expansions: {},
  9161. items: []
  9162. });
  9163. };
  9164. var register$1 = function (editor) {
  9165. var isSelectedFor = function (format) {
  9166. return function () {
  9167. return editor.formatter.match(format);
  9168. };
  9169. };
  9170. var getPreview = function (format) {
  9171. return function () {
  9172. return editor.formatter.getCssText(format);
  9173. };
  9174. };
  9175. var enrichSupported = function (item) {
  9176. return deepMerge(item, {
  9177. isSelected: isSelectedFor(item.format),
  9178. getPreview: getPreview(item.format)
  9179. });
  9180. };
  9181. var enrichMenu = function (item) {
  9182. return deepMerge(item, {
  9183. isSelected: never,
  9184. getPreview: constant$1('')
  9185. });
  9186. };
  9187. var enrichCustom = function (item) {
  9188. var formatName = generate$4(item.title);
  9189. var newItem = deepMerge(item, {
  9190. format: formatName,
  9191. isSelected: isSelectedFor(formatName),
  9192. getPreview: getPreview(formatName)
  9193. });
  9194. editor.formatter.register(formatName, newItem);
  9195. return newItem;
  9196. };
  9197. var doEnrich = function (items) {
  9198. return map$2(items, function (item) {
  9199. if (hasNonNullableKey(item, 'items')) {
  9200. var newItems = doEnrich(item.items);
  9201. return deepMerge(enrichMenu(item), { items: newItems });
  9202. } else if (hasNonNullableKey(item, 'format')) {
  9203. return enrichSupported(item);
  9204. } else {
  9205. return enrichCustom(item);
  9206. }
  9207. });
  9208. };
  9209. return doEnrich(getStyleFormats(editor));
  9210. };
  9211. var prune = function (editor, formats) {
  9212. var doPrune = function (items) {
  9213. return bind$3(items, function (item) {
  9214. if (item.items !== undefined) {
  9215. var newItems = doPrune(item.items);
  9216. return newItems.length > 0 ? [item] : [];
  9217. } else {
  9218. var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9219. return keep ? [item] : [];
  9220. }
  9221. });
  9222. };
  9223. var prunedItems = doPrune(formats);
  9224. return expand(prunedItems);
  9225. };
  9226. var ui = function (editor, formats, onDone) {
  9227. var pruned = prune(editor, formats);
  9228. return sketch$1({
  9229. formats: pruned,
  9230. handle: function (item, value) {
  9231. editor.undoManager.transact(function () {
  9232. if (Toggling.isOn(item)) {
  9233. editor.formatter.remove(value);
  9234. } else {
  9235. editor.formatter.apply(value);
  9236. }
  9237. });
  9238. onDone();
  9239. }
  9240. });
  9241. };
  9242. var extract = function (rawToolbar) {
  9243. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9244. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9245. };
  9246. var identifyFromArray = function (toolbar) {
  9247. return bind$3(toolbar, function (item) {
  9248. return isArray(item) ? identifyFromArray(item) : extract(item);
  9249. });
  9250. };
  9251. var identify = function (editor) {
  9252. var toolbar = getToolbar(editor);
  9253. return isArray(toolbar) ? identifyFromArray(toolbar) : extract(toolbar);
  9254. };
  9255. var setup$3 = function (realm, editor) {
  9256. var commandSketch = function (name) {
  9257. return function () {
  9258. return forToolbarCommand(editor, name);
  9259. };
  9260. };
  9261. var stateCommandSketch = function (name) {
  9262. return function () {
  9263. return forToolbarStateCommand(editor, name);
  9264. };
  9265. };
  9266. var actionSketch = function (name, query, action) {
  9267. return function () {
  9268. return forToolbarStateAction(editor, name, query, action);
  9269. };
  9270. };
  9271. var undo = commandSketch('undo');
  9272. var redo = commandSketch('redo');
  9273. var bold = stateCommandSketch('bold');
  9274. var italic = stateCommandSketch('italic');
  9275. var underline = stateCommandSketch('underline');
  9276. var removeformat = commandSketch('removeformat');
  9277. var link = function () {
  9278. return sketch$2(realm, editor);
  9279. };
  9280. var unlink = actionSketch('unlink', 'link', function () {
  9281. editor.execCommand('unlink', null, false);
  9282. });
  9283. var image = function () {
  9284. return sketch$5(editor);
  9285. };
  9286. var bullist = actionSketch('unordered-list', 'ul', function () {
  9287. editor.execCommand('InsertUnorderedList', null, false);
  9288. });
  9289. var numlist = actionSketch('ordered-list', 'ol', function () {
  9290. editor.execCommand('InsertOrderedList', null, false);
  9291. });
  9292. var fontsizeselect = function () {
  9293. return sketch$6(realm, editor);
  9294. };
  9295. var forecolor = function () {
  9296. return sketch$8(realm, editor);
  9297. };
  9298. var styleFormats = register$1(editor);
  9299. var styleFormatsMenu = function () {
  9300. return ui(editor, styleFormats, function () {
  9301. editor.fire('scrollIntoView');
  9302. });
  9303. };
  9304. var styleselect = function () {
  9305. return forToolbar('style-formats', function (button) {
  9306. editor.fire('toReading');
  9307. realm.dropup.appear(styleFormatsMenu, Toggling.on, button);
  9308. }, derive$2([
  9309. Toggling.config({
  9310. toggleClass: resolve('toolbar-button-selected'),
  9311. toggleOnExecute: false,
  9312. aria: { mode: 'pressed' }
  9313. }),
  9314. Receiving.config({
  9315. channels: wrapAll([
  9316. receive(orientationChanged, Toggling.off),
  9317. receive(dropupDismissed, Toggling.off)
  9318. ])
  9319. })
  9320. ]), editor);
  9321. };
  9322. var feature = function (prereq, sketch) {
  9323. return {
  9324. isSupported: function () {
  9325. var buttons = editor.ui.registry.getAll().buttons;
  9326. return prereq.forall(function (p) {
  9327. return hasNonNullableKey(buttons, p);
  9328. });
  9329. },
  9330. sketch: sketch
  9331. };
  9332. };
  9333. return {
  9334. undo: feature(Optional.none(), undo),
  9335. redo: feature(Optional.none(), redo),
  9336. bold: feature(Optional.none(), bold),
  9337. italic: feature(Optional.none(), italic),
  9338. underline: feature(Optional.none(), underline),
  9339. removeformat: feature(Optional.none(), removeformat),
  9340. link: feature(Optional.none(), link),
  9341. unlink: feature(Optional.none(), unlink),
  9342. image: feature(Optional.none(), image),
  9343. bullist: feature(Optional.some('bullist'), bullist),
  9344. numlist: feature(Optional.some('numlist'), numlist),
  9345. fontsizeselect: feature(Optional.none(), fontsizeselect),
  9346. forecolor: feature(Optional.none(), forecolor),
  9347. styleselect: feature(Optional.none(), styleselect)
  9348. };
  9349. };
  9350. var detect = function (editor, features) {
  9351. var itemNames = identify(editor);
  9352. var present = {};
  9353. return bind$3(itemNames, function (iName) {
  9354. var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9355. present[iName] = true;
  9356. return r;
  9357. });
  9358. };
  9359. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9360. return {
  9361. target: target,
  9362. x: x,
  9363. y: y,
  9364. stop: stop,
  9365. prevent: prevent,
  9366. kill: kill,
  9367. raw: raw
  9368. };
  9369. };
  9370. var fromRawEvent = function (rawEvent) {
  9371. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  9372. var stop = function () {
  9373. return rawEvent.stopPropagation();
  9374. };
  9375. var prevent = function () {
  9376. return rawEvent.preventDefault();
  9377. };
  9378. var kill = compose(prevent, stop);
  9379. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9380. };
  9381. var handle = function (filter, handler) {
  9382. return function (rawEvent) {
  9383. if (filter(rawEvent)) {
  9384. handler(fromRawEvent(rawEvent));
  9385. }
  9386. };
  9387. };
  9388. var binder = function (element, event, filter, handler, useCapture) {
  9389. var wrapped = handle(filter, handler);
  9390. element.dom.addEventListener(event, wrapped, useCapture);
  9391. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9392. };
  9393. var bind$1 = function (element, event, filter, handler) {
  9394. return binder(element, event, filter, handler, false);
  9395. };
  9396. var capture$1 = function (element, event, filter, handler) {
  9397. return binder(element, event, filter, handler, true);
  9398. };
  9399. var unbind = function (element, event, handler, useCapture) {
  9400. element.dom.removeEventListener(event, handler, useCapture);
  9401. };
  9402. var filter = always;
  9403. var bind = function (element, event, handler) {
  9404. return bind$1(element, event, filter, handler);
  9405. };
  9406. var capture = function (element, event, handler) {
  9407. return capture$1(element, event, filter, handler);
  9408. };
  9409. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9410. var INTERVAL = 50;
  9411. var INSURANCE = 1000 / INTERVAL;
  9412. var get$1 = function (outerWindow) {
  9413. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9414. return { isPortrait: constant$1(isPortrait) };
  9415. };
  9416. var getActualWidth = function (outerWindow) {
  9417. var isIos = detect$1().os.isiOS();
  9418. var isPortrait = get$1(outerWindow).isPortrait();
  9419. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9420. };
  9421. var onChange = function (outerWindow, listeners) {
  9422. var win = SugarElement.fromDom(outerWindow);
  9423. var poller = null;
  9424. var change = function () {
  9425. global$2.clearInterval(poller);
  9426. var orientation = get$1(outerWindow);
  9427. listeners.onChange(orientation);
  9428. onAdjustment(function () {
  9429. listeners.onReady(orientation);
  9430. });
  9431. };
  9432. var orientationHandle = bind(win, 'orientationchange', change);
  9433. var onAdjustment = function (f) {
  9434. global$2.clearInterval(poller);
  9435. var flag = outerWindow.innerHeight;
  9436. var insurance = 0;
  9437. poller = global$2.setInterval(function () {
  9438. if (flag !== outerWindow.innerHeight) {
  9439. global$2.clearInterval(poller);
  9440. f(Optional.some(outerWindow.innerHeight));
  9441. } else if (insurance > INSURANCE) {
  9442. global$2.clearInterval(poller);
  9443. f(Optional.none());
  9444. }
  9445. insurance++;
  9446. }, INTERVAL);
  9447. };
  9448. var destroy = function () {
  9449. orientationHandle.unbind();
  9450. };
  9451. return {
  9452. onAdjustment: onAdjustment,
  9453. destroy: destroy
  9454. };
  9455. };
  9456. var setStart = function (rng, situ) {
  9457. situ.fold(function (e) {
  9458. rng.setStartBefore(e.dom);
  9459. }, function (e, o) {
  9460. rng.setStart(e.dom, o);
  9461. }, function (e) {
  9462. rng.setStartAfter(e.dom);
  9463. });
  9464. };
  9465. var setFinish = function (rng, situ) {
  9466. situ.fold(function (e) {
  9467. rng.setEndBefore(e.dom);
  9468. }, function (e, o) {
  9469. rng.setEnd(e.dom, o);
  9470. }, function (e) {
  9471. rng.setEndAfter(e.dom);
  9472. });
  9473. };
  9474. var relativeToNative = function (win, startSitu, finishSitu) {
  9475. var range = win.document.createRange();
  9476. setStart(range, startSitu);
  9477. setFinish(range, finishSitu);
  9478. return range;
  9479. };
  9480. var exactToNative = function (win, start, soffset, finish, foffset) {
  9481. var rng = win.document.createRange();
  9482. rng.setStart(start.dom, soffset);
  9483. rng.setEnd(finish.dom, foffset);
  9484. return rng;
  9485. };
  9486. var toRect$1 = function (rect) {
  9487. return {
  9488. left: rect.left,
  9489. top: rect.top,
  9490. right: rect.right,
  9491. bottom: rect.bottom,
  9492. width: rect.width,
  9493. height: rect.height
  9494. };
  9495. };
  9496. var getFirstRect$1 = function (rng) {
  9497. var rects = rng.getClientRects();
  9498. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9499. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect$1) : Optional.none();
  9500. };
  9501. var adt$3 = Adt.generate([
  9502. {
  9503. ltr: [
  9504. 'start',
  9505. 'soffset',
  9506. 'finish',
  9507. 'foffset'
  9508. ]
  9509. },
  9510. {
  9511. rtl: [
  9512. 'start',
  9513. 'soffset',
  9514. 'finish',
  9515. 'foffset'
  9516. ]
  9517. }
  9518. ]);
  9519. var fromRange = function (win, type, range) {
  9520. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  9521. };
  9522. var getRanges = function (win, selection) {
  9523. return selection.match({
  9524. domRange: function (rng) {
  9525. return {
  9526. ltr: constant$1(rng),
  9527. rtl: Optional.none
  9528. };
  9529. },
  9530. relative: function (startSitu, finishSitu) {
  9531. return {
  9532. ltr: cached(function () {
  9533. return relativeToNative(win, startSitu, finishSitu);
  9534. }),
  9535. rtl: cached(function () {
  9536. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  9537. })
  9538. };
  9539. },
  9540. exact: function (start, soffset, finish, foffset) {
  9541. return {
  9542. ltr: cached(function () {
  9543. return exactToNative(win, start, soffset, finish, foffset);
  9544. }),
  9545. rtl: cached(function () {
  9546. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  9547. })
  9548. };
  9549. }
  9550. });
  9551. };
  9552. var doDiagnose = function (win, ranges) {
  9553. var rng = ranges.ltr();
  9554. if (rng.collapsed) {
  9555. var reversed = ranges.rtl().filter(function (rev) {
  9556. return rev.collapsed === false;
  9557. });
  9558. return reversed.map(function (rev) {
  9559. return adt$3.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  9560. }).getOrThunk(function () {
  9561. return fromRange(win, adt$3.ltr, rng);
  9562. });
  9563. } else {
  9564. return fromRange(win, adt$3.ltr, rng);
  9565. }
  9566. };
  9567. var diagnose = function (win, selection) {
  9568. var ranges = getRanges(win, selection);
  9569. return doDiagnose(win, ranges);
  9570. };
  9571. var asLtrRange = function (win, selection) {
  9572. var diagnosis = diagnose(win, selection);
  9573. return diagnosis.match({
  9574. ltr: function (start, soffset, finish, foffset) {
  9575. var rng = win.document.createRange();
  9576. rng.setStart(start.dom, soffset);
  9577. rng.setEnd(finish.dom, foffset);
  9578. return rng;
  9579. },
  9580. rtl: function (start, soffset, finish, foffset) {
  9581. var rng = win.document.createRange();
  9582. rng.setStart(finish.dom, foffset);
  9583. rng.setEnd(start.dom, soffset);
  9584. return rng;
  9585. }
  9586. });
  9587. };
  9588. adt$3.ltr;
  9589. adt$3.rtl;
  9590. var create$3 = function (start, soffset, finish, foffset) {
  9591. return {
  9592. start: start,
  9593. soffset: soffset,
  9594. finish: finish,
  9595. foffset: foffset
  9596. };
  9597. };
  9598. var SimRange = { create: create$3 };
  9599. var NodeValue = function (is, name) {
  9600. var get = function (element) {
  9601. if (!is(element)) {
  9602. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9603. }
  9604. return getOption(element).getOr('');
  9605. };
  9606. var getOption = function (element) {
  9607. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  9608. };
  9609. var set = function (element, value) {
  9610. if (!is(element)) {
  9611. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9612. }
  9613. element.dom.nodeValue = value;
  9614. };
  9615. return {
  9616. get: get,
  9617. getOption: getOption,
  9618. set: set
  9619. };
  9620. };
  9621. var api = NodeValue(isText, 'text');
  9622. var getOption = function (element) {
  9623. return api.getOption(element);
  9624. };
  9625. var getEnd = function (element) {
  9626. return name$1(element) === 'img' ? 1 : getOption(element).fold(function () {
  9627. return children(element).length;
  9628. }, function (v) {
  9629. return v.length;
  9630. });
  9631. };
  9632. var adt$2 = Adt.generate([
  9633. { before: ['element'] },
  9634. {
  9635. on: [
  9636. 'element',
  9637. 'offset'
  9638. ]
  9639. },
  9640. { after: ['element'] }
  9641. ]);
  9642. var cata = function (subject, onBefore, onOn, onAfter) {
  9643. return subject.fold(onBefore, onOn, onAfter);
  9644. };
  9645. var getStart$1 = function (situ) {
  9646. return situ.fold(identity, identity, identity);
  9647. };
  9648. var before = adt$2.before;
  9649. var on = adt$2.on;
  9650. var after$1 = adt$2.after;
  9651. var Situ = {
  9652. before: before,
  9653. on: on,
  9654. after: after$1,
  9655. cata: cata,
  9656. getStart: getStart$1
  9657. };
  9658. var adt$1 = Adt.generate([
  9659. { domRange: ['rng'] },
  9660. {
  9661. relative: [
  9662. 'startSitu',
  9663. 'finishSitu'
  9664. ]
  9665. },
  9666. {
  9667. exact: [
  9668. 'start',
  9669. 'soffset',
  9670. 'finish',
  9671. 'foffset'
  9672. ]
  9673. }
  9674. ]);
  9675. var exactFromRange = function (simRange) {
  9676. return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9677. };
  9678. var getStart = function (selection) {
  9679. return selection.match({
  9680. domRange: function (rng) {
  9681. return SugarElement.fromDom(rng.startContainer);
  9682. },
  9683. relative: function (startSitu, _finishSitu) {
  9684. return Situ.getStart(startSitu);
  9685. },
  9686. exact: function (start, _soffset, _finish, _foffset) {
  9687. return start;
  9688. }
  9689. });
  9690. };
  9691. var domRange = adt$1.domRange;
  9692. var relative = adt$1.relative;
  9693. var exact = adt$1.exact;
  9694. var getWin$1 = function (selection) {
  9695. var start = getStart(selection);
  9696. return defaultView(start);
  9697. };
  9698. var range = SimRange.create;
  9699. var SimSelection = {
  9700. domRange: domRange,
  9701. relative: relative,
  9702. exact: exact,
  9703. exactFromRange: exactFromRange,
  9704. getWin: getWin$1,
  9705. range: range
  9706. };
  9707. var beforeSpecial = function (element, offset) {
  9708. var name = name$1(element);
  9709. if ('input' === name) {
  9710. return Situ.after(element);
  9711. } else if (!contains$1([
  9712. 'br',
  9713. 'img'
  9714. ], name)) {
  9715. return Situ.on(element, offset);
  9716. } else {
  9717. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9718. }
  9719. };
  9720. var preprocessExact = function (start, soffset, finish, foffset) {
  9721. var startSitu = beforeSpecial(start, soffset);
  9722. var finishSitu = beforeSpecial(finish, foffset);
  9723. return SimSelection.relative(startSitu, finishSitu);
  9724. };
  9725. var makeRange = function (start, soffset, finish, foffset) {
  9726. var doc = owner$2(start);
  9727. var rng = doc.dom.createRange();
  9728. rng.setStart(start.dom, soffset);
  9729. rng.setEnd(finish.dom, foffset);
  9730. return rng;
  9731. };
  9732. var after = function (start, soffset, finish, foffset) {
  9733. var r = makeRange(start, soffset, finish, foffset);
  9734. var same = eq(start, finish) && soffset === foffset;
  9735. return r.collapsed && !same;
  9736. };
  9737. var getNativeSelection = function (win) {
  9738. return Optional.from(win.getSelection());
  9739. };
  9740. var doSetNativeRange = function (win, rng) {
  9741. getNativeSelection(win).each(function (selection) {
  9742. selection.removeAllRanges();
  9743. selection.addRange(rng);
  9744. });
  9745. };
  9746. var doSetRange = function (win, start, soffset, finish, foffset) {
  9747. var rng = exactToNative(win, start, soffset, finish, foffset);
  9748. doSetNativeRange(win, rng);
  9749. };
  9750. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9751. selection.collapse(start.dom, soffset);
  9752. selection.extend(finish.dom, foffset);
  9753. };
  9754. var setRangeFromRelative = function (win, relative) {
  9755. return diagnose(win, relative).match({
  9756. ltr: function (start, soffset, finish, foffset) {
  9757. doSetRange(win, start, soffset, finish, foffset);
  9758. },
  9759. rtl: function (start, soffset, finish, foffset) {
  9760. getNativeSelection(win).each(function (selection) {
  9761. if (selection.setBaseAndExtent) {
  9762. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9763. } else if (selection.extend) {
  9764. try {
  9765. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9766. } catch (e) {
  9767. doSetRange(win, finish, foffset, start, soffset);
  9768. }
  9769. } else {
  9770. doSetRange(win, finish, foffset, start, soffset);
  9771. }
  9772. });
  9773. }
  9774. });
  9775. };
  9776. var setExact = function (win, start, soffset, finish, foffset) {
  9777. var relative = preprocessExact(start, soffset, finish, foffset);
  9778. setRangeFromRelative(win, relative);
  9779. };
  9780. var readRange = function (selection) {
  9781. if (selection.rangeCount > 0) {
  9782. var firstRng = selection.getRangeAt(0);
  9783. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9784. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9785. } else {
  9786. return Optional.none();
  9787. }
  9788. };
  9789. var doGetExact = function (selection) {
  9790. if (selection.anchorNode === null || selection.focusNode === null) {
  9791. return readRange(selection);
  9792. } else {
  9793. var anchor = SugarElement.fromDom(selection.anchorNode);
  9794. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9795. return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9796. }
  9797. };
  9798. var getExact = function (win) {
  9799. return getNativeSelection(win).filter(function (sel) {
  9800. return sel.rangeCount > 0;
  9801. }).bind(doGetExact);
  9802. };
  9803. var get = function (win) {
  9804. return getExact(win).map(function (range) {
  9805. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9806. });
  9807. };
  9808. var getFirstRect = function (win, selection) {
  9809. var rng = asLtrRange(win, selection);
  9810. return getFirstRect$1(rng);
  9811. };
  9812. var clear = function (win) {
  9813. getNativeSelection(win).each(function (selection) {
  9814. return selection.removeAllRanges();
  9815. });
  9816. };
  9817. var getBodyFromFrame = function (frame) {
  9818. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document.body));
  9819. };
  9820. var getDocFromFrame = function (frame) {
  9821. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document));
  9822. };
  9823. var getWinFromFrame = function (frame) {
  9824. return Optional.from(frame.dom.contentWindow);
  9825. };
  9826. var getSelectionFromFrame = function (frame) {
  9827. var optWin = getWinFromFrame(frame);
  9828. return optWin.bind(getExact);
  9829. };
  9830. var getFrame = function (editor) {
  9831. return editor.getFrame();
  9832. };
  9833. var getOrDerive = function (name, f) {
  9834. return function (editor) {
  9835. var g = editor[name].getOrThunk(function () {
  9836. var frame = getFrame(editor);
  9837. return function () {
  9838. return f(frame);
  9839. };
  9840. });
  9841. return g();
  9842. };
  9843. };
  9844. var getOrListen = function (editor, doc, name, type) {
  9845. return editor[name].getOrThunk(function () {
  9846. return function (handler) {
  9847. return bind(doc, type, handler);
  9848. };
  9849. });
  9850. };
  9851. var getActiveApi = function (editor) {
  9852. var frame = getFrame(editor);
  9853. var tryFallbackBox = function (win) {
  9854. var isCollapsed = function (sel) {
  9855. return eq(sel.start, sel.finish) && sel.soffset === sel.foffset;
  9856. };
  9857. var toStartRect = function (sel) {
  9858. var rect = sel.start.dom.getBoundingClientRect();
  9859. return rect.width > 0 || rect.height > 0 ? Optional.some(rect) : Optional.none();
  9860. };
  9861. return getExact(win).filter(isCollapsed).bind(toStartRect);
  9862. };
  9863. return getBodyFromFrame(frame).bind(function (body) {
  9864. return getDocFromFrame(frame).bind(function (doc) {
  9865. return getWinFromFrame(frame).map(function (win) {
  9866. var html = SugarElement.fromDom(doc.dom.documentElement);
  9867. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  9868. return function () {
  9869. return get(win).bind(function (sel) {
  9870. return getFirstRect(win, sel).orThunk(function () {
  9871. return tryFallbackBox(win);
  9872. });
  9873. });
  9874. };
  9875. });
  9876. var setSelection = editor.setSelection.getOrThunk(function () {
  9877. return function (start, soffset, finish, foffset) {
  9878. setExact(win, start, soffset, finish, foffset);
  9879. };
  9880. });
  9881. var clearSelection = editor.clearSelection.getOrThunk(function () {
  9882. return function () {
  9883. clear(win);
  9884. };
  9885. });
  9886. return {
  9887. body: body,
  9888. doc: doc,
  9889. win: win,
  9890. html: html,
  9891. getSelection: curry(getSelectionFromFrame, frame),
  9892. setSelection: setSelection,
  9893. clearSelection: clearSelection,
  9894. frame: frame,
  9895. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  9896. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  9897. onDomChanged: editor.onDomChanged,
  9898. onScrollToCursor: editor.onScrollToCursor,
  9899. onScrollToElement: editor.onScrollToElement,
  9900. onToReading: editor.onToReading,
  9901. onToEditing: editor.onToEditing,
  9902. onToolbarScrollStart: editor.onToolbarScrollStart,
  9903. onTouchContent: editor.onTouchContent,
  9904. onTapContent: editor.onTapContent,
  9905. onTouchToolstrip: editor.onTouchToolstrip,
  9906. getCursorBox: getCursorBox
  9907. };
  9908. });
  9909. });
  9910. });
  9911. };
  9912. var getWin = getOrDerive('getWin', getWinFromFrame);
  9913. var tag = function () {
  9914. var head = first$1('head').getOrDie();
  9915. var nu = function () {
  9916. var meta = SugarElement.fromTag('meta');
  9917. set$8(meta, 'name', 'viewport');
  9918. append$2(head, meta);
  9919. return meta;
  9920. };
  9921. var element = first$1('meta[name="viewport"]').getOrThunk(nu);
  9922. var backup = get$b(element, 'content');
  9923. var maximize = function () {
  9924. set$8(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  9925. };
  9926. var restore = function () {
  9927. if (backup !== undefined && backup !== null && backup.length > 0) {
  9928. set$8(element, 'content', backup);
  9929. } else {
  9930. set$8(element, 'content', 'user-scalable=yes');
  9931. }
  9932. };
  9933. return {
  9934. maximize: maximize,
  9935. restore: restore
  9936. };
  9937. };
  9938. var attr = 'data-ephox-mobile-fullscreen-style';
  9939. var siblingStyles = 'display:none!important;';
  9940. var ancestorPosition = 'position:absolute!important;';
  9941. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  9942. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  9943. var isAndroid = detect$1().os.isAndroid();
  9944. var matchColor = function (editorBody) {
  9945. var color = get$8(editorBody, 'background-color');
  9946. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  9947. };
  9948. var clobberStyles = function (container, editorBody) {
  9949. var gatherSiblings = function (element) {
  9950. return siblings(element, '*');
  9951. };
  9952. var clobber = function (clobberStyle) {
  9953. return function (element) {
  9954. var styles = get$b(element, 'style');
  9955. var backup = styles === undefined ? 'no-styles' : styles.trim();
  9956. if (backup === clobberStyle) {
  9957. return;
  9958. } else {
  9959. set$8(element, attr, backup);
  9960. set$8(element, 'style', clobberStyle);
  9961. }
  9962. };
  9963. };
  9964. var ancestors$1 = ancestors(container, '*');
  9965. var siblings$1 = bind$3(ancestors$1, gatherSiblings);
  9966. var bgColor = matchColor(editorBody);
  9967. each$1(siblings$1, clobber(siblingStyles));
  9968. each$1(ancestors$1, clobber(ancestorPosition + ancestorStyles + bgColor));
  9969. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  9970. clobber(containerStyles + ancestorStyles + bgColor)(container);
  9971. };
  9972. var restoreStyles = function () {
  9973. var clobberedEls = all('[' + attr + ']');
  9974. each$1(clobberedEls, function (element) {
  9975. var restore = get$b(element, attr);
  9976. if (restore !== 'no-styles') {
  9977. set$8(element, 'style', restore);
  9978. } else {
  9979. remove$6(element, 'style');
  9980. }
  9981. remove$6(element, attr);
  9982. });
  9983. };
  9984. var DelayedFunction = function (fun, delay) {
  9985. var ref = null;
  9986. var schedule = function () {
  9987. var args = [];
  9988. for (var _i = 0; _i < arguments.length; _i++) {
  9989. args[_i] = arguments[_i];
  9990. }
  9991. ref = setTimeout(function () {
  9992. fun.apply(null, args);
  9993. ref = null;
  9994. }, delay);
  9995. };
  9996. var cancel = function () {
  9997. if (ref !== null) {
  9998. clearTimeout(ref);
  9999. ref = null;
  10000. }
  10001. };
  10002. return {
  10003. cancel: cancel,
  10004. schedule: schedule
  10005. };
  10006. };
  10007. var SIGNIFICANT_MOVE = 5;
  10008. var LONGPRESS_DELAY = 400;
  10009. var getTouch = function (event) {
  10010. var raw = event.raw;
  10011. if (raw.touches === undefined || raw.touches.length !== 1) {
  10012. return Optional.none();
  10013. }
  10014. return Optional.some(raw.touches[0]);
  10015. };
  10016. var isFarEnough = function (touch, data) {
  10017. var distX = Math.abs(touch.clientX - data.x);
  10018. var distY = Math.abs(touch.clientY - data.y);
  10019. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  10020. };
  10021. var monitor$1 = function (settings) {
  10022. var startData = value();
  10023. var longpressFired = Cell(false);
  10024. var longpress$1 = DelayedFunction(function (event) {
  10025. settings.triggerEvent(longpress(), event);
  10026. longpressFired.set(true);
  10027. }, LONGPRESS_DELAY);
  10028. var handleTouchstart = function (event) {
  10029. getTouch(event).each(function (touch) {
  10030. longpress$1.cancel();
  10031. var data = {
  10032. x: touch.clientX,
  10033. y: touch.clientY,
  10034. target: event.target
  10035. };
  10036. longpress$1.schedule(event);
  10037. longpressFired.set(false);
  10038. startData.set(data);
  10039. });
  10040. return Optional.none();
  10041. };
  10042. var handleTouchmove = function (event) {
  10043. longpress$1.cancel();
  10044. getTouch(event).each(function (touch) {
  10045. startData.on(function (data) {
  10046. if (isFarEnough(touch, data)) {
  10047. startData.clear();
  10048. }
  10049. });
  10050. });
  10051. return Optional.none();
  10052. };
  10053. var handleTouchend = function (event) {
  10054. longpress$1.cancel();
  10055. var isSame = function (data) {
  10056. return eq(data.target, event.target);
  10057. };
  10058. return startData.get().filter(isSame).map(function (_data) {
  10059. if (longpressFired.get()) {
  10060. event.prevent();
  10061. return false;
  10062. } else {
  10063. return settings.triggerEvent(tap(), event);
  10064. }
  10065. });
  10066. };
  10067. var handlers = wrapAll([
  10068. {
  10069. key: touchstart(),
  10070. value: handleTouchstart
  10071. },
  10072. {
  10073. key: touchmove(),
  10074. value: handleTouchmove
  10075. },
  10076. {
  10077. key: touchend(),
  10078. value: handleTouchend
  10079. }
  10080. ]);
  10081. var fireIfReady = function (event, type) {
  10082. return get$c(handlers, type).bind(function (handler) {
  10083. return handler(event);
  10084. });
  10085. };
  10086. return { fireIfReady: fireIfReady };
  10087. };
  10088. var monitor = function (editorApi) {
  10089. var tapEvent = monitor$1({
  10090. triggerEvent: function (type, evt) {
  10091. editorApi.onTapContent(evt);
  10092. }
  10093. });
  10094. var onTouchend = function () {
  10095. return bind(editorApi.body, 'touchend', function (evt) {
  10096. tapEvent.fireIfReady(evt, 'touchend');
  10097. });
  10098. };
  10099. var onTouchmove = function () {
  10100. return bind(editorApi.body, 'touchmove', function (evt) {
  10101. tapEvent.fireIfReady(evt, 'touchmove');
  10102. });
  10103. };
  10104. var fireTouchstart = function (evt) {
  10105. tapEvent.fireIfReady(evt, 'touchstart');
  10106. };
  10107. return {
  10108. fireTouchstart: fireTouchstart,
  10109. onTouchend: onTouchend,
  10110. onTouchmove: onTouchmove
  10111. };
  10112. };
  10113. var isAndroid6 = detect$1().os.version.major >= 6;
  10114. var initEvents$1 = function (editorApi, toolstrip, alloy) {
  10115. var tapping = monitor(editorApi);
  10116. var outerDoc = owner$2(toolstrip);
  10117. var isRanged = function (sel) {
  10118. return !eq(sel.start, sel.finish) || sel.soffset !== sel.foffset;
  10119. };
  10120. var hasRangeInUi = function () {
  10121. return active(outerDoc).filter(function (input) {
  10122. return name$1(input) === 'input';
  10123. }).exists(function (input) {
  10124. return input.dom.selectionStart !== input.dom.selectionEnd;
  10125. });
  10126. };
  10127. var updateMargin = function () {
  10128. var rangeInContent = editorApi.doc.dom.hasFocus() && editorApi.getSelection().exists(isRanged);
  10129. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  10130. };
  10131. var listeners = [
  10132. bind(editorApi.body, 'touchstart', function (evt) {
  10133. editorApi.onTouchContent();
  10134. tapping.fireTouchstart(evt);
  10135. }),
  10136. tapping.onTouchmove(),
  10137. tapping.onTouchend(),
  10138. bind(toolstrip, 'touchstart', function (_evt) {
  10139. editorApi.onTouchToolstrip();
  10140. }),
  10141. editorApi.onToReading(function () {
  10142. blur$1(editorApi.body);
  10143. }),
  10144. editorApi.onToEditing(noop),
  10145. editorApi.onScrollToCursor(function (tinyEvent) {
  10146. tinyEvent.preventDefault();
  10147. editorApi.getCursorBox().each(function (bounds) {
  10148. var cWin = editorApi.win;
  10149. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10150. var cScrollBy = isOutside ? bounds.bottom - cWin.innerHeight + 50 : 0;
  10151. if (cScrollBy !== 0) {
  10152. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10153. }
  10154. });
  10155. })
  10156. ].concat(isAndroid6 === true ? [] : [
  10157. bind(SugarElement.fromDom(editorApi.win), 'blur', function () {
  10158. alloy.getByDom(toolstrip).each(Toggling.off);
  10159. }),
  10160. bind(outerDoc, 'select', updateMargin),
  10161. bind(editorApi.doc, 'selectionchange', updateMargin)
  10162. ]);
  10163. var destroy = function () {
  10164. each$1(listeners, function (l) {
  10165. l.unbind();
  10166. });
  10167. };
  10168. return { destroy: destroy };
  10169. };
  10170. var safeParse = function (element, attribute) {
  10171. var parsed = parseInt(get$b(element, attribute), 10);
  10172. return isNaN(parsed) ? 0 : parsed;
  10173. };
  10174. var COLLAPSED_WIDTH = 2;
  10175. var collapsedRect = function (rect) {
  10176. return __assign(__assign({}, rect), { width: COLLAPSED_WIDTH });
  10177. };
  10178. var toRect = function (rawRect) {
  10179. return {
  10180. left: rawRect.left,
  10181. top: rawRect.top,
  10182. right: rawRect.right,
  10183. bottom: rawRect.bottom,
  10184. width: rawRect.width,
  10185. height: rawRect.height
  10186. };
  10187. };
  10188. var getRectsFromRange = function (range) {
  10189. if (!range.collapsed) {
  10190. return map$2(range.getClientRects(), toRect);
  10191. } else {
  10192. var start_1 = SugarElement.fromDom(range.startContainer);
  10193. return parent(start_1).bind(function (parent) {
  10194. var selection = SimSelection.exact(start_1, range.startOffset, parent, getEnd(parent));
  10195. var optRect = getFirstRect(range.startContainer.ownerDocument.defaultView, selection);
  10196. return optRect.map(collapsedRect).map(pure$2);
  10197. }).getOr([]);
  10198. }
  10199. };
  10200. var getRectangles = function (cWin) {
  10201. var sel = cWin.getSelection();
  10202. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  10203. };
  10204. var autocompleteHack = function () {
  10205. return function (f) {
  10206. global$2.setTimeout(function () {
  10207. f();
  10208. }, 0);
  10209. };
  10210. };
  10211. var resume$1 = function (cWin) {
  10212. cWin.focus();
  10213. var iBody = SugarElement.fromDom(cWin.document.body);
  10214. var inInput = active().exists(function (elem) {
  10215. return contains$1([
  10216. 'input',
  10217. 'textarea'
  10218. ], name$1(elem));
  10219. });
  10220. var transaction = inInput ? autocompleteHack() : apply$1;
  10221. transaction(function () {
  10222. active().each(blur$1);
  10223. focus$3(iBody);
  10224. });
  10225. };
  10226. var EXTRA_SPACING = 50;
  10227. var data = 'data-' + resolve('last-outer-height');
  10228. var setLastHeight = function (cBody, value) {
  10229. set$8(cBody, data, value);
  10230. };
  10231. var getLastHeight = function (cBody) {
  10232. return safeParse(cBody, data);
  10233. };
  10234. var getBoundsFrom = function (rect) {
  10235. return {
  10236. top: rect.top,
  10237. bottom: rect.top + rect.height
  10238. };
  10239. };
  10240. var getBounds = function (cWin) {
  10241. var rects = getRectangles(cWin);
  10242. return rects.length > 0 ? Optional.some(rects[0]).map(getBoundsFrom) : Optional.none();
  10243. };
  10244. var findDelta = function (outerWindow, cBody) {
  10245. var last = getLastHeight(cBody);
  10246. var current = outerWindow.innerHeight;
  10247. return last > current ? Optional.some(last - current) : Optional.none();
  10248. };
  10249. var calculate = function (cWin, bounds, delta) {
  10250. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10251. return isOutside ? Math.min(delta, bounds.bottom - cWin.innerHeight + EXTRA_SPACING) : 0;
  10252. };
  10253. var setup$2 = function (outerWindow, cWin) {
  10254. var cBody = SugarElement.fromDom(cWin.document.body);
  10255. var toEditing = function () {
  10256. resume$1(cWin);
  10257. };
  10258. var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () {
  10259. findDelta(outerWindow, cBody).each(function (delta) {
  10260. getBounds(cWin).each(function (bounds) {
  10261. var cScrollBy = calculate(cWin, bounds, delta);
  10262. if (cScrollBy !== 0) {
  10263. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10264. }
  10265. });
  10266. });
  10267. setLastHeight(cBody, outerWindow.innerHeight);
  10268. });
  10269. setLastHeight(cBody, outerWindow.innerHeight);
  10270. var destroy = function () {
  10271. onResize.unbind();
  10272. };
  10273. return {
  10274. toEditing: toEditing,
  10275. destroy: destroy
  10276. };
  10277. };
  10278. var create$2 = function (platform, mask) {
  10279. var meta = tag();
  10280. var androidApi = api$2();
  10281. var androidEvents = api$2();
  10282. var enter = function () {
  10283. mask.hide();
  10284. add$1(platform.container, resolve('fullscreen-maximized'));
  10285. add$1(platform.container, resolve('android-maximized'));
  10286. meta.maximize();
  10287. add$1(platform.body, resolve('android-scroll-reload'));
  10288. androidApi.set(setup$2(platform.win, getWin(platform.editor).getOrDie('no')));
  10289. getActiveApi(platform.editor).each(function (editorApi) {
  10290. clobberStyles(platform.container, editorApi.body);
  10291. androidEvents.set(initEvents$1(editorApi, platform.toolstrip, platform.alloy));
  10292. });
  10293. };
  10294. var exit = function () {
  10295. meta.restore();
  10296. mask.show();
  10297. remove$3(platform.container, resolve('fullscreen-maximized'));
  10298. remove$3(platform.container, resolve('android-maximized'));
  10299. restoreStyles();
  10300. remove$3(platform.body, resolve('android-scroll-reload'));
  10301. androidEvents.clear();
  10302. androidApi.clear();
  10303. };
  10304. return {
  10305. enter: enter,
  10306. exit: exit
  10307. };
  10308. };
  10309. var first = function (fn, rate) {
  10310. var timer = null;
  10311. var cancel = function () {
  10312. if (!isNull(timer)) {
  10313. clearTimeout(timer);
  10314. timer = null;
  10315. }
  10316. };
  10317. var throttle = function () {
  10318. var args = [];
  10319. for (var _i = 0; _i < arguments.length; _i++) {
  10320. args[_i] = arguments[_i];
  10321. }
  10322. if (isNull(timer)) {
  10323. timer = setTimeout(function () {
  10324. timer = null;
  10325. fn.apply(null, args);
  10326. }, rate);
  10327. }
  10328. };
  10329. return {
  10330. cancel: cancel,
  10331. throttle: throttle
  10332. };
  10333. };
  10334. var last = function (fn, rate) {
  10335. var timer = null;
  10336. var cancel = function () {
  10337. if (!isNull(timer)) {
  10338. clearTimeout(timer);
  10339. timer = null;
  10340. }
  10341. };
  10342. var throttle = function () {
  10343. var args = [];
  10344. for (var _i = 0; _i < arguments.length; _i++) {
  10345. args[_i] = arguments[_i];
  10346. }
  10347. cancel();
  10348. timer = setTimeout(function () {
  10349. timer = null;
  10350. fn.apply(null, args);
  10351. }, rate);
  10352. };
  10353. return {
  10354. cancel: cancel,
  10355. throttle: throttle
  10356. };
  10357. };
  10358. var sketch = function (onView, _translate) {
  10359. var memIcon = record(Container.sketch({
  10360. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10361. containerBehaviours: derive$2([Toggling.config({
  10362. toggleClass: resolve('mask-tap-icon-selected'),
  10363. toggleOnExecute: false
  10364. })])
  10365. }));
  10366. var onViewThrottle = first(onView, 200);
  10367. return Container.sketch({
  10368. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10369. components: [Container.sketch({
  10370. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10371. components: [Button.sketch({
  10372. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10373. components: [memIcon.asSpec()],
  10374. action: function (_button) {
  10375. onViewThrottle.throttle();
  10376. },
  10377. buttonBehaviours: derive$2([Toggling.config({ toggleClass: resolve('mask-tap-icon-selected') })])
  10378. })]
  10379. })]
  10380. });
  10381. };
  10382. var unbindNoop = constant$1({ unbind: noop });
  10383. var MobileSchema = objOf([
  10384. requiredObjOf('editor', [
  10385. required$1('getFrame'),
  10386. option('getBody'),
  10387. option('getDoc'),
  10388. option('getWin'),
  10389. option('getSelection'),
  10390. option('setSelection'),
  10391. option('clearSelection'),
  10392. option('cursorSaver'),
  10393. option('onKeyup'),
  10394. option('onNodeChanged'),
  10395. option('getCursorBox'),
  10396. required$1('onDomChanged'),
  10397. defaulted('onTouchContent', noop),
  10398. defaulted('onTapContent', noop),
  10399. defaulted('onTouchToolstrip', noop),
  10400. defaulted('onScrollToCursor', unbindNoop),
  10401. defaulted('onScrollToElement', unbindNoop),
  10402. defaulted('onToEditing', unbindNoop),
  10403. defaulted('onToReading', unbindNoop),
  10404. defaulted('onToolbarScrollStart', identity)
  10405. ]),
  10406. required$1('socket'),
  10407. required$1('toolstrip'),
  10408. required$1('dropup'),
  10409. required$1('toolbar'),
  10410. required$1('container'),
  10411. required$1('alloy'),
  10412. customField('win', function (spec) {
  10413. return owner$2(spec.socket).dom.defaultView;
  10414. }),
  10415. customField('body', function (spec) {
  10416. return SugarElement.fromDom(spec.socket.dom.ownerDocument.body);
  10417. }),
  10418. defaulted('translate', identity),
  10419. defaulted('setReadOnly', noop),
  10420. defaulted('readOnlyOnInit', always)
  10421. ]);
  10422. var produce$1 = function (raw) {
  10423. var mobile = asRawOrDie$1('Getting AndroidWebapp schema', MobileSchema, raw);
  10424. set$5(mobile.toolstrip, 'width', '100%');
  10425. var onTap = function () {
  10426. mobile.setReadOnly(mobile.readOnlyOnInit());
  10427. mode.enter();
  10428. };
  10429. var mask = build$1(sketch(onTap, mobile.translate));
  10430. mobile.alloy.add(mask);
  10431. var maskApi = {
  10432. show: function () {
  10433. mobile.alloy.add(mask);
  10434. },
  10435. hide: function () {
  10436. mobile.alloy.remove(mask);
  10437. }
  10438. };
  10439. append$2(mobile.container, mask.element);
  10440. var mode = create$2(mobile, maskApi);
  10441. return {
  10442. setReadOnly: mobile.setReadOnly,
  10443. refreshStructure: noop,
  10444. enter: mode.enter,
  10445. exit: mode.exit,
  10446. destroy: noop
  10447. };
  10448. };
  10449. var schema$1 = constant$1([
  10450. required$1('dom'),
  10451. defaulted('shell', true),
  10452. field$1('toolbarBehaviours', [Replacing])
  10453. ]);
  10454. var enhanceGroups = function () {
  10455. return { behaviours: derive$2([Replacing.config({})]) };
  10456. };
  10457. var parts$1 = constant$1([optional({
  10458. name: 'groups',
  10459. overrides: enhanceGroups
  10460. })]);
  10461. var factory$1 = function (detail, components, _spec, _externals) {
  10462. var setGroups = function (toolbar, groups) {
  10463. getGroupContainer(toolbar).fold(function () {
  10464. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10465. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10466. }, function (container) {
  10467. Replacing.set(container, groups);
  10468. });
  10469. };
  10470. var getGroupContainer = function (component) {
  10471. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  10472. };
  10473. var extra = detail.shell ? {
  10474. behaviours: [Replacing.config({})],
  10475. components: []
  10476. } : {
  10477. behaviours: [],
  10478. components: components
  10479. };
  10480. return {
  10481. uid: detail.uid,
  10482. dom: detail.dom,
  10483. components: extra.components,
  10484. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10485. apis: { setGroups: setGroups },
  10486. domModification: { attributes: { role: 'group' } }
  10487. };
  10488. };
  10489. var Toolbar = composite({
  10490. name: 'Toolbar',
  10491. configFields: schema$1(),
  10492. partFields: parts$1(),
  10493. factory: factory$1,
  10494. apis: {
  10495. setGroups: function (apis, toolbar, groups) {
  10496. apis.setGroups(toolbar, groups);
  10497. }
  10498. }
  10499. });
  10500. var schema = constant$1([
  10501. required$1('items'),
  10502. markers(['itemSelector']),
  10503. field$1('tgroupBehaviours', [Keying])
  10504. ]);
  10505. var parts = constant$1([group({
  10506. name: 'items',
  10507. unit: 'item'
  10508. })]);
  10509. var factory = function (detail, components, _spec, _externals) {
  10510. return {
  10511. uid: detail.uid,
  10512. dom: detail.dom,
  10513. components: components,
  10514. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10515. mode: 'flow',
  10516. selector: detail.markers.itemSelector
  10517. })]),
  10518. domModification: { attributes: { role: 'toolbar' } }
  10519. };
  10520. };
  10521. var ToolbarGroup = composite({
  10522. name: 'ToolbarGroup',
  10523. configFields: schema(),
  10524. partFields: parts(),
  10525. factory: factory
  10526. });
  10527. var dataHorizontal = 'data-' + resolve('horizontal-scroll');
  10528. var canScrollVertically = function (container) {
  10529. container.dom.scrollTop = 1;
  10530. var result = container.dom.scrollTop !== 0;
  10531. container.dom.scrollTop = 0;
  10532. return result;
  10533. };
  10534. var canScrollHorizontally = function (container) {
  10535. container.dom.scrollLeft = 1;
  10536. var result = container.dom.scrollLeft !== 0;
  10537. container.dom.scrollLeft = 0;
  10538. return result;
  10539. };
  10540. var hasVerticalScroll = function (container) {
  10541. return container.dom.scrollTop > 0 || canScrollVertically(container);
  10542. };
  10543. var hasHorizontalScroll = function (container) {
  10544. return container.dom.scrollLeft > 0 || canScrollHorizontally(container);
  10545. };
  10546. var markAsHorizontal = function (container) {
  10547. set$8(container, dataHorizontal, 'true');
  10548. };
  10549. var hasScroll = function (container) {
  10550. return get$b(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10551. };
  10552. var exclusive = function (scope, selector) {
  10553. return bind(scope, 'touchmove', function (event) {
  10554. closest$1(event.target, selector).filter(hasScroll).fold(function () {
  10555. event.prevent();
  10556. }, noop);
  10557. });
  10558. };
  10559. var ScrollingToolbar = function () {
  10560. var makeGroup = function (gSpec) {
  10561. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10562. return {
  10563. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10564. tgroupBehaviours: derive$2([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, _simulatedEvent) {
  10565. set$5(component.element, 'overflow-x', 'auto');
  10566. markAsHorizontal(component.element);
  10567. register$2(component.element);
  10568. })] : [])]),
  10569. components: [Container.sketch({ components: [ToolbarGroup.parts.items({})] })],
  10570. markers: { itemSelector: '.' + resolve('toolbar-group-item') },
  10571. items: gSpec.items
  10572. };
  10573. };
  10574. var toolbar = build$1(Toolbar.sketch({
  10575. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10576. components: [Toolbar.parts.groups({})],
  10577. toolbarBehaviours: derive$2([
  10578. Toggling.config({
  10579. toggleClass: resolve('context-toolbar'),
  10580. toggleOnExecute: false,
  10581. aria: { mode: 'none' }
  10582. }),
  10583. Keying.config({ mode: 'cyclic' })
  10584. ]),
  10585. shell: true
  10586. }));
  10587. var wrapper = build$1(Container.sketch({
  10588. dom: { classes: [resolve('toolstrip')] },
  10589. components: [premade(toolbar)],
  10590. containerBehaviours: derive$2([Toggling.config({
  10591. toggleClass: resolve('android-selection-context-toolbar'),
  10592. toggleOnExecute: false
  10593. })])
  10594. }));
  10595. var resetGroups = function () {
  10596. Toolbar.setGroups(toolbar, initGroups.get());
  10597. Toggling.off(toolbar);
  10598. };
  10599. var initGroups = Cell([]);
  10600. var setGroups = function (gs) {
  10601. initGroups.set(gs);
  10602. resetGroups();
  10603. };
  10604. var createGroups = function (gs) {
  10605. return map$2(gs, compose(ToolbarGroup.sketch, makeGroup));
  10606. };
  10607. var refresh = function () {
  10608. };
  10609. var setContextToolbar = function (gs) {
  10610. Toggling.on(toolbar);
  10611. Toolbar.setGroups(toolbar, gs);
  10612. };
  10613. var restoreToolbar = function () {
  10614. if (Toggling.isOn(toolbar)) {
  10615. resetGroups();
  10616. }
  10617. };
  10618. var focus = function () {
  10619. Keying.focusIn(toolbar);
  10620. };
  10621. return {
  10622. wrapper: wrapper,
  10623. toolbar: toolbar,
  10624. createGroups: createGroups,
  10625. setGroups: setGroups,
  10626. setContextToolbar: setContextToolbar,
  10627. restoreToolbar: restoreToolbar,
  10628. refresh: refresh,
  10629. focus: focus
  10630. };
  10631. };
  10632. var makeEditSwitch = function (webapp) {
  10633. return build$1(Button.sketch({
  10634. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10635. action: function () {
  10636. webapp.run(function (w) {
  10637. w.setReadOnly(false);
  10638. });
  10639. }
  10640. }));
  10641. };
  10642. var makeSocket = function () {
  10643. return build$1(Container.sketch({
  10644. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10645. components: [],
  10646. containerBehaviours: derive$2([Replacing.config({})])
  10647. }));
  10648. };
  10649. var showEdit = function (socket, switchToEdit) {
  10650. Replacing.append(socket, premade(switchToEdit));
  10651. };
  10652. var hideEdit = function (socket, switchToEdit) {
  10653. Replacing.remove(socket, switchToEdit);
  10654. };
  10655. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10656. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10657. swap(root);
  10658. var f = readOnly ? showEdit : hideEdit;
  10659. f(socket, switchToEdit);
  10660. };
  10661. var getAnimationRoot = function (component, slideConfig) {
  10662. return slideConfig.getAnimationRoot.fold(function () {
  10663. return component.element;
  10664. }, function (get) {
  10665. return get(component);
  10666. });
  10667. };
  10668. var getDimensionProperty = function (slideConfig) {
  10669. return slideConfig.dimension.property;
  10670. };
  10671. var getDimension = function (slideConfig, elem) {
  10672. return slideConfig.dimension.getDimension(elem);
  10673. };
  10674. var disableTransitions = function (component, slideConfig) {
  10675. var root = getAnimationRoot(component, slideConfig);
  10676. remove$1(root, [
  10677. slideConfig.shrinkingClass,
  10678. slideConfig.growingClass
  10679. ]);
  10680. };
  10681. var setShrunk = function (component, slideConfig) {
  10682. remove$3(component.element, slideConfig.openClass);
  10683. add$1(component.element, slideConfig.closedClass);
  10684. set$5(component.element, getDimensionProperty(slideConfig), '0px');
  10685. reflow(component.element);
  10686. };
  10687. var setGrown = function (component, slideConfig) {
  10688. remove$3(component.element, slideConfig.closedClass);
  10689. add$1(component.element, slideConfig.openClass);
  10690. remove$2(component.element, getDimensionProperty(slideConfig));
  10691. };
  10692. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10693. slideState.setCollapsed();
  10694. set$5(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  10695. reflow(component.element);
  10696. disableTransitions(component, slideConfig);
  10697. setShrunk(component, slideConfig);
  10698. slideConfig.onStartShrink(component);
  10699. slideConfig.onShrunk(component);
  10700. };
  10701. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10702. var size = calculatedSize.getOrThunk(function () {
  10703. return getDimension(slideConfig, component.element);
  10704. });
  10705. slideState.setCollapsed();
  10706. set$5(component.element, getDimensionProperty(slideConfig), size);
  10707. reflow(component.element);
  10708. var root = getAnimationRoot(component, slideConfig);
  10709. remove$3(root, slideConfig.growingClass);
  10710. add$1(root, slideConfig.shrinkingClass);
  10711. setShrunk(component, slideConfig);
  10712. slideConfig.onStartShrink(component);
  10713. };
  10714. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10715. var size = getDimension(slideConfig, component.element);
  10716. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10717. shrinker(component, slideConfig, slideState, Optional.some(size));
  10718. };
  10719. var doStartGrow = function (component, slideConfig, slideState) {
  10720. var root = getAnimationRoot(component, slideConfig);
  10721. var wasShrinking = has(root, slideConfig.shrinkingClass);
  10722. var beforeSize = getDimension(slideConfig, component.element);
  10723. setGrown(component, slideConfig);
  10724. var fullSize = getDimension(slideConfig, component.element);
  10725. var startPartialGrow = function () {
  10726. set$5(component.element, getDimensionProperty(slideConfig), beforeSize);
  10727. reflow(component.element);
  10728. };
  10729. var startCompleteGrow = function () {
  10730. setShrunk(component, slideConfig);
  10731. };
  10732. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  10733. setStartSize();
  10734. remove$3(root, slideConfig.shrinkingClass);
  10735. add$1(root, slideConfig.growingClass);
  10736. setGrown(component, slideConfig);
  10737. set$5(component.element, getDimensionProperty(slideConfig), fullSize);
  10738. slideState.setExpanded();
  10739. slideConfig.onStartGrow(component);
  10740. };
  10741. var refresh$1 = function (component, slideConfig, slideState) {
  10742. if (slideState.isExpanded()) {
  10743. remove$2(component.element, getDimensionProperty(slideConfig));
  10744. var fullSize = getDimension(slideConfig, component.element);
  10745. set$5(component.element, getDimensionProperty(slideConfig), fullSize);
  10746. }
  10747. };
  10748. var grow = function (component, slideConfig, slideState) {
  10749. if (!slideState.isExpanded()) {
  10750. doStartGrow(component, slideConfig, slideState);
  10751. }
  10752. };
  10753. var shrink = function (component, slideConfig, slideState) {
  10754. if (slideState.isExpanded()) {
  10755. doStartSmartShrink(component, slideConfig, slideState);
  10756. }
  10757. };
  10758. var immediateShrink = function (component, slideConfig, slideState) {
  10759. if (slideState.isExpanded()) {
  10760. doImmediateShrink(component, slideConfig, slideState);
  10761. }
  10762. };
  10763. var hasGrown = function (component, slideConfig, slideState) {
  10764. return slideState.isExpanded();
  10765. };
  10766. var hasShrunk = function (component, slideConfig, slideState) {
  10767. return slideState.isCollapsed();
  10768. };
  10769. var isGrowing = function (component, slideConfig, _slideState) {
  10770. var root = getAnimationRoot(component, slideConfig);
  10771. return has(root, slideConfig.growingClass) === true;
  10772. };
  10773. var isShrinking = function (component, slideConfig, _slideState) {
  10774. var root = getAnimationRoot(component, slideConfig);
  10775. return has(root, slideConfig.shrinkingClass) === true;
  10776. };
  10777. var isTransitioning = function (component, slideConfig, slideState) {
  10778. return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  10779. };
  10780. var toggleGrow = function (component, slideConfig, slideState) {
  10781. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  10782. f(component, slideConfig, slideState);
  10783. };
  10784. var SlidingApis = /*#__PURE__*/Object.freeze({
  10785. __proto__: null,
  10786. refresh: refresh$1,
  10787. grow: grow,
  10788. shrink: shrink,
  10789. immediateShrink: immediateShrink,
  10790. hasGrown: hasGrown,
  10791. hasShrunk: hasShrunk,
  10792. isGrowing: isGrowing,
  10793. isShrinking: isShrinking,
  10794. isTransitioning: isTransitioning,
  10795. toggleGrow: toggleGrow,
  10796. disableTransitions: disableTransitions
  10797. });
  10798. var exhibit = function (base, slideConfig, _slideState) {
  10799. var expanded = slideConfig.expanded;
  10800. return expanded ? nu$3({
  10801. classes: [slideConfig.openClass],
  10802. styles: {}
  10803. }) : nu$3({
  10804. classes: [slideConfig.closedClass],
  10805. styles: wrap(slideConfig.dimension.property, '0px')
  10806. });
  10807. };
  10808. var events = function (slideConfig, slideState) {
  10809. return derive$3([runOnSource(transitionend(), function (component, simulatedEvent) {
  10810. var raw = simulatedEvent.event.raw;
  10811. if (raw.propertyName === slideConfig.dimension.property) {
  10812. disableTransitions(component, slideConfig);
  10813. if (slideState.isExpanded()) {
  10814. remove$2(component.element, slideConfig.dimension.property);
  10815. }
  10816. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  10817. notify(component);
  10818. }
  10819. })]);
  10820. };
  10821. var ActiveSliding = /*#__PURE__*/Object.freeze({
  10822. __proto__: null,
  10823. exhibit: exhibit,
  10824. events: events
  10825. });
  10826. var SlidingSchema = [
  10827. required$1('closedClass'),
  10828. required$1('openClass'),
  10829. required$1('shrinkingClass'),
  10830. required$1('growingClass'),
  10831. option('getAnimationRoot'),
  10832. onHandler('onShrunk'),
  10833. onHandler('onStartShrink'),
  10834. onHandler('onGrown'),
  10835. onHandler('onStartGrow'),
  10836. defaulted('expanded', false),
  10837. requiredOf('dimension', choose$1('property', {
  10838. width: [
  10839. output('property', 'width'),
  10840. output('getDimension', function (elem) {
  10841. return get$5(elem) + 'px';
  10842. })
  10843. ],
  10844. height: [
  10845. output('property', 'height'),
  10846. output('getDimension', function (elem) {
  10847. return get$7(elem) + 'px';
  10848. })
  10849. ]
  10850. }))
  10851. ];
  10852. var init$1 = function (spec) {
  10853. var state = Cell(spec.expanded);
  10854. var readState = function () {
  10855. return 'expanded: ' + state.get();
  10856. };
  10857. return nu$2({
  10858. isExpanded: function () {
  10859. return state.get() === true;
  10860. },
  10861. isCollapsed: function () {
  10862. return state.get() === false;
  10863. },
  10864. setCollapsed: curry(state.set, false),
  10865. setExpanded: curry(state.set, true),
  10866. readState: readState
  10867. });
  10868. };
  10869. var SlidingState = /*#__PURE__*/Object.freeze({
  10870. __proto__: null,
  10871. init: init$1
  10872. });
  10873. var Sliding = create$5({
  10874. fields: SlidingSchema,
  10875. name: 'sliding',
  10876. active: ActiveSliding,
  10877. apis: SlidingApis,
  10878. state: SlidingState
  10879. });
  10880. var build = function (refresh, scrollIntoView) {
  10881. var dropup = build$1(Container.sketch({
  10882. dom: {
  10883. tag: 'div',
  10884. classes: [resolve('dropup')]
  10885. },
  10886. components: [],
  10887. containerBehaviours: derive$2([
  10888. Replacing.config({}),
  10889. Sliding.config({
  10890. closedClass: resolve('dropup-closed'),
  10891. openClass: resolve('dropup-open'),
  10892. shrinkingClass: resolve('dropup-shrinking'),
  10893. growingClass: resolve('dropup-growing'),
  10894. dimension: { property: 'height' },
  10895. onShrunk: function (component) {
  10896. refresh();
  10897. scrollIntoView();
  10898. Replacing.set(component, []);
  10899. },
  10900. onGrown: function (_component) {
  10901. refresh();
  10902. scrollIntoView();
  10903. }
  10904. }),
  10905. orientation(function (_component, _data) {
  10906. disappear(noop);
  10907. })
  10908. ])
  10909. }));
  10910. var appear = function (menu, update, component) {
  10911. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  10912. window.requestAnimationFrame(function () {
  10913. update(component);
  10914. Replacing.set(dropup, [menu()]);
  10915. Sliding.grow(dropup);
  10916. });
  10917. }
  10918. };
  10919. var disappear = function (onReadyToShrink) {
  10920. window.requestAnimationFrame(function () {
  10921. onReadyToShrink();
  10922. Sliding.shrink(dropup);
  10923. });
  10924. };
  10925. return {
  10926. appear: appear,
  10927. disappear: disappear,
  10928. component: dropup,
  10929. element: dropup.element
  10930. };
  10931. };
  10932. var closest = function (scope, selector, isRoot) {
  10933. return closest$1(scope, selector, isRoot).isSome();
  10934. };
  10935. var isDangerous = function (event) {
  10936. var keyEv = event.raw;
  10937. return keyEv.which === BACKSPACE[0] && !contains$1([
  10938. 'input',
  10939. 'textarea'
  10940. ], name$1(event.target)) && !closest(event.target, '[contenteditable="true"]');
  10941. };
  10942. var isFirefox = function () {
  10943. return detect$1().browser.isFirefox();
  10944. };
  10945. var bindFocus = function (container, handler) {
  10946. if (isFirefox()) {
  10947. return capture(container, 'focus', handler);
  10948. } else {
  10949. return bind(container, 'focusin', handler);
  10950. }
  10951. };
  10952. var bindBlur = function (container, handler) {
  10953. if (isFirefox()) {
  10954. return capture(container, 'blur', handler);
  10955. } else {
  10956. return bind(container, 'focusout', handler);
  10957. }
  10958. };
  10959. var setup$1 = function (container, rawSettings) {
  10960. var settings = __assign({ stopBackspace: true }, rawSettings);
  10961. var pointerEvents = [
  10962. 'touchstart',
  10963. 'touchmove',
  10964. 'touchend',
  10965. 'touchcancel',
  10966. 'gesturestart',
  10967. 'mousedown',
  10968. 'mouseup',
  10969. 'mouseover',
  10970. 'mousemove',
  10971. 'mouseout',
  10972. 'click'
  10973. ];
  10974. var tapEvent = monitor$1(settings);
  10975. var simpleEvents = map$2(pointerEvents.concat([
  10976. 'selectstart',
  10977. 'input',
  10978. 'contextmenu',
  10979. 'change',
  10980. 'transitionend',
  10981. 'transitioncancel',
  10982. 'drag',
  10983. 'dragstart',
  10984. 'dragend',
  10985. 'dragenter',
  10986. 'dragleave',
  10987. 'dragover',
  10988. 'drop',
  10989. 'keyup'
  10990. ]), function (type) {
  10991. return bind(container, type, function (event) {
  10992. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  10993. if (tapStopped) {
  10994. event.kill();
  10995. }
  10996. });
  10997. var stopped = settings.triggerEvent(type, event);
  10998. if (stopped) {
  10999. event.kill();
  11000. }
  11001. });
  11002. });
  11003. var pasteTimeout = value();
  11004. var onPaste = bind(container, 'paste', function (event) {
  11005. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11006. if (tapStopped) {
  11007. event.kill();
  11008. }
  11009. });
  11010. var stopped = settings.triggerEvent('paste', event);
  11011. if (stopped) {
  11012. event.kill();
  11013. }
  11014. pasteTimeout.set(setTimeout(function () {
  11015. settings.triggerEvent(postPaste(), event);
  11016. }, 0));
  11017. });
  11018. var onKeydown = bind(container, 'keydown', function (event) {
  11019. var stopped = settings.triggerEvent('keydown', event);
  11020. if (stopped) {
  11021. event.kill();
  11022. } else if (settings.stopBackspace && isDangerous(event)) {
  11023. event.prevent();
  11024. }
  11025. });
  11026. var onFocusIn = bindFocus(container, function (event) {
  11027. var stopped = settings.triggerEvent('focusin', event);
  11028. if (stopped) {
  11029. event.kill();
  11030. }
  11031. });
  11032. var focusoutTimeout = value();
  11033. var onFocusOut = bindBlur(container, function (event) {
  11034. var stopped = settings.triggerEvent('focusout', event);
  11035. if (stopped) {
  11036. event.kill();
  11037. }
  11038. focusoutTimeout.set(setTimeout(function () {
  11039. settings.triggerEvent(postBlur(), event);
  11040. }, 0));
  11041. });
  11042. var unbind = function () {
  11043. each$1(simpleEvents, function (e) {
  11044. e.unbind();
  11045. });
  11046. onKeydown.unbind();
  11047. onFocusIn.unbind();
  11048. onFocusOut.unbind();
  11049. onPaste.unbind();
  11050. pasteTimeout.on(clearTimeout);
  11051. focusoutTimeout.on(clearTimeout);
  11052. };
  11053. return { unbind: unbind };
  11054. };
  11055. var derive$1 = function (rawEvent, rawTarget) {
  11056. var source = get$c(rawEvent, 'target').getOr(rawTarget);
  11057. return Cell(source);
  11058. };
  11059. var fromSource = function (event, source) {
  11060. var stopper = Cell(false);
  11061. var cutter = Cell(false);
  11062. var stop = function () {
  11063. stopper.set(true);
  11064. };
  11065. var cut = function () {
  11066. cutter.set(true);
  11067. };
  11068. return {
  11069. stop: stop,
  11070. cut: cut,
  11071. isStopped: stopper.get,
  11072. isCut: cutter.get,
  11073. event: event,
  11074. setSource: source.set,
  11075. getSource: source.get
  11076. };
  11077. };
  11078. var fromExternal = function (event) {
  11079. var stopper = Cell(false);
  11080. var stop = function () {
  11081. stopper.set(true);
  11082. };
  11083. return {
  11084. stop: stop,
  11085. cut: noop,
  11086. isStopped: stopper.get,
  11087. isCut: never,
  11088. event: event,
  11089. setSource: die('Cannot set source of a broadcasted event'),
  11090. getSource: die('Cannot get source of a broadcasted event')
  11091. };
  11092. };
  11093. var adt = Adt.generate([
  11094. { stopped: [] },
  11095. { resume: ['element'] },
  11096. { complete: [] }
  11097. ]);
  11098. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11099. var handler = lookup(eventType, target);
  11100. var simulatedEvent = fromSource(rawEvent, source);
  11101. return handler.fold(function () {
  11102. logger.logEventNoHandlers(eventType, target);
  11103. return adt.complete();
  11104. }, function (handlerInfo) {
  11105. var descHandler = handlerInfo.descHandler;
  11106. var eventHandler = getCurried(descHandler);
  11107. eventHandler(simulatedEvent);
  11108. if (simulatedEvent.isStopped()) {
  11109. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  11110. return adt.stopped();
  11111. } else if (simulatedEvent.isCut()) {
  11112. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  11113. return adt.complete();
  11114. } else {
  11115. return parent(handlerInfo.element).fold(function () {
  11116. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  11117. return adt.complete();
  11118. }, function (parent) {
  11119. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  11120. return adt.resume(parent);
  11121. });
  11122. }
  11123. });
  11124. };
  11125. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11126. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) {
  11127. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11128. }, never);
  11129. };
  11130. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11131. var source = derive$1(rawEvent, target);
  11132. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11133. };
  11134. var broadcast = function (listeners, rawEvent, _logger) {
  11135. var simulatedEvent = fromExternal(rawEvent);
  11136. each$1(listeners, function (listener) {
  11137. var descHandler = listener.descHandler;
  11138. var handler = getCurried(descHandler);
  11139. handler(simulatedEvent);
  11140. });
  11141. return simulatedEvent.isStopped();
  11142. };
  11143. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11144. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  11145. };
  11146. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11147. var source = derive$1(rawEvent, rawTarget);
  11148. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11149. };
  11150. var eventHandler = function (element, descHandler) {
  11151. return {
  11152. element: element,
  11153. descHandler: descHandler
  11154. };
  11155. };
  11156. var broadcastHandler = function (id, handler) {
  11157. return {
  11158. id: id,
  11159. descHandler: handler
  11160. };
  11161. };
  11162. var EventRegistry = function () {
  11163. var registry = {};
  11164. var registerId = function (extraArgs, id, events) {
  11165. each(events, function (v, k) {
  11166. var handlers = registry[k] !== undefined ? registry[k] : {};
  11167. handlers[id] = curryArgs(v, extraArgs);
  11168. registry[k] = handlers;
  11169. });
  11170. };
  11171. var findHandler = function (handlers, elem) {
  11172. return read(elem).bind(function (id) {
  11173. return get$c(handlers, id);
  11174. }).map(function (descHandler) {
  11175. return eventHandler(elem, descHandler);
  11176. });
  11177. };
  11178. var filterByType = function (type) {
  11179. return get$c(registry, type).map(function (handlers) {
  11180. return mapToArray(handlers, function (f, id) {
  11181. return broadcastHandler(id, f);
  11182. });
  11183. }).getOr([]);
  11184. };
  11185. var find = function (isAboveRoot, type, target) {
  11186. return get$c(registry, type).bind(function (handlers) {
  11187. return closest$3(target, function (elem) {
  11188. return findHandler(handlers, elem);
  11189. }, isAboveRoot);
  11190. });
  11191. };
  11192. var unregisterId = function (id) {
  11193. each(registry, function (handlersById, _eventName) {
  11194. if (has$2(handlersById, id)) {
  11195. delete handlersById[id];
  11196. }
  11197. });
  11198. };
  11199. return {
  11200. registerId: registerId,
  11201. unregisterId: unregisterId,
  11202. filterByType: filterByType,
  11203. find: find
  11204. };
  11205. };
  11206. var Registry = function () {
  11207. var events = EventRegistry();
  11208. var components = {};
  11209. var readOrTag = function (component) {
  11210. var elem = component.element;
  11211. return read(elem).getOrThunk(function () {
  11212. return write('uid-', component.element);
  11213. });
  11214. };
  11215. var failOnDuplicate = function (component, tagId) {
  11216. var conflict = components[tagId];
  11217. if (conflict === component) {
  11218. unregister(component);
  11219. } else {
  11220. 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');
  11221. }
  11222. };
  11223. var register = function (component) {
  11224. var tagId = readOrTag(component);
  11225. if (hasNonNullableKey(components, tagId)) {
  11226. failOnDuplicate(component, tagId);
  11227. }
  11228. var extraArgs = [component];
  11229. events.registerId(extraArgs, tagId, component.events);
  11230. components[tagId] = component;
  11231. };
  11232. var unregister = function (component) {
  11233. read(component.element).each(function (tagId) {
  11234. delete components[tagId];
  11235. events.unregisterId(tagId);
  11236. });
  11237. };
  11238. var filter = function (type) {
  11239. return events.filterByType(type);
  11240. };
  11241. var find = function (isAboveRoot, type, target) {
  11242. return events.find(isAboveRoot, type, target);
  11243. };
  11244. var getById = function (id) {
  11245. return get$c(components, id);
  11246. };
  11247. return {
  11248. find: find,
  11249. filter: filter,
  11250. register: register,
  11251. unregister: unregister,
  11252. getById: getById
  11253. };
  11254. };
  11255. var takeover$1 = function (root) {
  11256. var isAboveRoot = function (el) {
  11257. return parent(root.element).fold(always, function (parent) {
  11258. return eq(el, parent);
  11259. });
  11260. };
  11261. var registry = Registry();
  11262. var lookup = function (eventName, target) {
  11263. return registry.find(isAboveRoot, eventName, target);
  11264. };
  11265. var domEvents = setup$1(root.element, {
  11266. triggerEvent: function (eventName, event) {
  11267. return monitorEvent(eventName, event.target, function (logger) {
  11268. return triggerUntilStopped(lookup, eventName, event, logger);
  11269. });
  11270. }
  11271. });
  11272. var systemApi = {
  11273. debugInfo: constant$1('real'),
  11274. triggerEvent: function (eventName, target, data) {
  11275. monitorEvent(eventName, target, function (logger) {
  11276. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11277. });
  11278. },
  11279. triggerFocus: function (target, originator) {
  11280. read(target).fold(function () {
  11281. focus$3(target);
  11282. }, function (_alloyId) {
  11283. monitorEvent(focus$4(), target, function (logger) {
  11284. triggerHandler(lookup, focus$4(), {
  11285. originator: originator,
  11286. kill: noop,
  11287. prevent: noop,
  11288. target: target
  11289. }, target, logger);
  11290. return false;
  11291. });
  11292. });
  11293. },
  11294. triggerEscape: function (comp, simulatedEvent) {
  11295. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  11296. },
  11297. getByUid: function (uid) {
  11298. return getByUid(uid);
  11299. },
  11300. getByDom: function (elem) {
  11301. return getByDom(elem);
  11302. },
  11303. build: build$1,
  11304. addToGui: function (c) {
  11305. add(c);
  11306. },
  11307. removeFromGui: function (c) {
  11308. remove(c);
  11309. },
  11310. addToWorld: function (c) {
  11311. addToWorld(c);
  11312. },
  11313. removeFromWorld: function (c) {
  11314. removeFromWorld(c);
  11315. },
  11316. broadcast: function (message) {
  11317. broadcast$1(message);
  11318. },
  11319. broadcastOn: function (channels, message) {
  11320. broadcastOn(channels, message);
  11321. },
  11322. broadcastEvent: function (eventName, event) {
  11323. broadcastEvent(eventName, event);
  11324. },
  11325. isConnected: always
  11326. };
  11327. var addToWorld = function (component) {
  11328. component.connect(systemApi);
  11329. if (!isText(component.element)) {
  11330. registry.register(component);
  11331. each$1(component.components(), addToWorld);
  11332. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  11333. }
  11334. };
  11335. var removeFromWorld = function (component) {
  11336. if (!isText(component.element)) {
  11337. each$1(component.components(), removeFromWorld);
  11338. registry.unregister(component);
  11339. }
  11340. component.disconnect();
  11341. };
  11342. var add = function (component) {
  11343. attach(root, component);
  11344. };
  11345. var remove = function (component) {
  11346. detach(component);
  11347. };
  11348. var destroy = function () {
  11349. domEvents.unbind();
  11350. remove$7(root.element);
  11351. };
  11352. var broadcastData = function (data) {
  11353. var receivers = registry.filter(receive$1());
  11354. each$1(receivers, function (receiver) {
  11355. var descHandler = receiver.descHandler;
  11356. var handler = getCurried(descHandler);
  11357. handler(data);
  11358. });
  11359. };
  11360. var broadcast$1 = function (message) {
  11361. broadcastData({
  11362. universal: true,
  11363. data: message
  11364. });
  11365. };
  11366. var broadcastOn = function (channels, message) {
  11367. broadcastData({
  11368. universal: false,
  11369. channels: channels,
  11370. data: message
  11371. });
  11372. };
  11373. var broadcastEvent = function (eventName, event) {
  11374. var listeners = registry.filter(eventName);
  11375. return broadcast(listeners, event);
  11376. };
  11377. var getByUid = function (uid) {
  11378. return registry.getById(uid).fold(function () {
  11379. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11380. }, Result.value);
  11381. };
  11382. var getByDom = function (elem) {
  11383. var uid = read(elem).getOr('not found');
  11384. return getByUid(uid);
  11385. };
  11386. addToWorld(root);
  11387. return {
  11388. root: root,
  11389. element: root.element,
  11390. destroy: destroy,
  11391. add: add,
  11392. remove: remove,
  11393. getByUid: getByUid,
  11394. getByDom: getByDom,
  11395. addToWorld: addToWorld,
  11396. removeFromWorld: removeFromWorld,
  11397. broadcast: broadcast$1,
  11398. broadcastOn: broadcastOn,
  11399. broadcastEvent: broadcastEvent
  11400. };
  11401. };
  11402. var READ_ONLY_MODE_CLASS = resolve('readonly-mode');
  11403. var EDIT_MODE_CLASS = resolve('edit-mode');
  11404. function OuterContainer (spec) {
  11405. var root = build$1(Container.sketch({
  11406. dom: { classes: [resolve('outer-container')].concat(spec.classes) },
  11407. containerBehaviours: derive$2([Swapping.config({
  11408. alpha: READ_ONLY_MODE_CLASS,
  11409. omega: EDIT_MODE_CLASS
  11410. })])
  11411. }));
  11412. return takeover$1(root);
  11413. }
  11414. function AndroidRealm (scrollIntoView) {
  11415. var alloy = OuterContainer({ classes: [resolve('android-container')] });
  11416. var toolbar = ScrollingToolbar();
  11417. var webapp = api$2();
  11418. var switchToEdit = makeEditSwitch(webapp);
  11419. var socket = makeSocket();
  11420. var dropup = build(noop, scrollIntoView);
  11421. alloy.add(toolbar.wrapper);
  11422. alloy.add(socket);
  11423. alloy.add(dropup.component);
  11424. var setToolbarGroups = function (rawGroups) {
  11425. var groups = toolbar.createGroups(rawGroups);
  11426. toolbar.setGroups(groups);
  11427. };
  11428. var setContextToolbar = function (rawGroups) {
  11429. var groups = toolbar.createGroups(rawGroups);
  11430. toolbar.setContextToolbar(groups);
  11431. };
  11432. var focusToolbar = function () {
  11433. toolbar.focus();
  11434. };
  11435. var restoreToolbar = function () {
  11436. toolbar.restoreToolbar();
  11437. };
  11438. var init = function (spec) {
  11439. webapp.set(produce$1(spec));
  11440. };
  11441. var exit = function () {
  11442. webapp.run(function (w) {
  11443. w.exit();
  11444. Replacing.remove(socket, switchToEdit);
  11445. });
  11446. };
  11447. var updateMode$1 = function (readOnly) {
  11448. updateMode(socket, switchToEdit, readOnly, alloy.root);
  11449. };
  11450. return {
  11451. system: alloy,
  11452. element: alloy.element,
  11453. init: init,
  11454. exit: exit,
  11455. setToolbarGroups: setToolbarGroups,
  11456. setContextToolbar: setContextToolbar,
  11457. focusToolbar: focusToolbar,
  11458. restoreToolbar: restoreToolbar,
  11459. updateMode: updateMode$1,
  11460. socket: socket,
  11461. dropup: dropup
  11462. };
  11463. }
  11464. var input = function (parent, operation) {
  11465. var input = SugarElement.fromTag('input');
  11466. setAll(input, {
  11467. opacity: '0',
  11468. position: 'absolute',
  11469. top: '-1000px',
  11470. left: '-1000px'
  11471. });
  11472. append$2(parent, input);
  11473. focus$3(input);
  11474. operation(input);
  11475. remove$7(input);
  11476. };
  11477. var refresh = function (winScope) {
  11478. var sel = winScope.getSelection();
  11479. if (sel.rangeCount > 0) {
  11480. var br = sel.getRangeAt(0);
  11481. var r = winScope.document.createRange();
  11482. r.setStart(br.startContainer, br.startOffset);
  11483. r.setEnd(br.endContainer, br.endOffset);
  11484. sel.removeAllRanges();
  11485. sel.addRange(r);
  11486. }
  11487. };
  11488. var resume = function (cWin, frame) {
  11489. active().each(function (active) {
  11490. if (!eq(active, frame)) {
  11491. blur$1(active);
  11492. }
  11493. });
  11494. cWin.focus();
  11495. focus$3(SugarElement.fromDom(cWin.document.body));
  11496. refresh(cWin);
  11497. };
  11498. var stubborn = function (outerBody, cWin, page, frame) {
  11499. var toEditing = function () {
  11500. resume(cWin, frame);
  11501. };
  11502. var toReading = function () {
  11503. input(outerBody, blur$1);
  11504. };
  11505. var captureInput = bind(page, 'keydown', function (evt) {
  11506. if (!contains$1([
  11507. 'input',
  11508. 'textarea'
  11509. ], name$1(evt.target))) {
  11510. toEditing();
  11511. }
  11512. });
  11513. var onToolbarTouch = noop;
  11514. var destroy = function () {
  11515. captureInput.unbind();
  11516. };
  11517. return {
  11518. toReading: toReading,
  11519. toEditing: toEditing,
  11520. onToolbarTouch: onToolbarTouch,
  11521. destroy: destroy
  11522. };
  11523. };
  11524. var initEvents = function (editorApi, iosApi, toolstrip, socket, _dropup) {
  11525. var saveSelectionFirst = function () {
  11526. iosApi.run(function (api) {
  11527. api.highlightSelection();
  11528. });
  11529. };
  11530. var refreshIosSelection = function () {
  11531. iosApi.run(function (api) {
  11532. api.refreshSelection();
  11533. });
  11534. };
  11535. var scrollToY = function (yTop, height) {
  11536. var y = yTop - socket.dom.scrollTop;
  11537. iosApi.run(function (api) {
  11538. api.scrollIntoView(y, y + height);
  11539. });
  11540. };
  11541. var scrollToElement = function (_target) {
  11542. scrollToY(iosApi, socket);
  11543. };
  11544. var scrollToCursor = function () {
  11545. editorApi.getCursorBox().each(function (box) {
  11546. scrollToY(box.top, box.height);
  11547. });
  11548. };
  11549. var clearSelection = function () {
  11550. iosApi.run(function (api) {
  11551. api.clearSelection();
  11552. });
  11553. };
  11554. var clearAndRefresh = function () {
  11555. clearSelection();
  11556. refreshThrottle.throttle();
  11557. };
  11558. var refreshView = function () {
  11559. scrollToCursor();
  11560. iosApi.run(function (api) {
  11561. api.syncHeight();
  11562. });
  11563. };
  11564. var reposition = function () {
  11565. var toolbarHeight = get$7(toolstrip);
  11566. iosApi.run(function (api) {
  11567. api.setViewportOffset(toolbarHeight);
  11568. });
  11569. refreshIosSelection();
  11570. refreshView();
  11571. };
  11572. var toEditing = function () {
  11573. iosApi.run(function (api) {
  11574. api.toEditing();
  11575. });
  11576. };
  11577. var toReading = function () {
  11578. iosApi.run(function (api) {
  11579. api.toReading();
  11580. });
  11581. };
  11582. var onToolbarTouch = function (event) {
  11583. iosApi.run(function (api) {
  11584. api.onToolbarTouch(event);
  11585. });
  11586. };
  11587. var tapping = monitor(editorApi);
  11588. var refreshThrottle = last(refreshView, 300);
  11589. var listeners = [
  11590. editorApi.onKeyup(clearAndRefresh),
  11591. editorApi.onNodeChanged(refreshIosSelection),
  11592. editorApi.onDomChanged(refreshThrottle.throttle),
  11593. editorApi.onDomChanged(refreshIosSelection),
  11594. editorApi.onScrollToCursor(function (tinyEvent) {
  11595. tinyEvent.preventDefault();
  11596. refreshThrottle.throttle();
  11597. }),
  11598. editorApi.onScrollToElement(function (event) {
  11599. scrollToElement(event.element);
  11600. }),
  11601. editorApi.onToEditing(toEditing),
  11602. editorApi.onToReading(toReading),
  11603. bind(editorApi.doc, 'touchend', function (touchEvent) {
  11604. if (eq(editorApi.html, touchEvent.target) || eq(editorApi.body, touchEvent.target)) ;
  11605. }),
  11606. bind(toolstrip, 'transitionend', function (transitionEvent) {
  11607. if (transitionEvent.raw.propertyName === 'height') {
  11608. reposition();
  11609. }
  11610. }),
  11611. capture(toolstrip, 'touchstart', function (touchEvent) {
  11612. saveSelectionFirst();
  11613. onToolbarTouch(touchEvent);
  11614. editorApi.onTouchToolstrip();
  11615. }),
  11616. bind(editorApi.body, 'touchstart', function (evt) {
  11617. clearSelection();
  11618. editorApi.onTouchContent();
  11619. tapping.fireTouchstart(evt);
  11620. }),
  11621. tapping.onTouchmove(),
  11622. tapping.onTouchend(),
  11623. bind(editorApi.body, 'click', function (event) {
  11624. event.kill();
  11625. }),
  11626. bind(toolstrip, 'touchmove', function () {
  11627. editorApi.onToolbarScrollStart();
  11628. })
  11629. ];
  11630. var destroy = function () {
  11631. each$1(listeners, function (l) {
  11632. l.unbind();
  11633. });
  11634. };
  11635. return { destroy: destroy };
  11636. };
  11637. function FakeSelection (win, frame) {
  11638. var doc = win.document;
  11639. var container = SugarElement.fromTag('div');
  11640. add$1(container, resolve('unfocused-selections'));
  11641. append$2(SugarElement.fromDom(doc.documentElement), container);
  11642. var onTouch = bind(container, 'touchstart', function (event) {
  11643. event.prevent();
  11644. resume(win, frame);
  11645. clear();
  11646. });
  11647. var make = function (rectangle) {
  11648. var span = SugarElement.fromTag('span');
  11649. add(span, [
  11650. resolve('layer-editor'),
  11651. resolve('unfocused-selection')
  11652. ]);
  11653. setAll(span, {
  11654. left: rectangle.left + 'px',
  11655. top: rectangle.top + 'px',
  11656. width: rectangle.width + 'px',
  11657. height: rectangle.height + 'px'
  11658. });
  11659. return span;
  11660. };
  11661. var update = function () {
  11662. clear();
  11663. var rectangles = getRectangles(win);
  11664. var spans = map$2(rectangles, make);
  11665. append$1(container, spans);
  11666. };
  11667. var clear = function () {
  11668. empty(container);
  11669. };
  11670. var destroy = function () {
  11671. onTouch.unbind();
  11672. remove$7(container);
  11673. };
  11674. var isActive = function () {
  11675. return children(container).length > 0;
  11676. };
  11677. return {
  11678. update: update,
  11679. isActive: isActive,
  11680. destroy: destroy,
  11681. clear: clear
  11682. };
  11683. }
  11684. var nu$1 = function (baseFn) {
  11685. var data = Optional.none();
  11686. var callbacks = [];
  11687. var map = function (f) {
  11688. return nu$1(function (nCallback) {
  11689. get(function (data) {
  11690. nCallback(f(data));
  11691. });
  11692. });
  11693. };
  11694. var get = function (nCallback) {
  11695. if (isReady()) {
  11696. call(nCallback);
  11697. } else {
  11698. callbacks.push(nCallback);
  11699. }
  11700. };
  11701. var set = function (x) {
  11702. if (!isReady()) {
  11703. data = Optional.some(x);
  11704. run(callbacks);
  11705. callbacks = [];
  11706. }
  11707. };
  11708. var isReady = function () {
  11709. return data.isSome();
  11710. };
  11711. var run = function (cbs) {
  11712. each$1(cbs, call);
  11713. };
  11714. var call = function (cb) {
  11715. data.each(function (x) {
  11716. setTimeout(function () {
  11717. cb(x);
  11718. }, 0);
  11719. });
  11720. };
  11721. baseFn(set);
  11722. return {
  11723. get: get,
  11724. map: map,
  11725. isReady: isReady
  11726. };
  11727. };
  11728. var pure$1 = function (a) {
  11729. return nu$1(function (callback) {
  11730. callback(a);
  11731. });
  11732. };
  11733. var LazyValue = {
  11734. nu: nu$1,
  11735. pure: pure$1
  11736. };
  11737. var errorReporter = function (err) {
  11738. setTimeout(function () {
  11739. throw err;
  11740. }, 0);
  11741. };
  11742. var make = function (run) {
  11743. var get = function (callback) {
  11744. run().then(callback, errorReporter);
  11745. };
  11746. var map = function (fab) {
  11747. return make(function () {
  11748. return run().then(fab);
  11749. });
  11750. };
  11751. var bind = function (aFutureB) {
  11752. return make(function () {
  11753. return run().then(function (v) {
  11754. return aFutureB(v).toPromise();
  11755. });
  11756. });
  11757. };
  11758. var anonBind = function (futureB) {
  11759. return make(function () {
  11760. return run().then(function () {
  11761. return futureB.toPromise();
  11762. });
  11763. });
  11764. };
  11765. var toLazy = function () {
  11766. return LazyValue.nu(get);
  11767. };
  11768. var toCached = function () {
  11769. var cache = null;
  11770. return make(function () {
  11771. if (cache === null) {
  11772. cache = run();
  11773. }
  11774. return cache;
  11775. });
  11776. };
  11777. var toPromise = run;
  11778. return {
  11779. map: map,
  11780. bind: bind,
  11781. anonBind: anonBind,
  11782. toLazy: toLazy,
  11783. toCached: toCached,
  11784. toPromise: toPromise,
  11785. get: get
  11786. };
  11787. };
  11788. var nu = function (baseFn) {
  11789. return make(function () {
  11790. return new Promise$1(baseFn);
  11791. });
  11792. };
  11793. var pure = function (a) {
  11794. return make(function () {
  11795. return Promise$1.resolve(a);
  11796. });
  11797. };
  11798. var Future = {
  11799. nu: nu,
  11800. pure: pure
  11801. };
  11802. var adjust = function (value, destination, amount) {
  11803. if (Math.abs(value - destination) <= amount) {
  11804. return Optional.none();
  11805. } else if (value < destination) {
  11806. return Optional.some(value + amount);
  11807. } else {
  11808. return Optional.some(value - amount);
  11809. }
  11810. };
  11811. var create$1 = function () {
  11812. var interval = null;
  11813. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  11814. var finished = false;
  11815. var finish = function (v) {
  11816. finished = true;
  11817. doFinish(v);
  11818. };
  11819. global$2.clearInterval(interval);
  11820. var abort = function (v) {
  11821. global$2.clearInterval(interval);
  11822. finish(v);
  11823. };
  11824. interval = global$2.setInterval(function () {
  11825. var value = getCurrent();
  11826. adjust(value, destination, amount).fold(function () {
  11827. global$2.clearInterval(interval);
  11828. finish(destination);
  11829. }, function (s) {
  11830. increment(s, abort);
  11831. if (!finished) {
  11832. var newValue = getCurrent();
  11833. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  11834. global$2.clearInterval(interval);
  11835. finish(destination);
  11836. }
  11837. }
  11838. });
  11839. }, rate);
  11840. };
  11841. return { animate: animate };
  11842. };
  11843. var findDevice = function (deviceWidth, deviceHeight) {
  11844. var devices = [
  11845. {
  11846. width: 320,
  11847. height: 480,
  11848. keyboard: {
  11849. portrait: 300,
  11850. landscape: 240
  11851. }
  11852. },
  11853. {
  11854. width: 320,
  11855. height: 568,
  11856. keyboard: {
  11857. portrait: 300,
  11858. landscape: 240
  11859. }
  11860. },
  11861. {
  11862. width: 375,
  11863. height: 667,
  11864. keyboard: {
  11865. portrait: 305,
  11866. landscape: 240
  11867. }
  11868. },
  11869. {
  11870. width: 414,
  11871. height: 736,
  11872. keyboard: {
  11873. portrait: 320,
  11874. landscape: 240
  11875. }
  11876. },
  11877. {
  11878. width: 768,
  11879. height: 1024,
  11880. keyboard: {
  11881. portrait: 320,
  11882. landscape: 400
  11883. }
  11884. },
  11885. {
  11886. width: 1024,
  11887. height: 1366,
  11888. keyboard: {
  11889. portrait: 380,
  11890. landscape: 460
  11891. }
  11892. }
  11893. ];
  11894. return findMap(devices, function (device) {
  11895. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  11896. }).getOr({
  11897. portrait: deviceHeight / 5,
  11898. landscape: deviceWidth / 4
  11899. });
  11900. };
  11901. var softKeyboardLimits = function (outerWindow) {
  11902. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  11903. };
  11904. var accountableKeyboardHeight = function (outerWindow) {
  11905. var portrait = get$1(outerWindow).isPortrait();
  11906. var limits = softKeyboardLimits(outerWindow);
  11907. var keyboard = portrait ? limits.portrait : limits.landscape;
  11908. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  11909. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  11910. };
  11911. var getGreenzone = function (socket, dropup) {
  11912. var outerWindow = owner$2(socket).dom.defaultView;
  11913. var viewportHeight = get$7(socket) + get$7(dropup);
  11914. var acc = accountableKeyboardHeight(outerWindow);
  11915. return viewportHeight - acc;
  11916. };
  11917. var updatePadding = function (contentBody, socket, dropup) {
  11918. var greenzoneHeight = getGreenzone(socket, dropup);
  11919. var deltaHeight = get$7(socket) + get$7(dropup) - greenzoneHeight;
  11920. set$5(contentBody, 'padding-bottom', deltaHeight + 'px');
  11921. };
  11922. var fixture = Adt.generate([
  11923. {
  11924. fixed: [
  11925. 'element',
  11926. 'property',
  11927. 'offsetY'
  11928. ]
  11929. },
  11930. {
  11931. scroller: [
  11932. 'element',
  11933. 'offsetY'
  11934. ]
  11935. }
  11936. ]);
  11937. var yFixedData = 'data-' + resolve('position-y-fixed');
  11938. var yFixedProperty = 'data-' + resolve('y-property');
  11939. var yScrollingData = 'data-' + resolve('scrolling');
  11940. var windowSizeData = 'data-' + resolve('last-window-height');
  11941. var getYFixedData = function (element) {
  11942. return safeParse(element, yFixedData);
  11943. };
  11944. var getYFixedProperty = function (element) {
  11945. return get$b(element, yFixedProperty);
  11946. };
  11947. var getLastWindowSize = function (element) {
  11948. return safeParse(element, windowSizeData);
  11949. };
  11950. var classifyFixed = function (element, offsetY) {
  11951. var prop = getYFixedProperty(element);
  11952. return fixture.fixed(element, prop, offsetY);
  11953. };
  11954. var classifyScrolling = function (element, offsetY) {
  11955. return fixture.scroller(element, offsetY);
  11956. };
  11957. var classify = function (element) {
  11958. var offsetY = getYFixedData(element);
  11959. var classifier = get$b(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  11960. return classifier(element, offsetY);
  11961. };
  11962. var findFixtures = function (container) {
  11963. var candidates = descendants(container, '[' + yFixedData + ']');
  11964. return map$2(candidates, classify);
  11965. };
  11966. var takeoverToolbar = function (toolbar) {
  11967. var oldToolbarStyle = get$b(toolbar, 'style');
  11968. setAll(toolbar, {
  11969. position: 'absolute',
  11970. top: '0px'
  11971. });
  11972. set$8(toolbar, yFixedData, '0px');
  11973. set$8(toolbar, yFixedProperty, 'top');
  11974. var restore = function () {
  11975. set$8(toolbar, 'style', oldToolbarStyle || '');
  11976. remove$6(toolbar, yFixedData);
  11977. remove$6(toolbar, yFixedProperty);
  11978. };
  11979. return { restore: restore };
  11980. };
  11981. var takeoverViewport = function (toolbarHeight, height, viewport) {
  11982. var oldViewportStyle = get$b(viewport, 'style');
  11983. register$2(viewport);
  11984. setAll(viewport, {
  11985. position: 'absolute',
  11986. height: height + 'px',
  11987. width: '100%',
  11988. top: toolbarHeight + 'px'
  11989. });
  11990. set$8(viewport, yFixedData, toolbarHeight + 'px');
  11991. set$8(viewport, yScrollingData, 'true');
  11992. set$8(viewport, yFixedProperty, 'top');
  11993. var restore = function () {
  11994. deregister(viewport);
  11995. set$8(viewport, 'style', oldViewportStyle || '');
  11996. remove$6(viewport, yFixedData);
  11997. remove$6(viewport, yScrollingData);
  11998. remove$6(viewport, yFixedProperty);
  11999. };
  12000. return { restore: restore };
  12001. };
  12002. var takeoverDropup = function (dropup) {
  12003. var oldDropupStyle = get$b(dropup, 'style');
  12004. setAll(dropup, {
  12005. position: 'absolute',
  12006. bottom: '0px'
  12007. });
  12008. set$8(dropup, yFixedData, '0px');
  12009. set$8(dropup, yFixedProperty, 'bottom');
  12010. var restore = function () {
  12011. set$8(dropup, 'style', oldDropupStyle || '');
  12012. remove$6(dropup, yFixedData);
  12013. remove$6(dropup, yFixedProperty);
  12014. };
  12015. return { restore: restore };
  12016. };
  12017. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12018. var outerWindow = owner$2(viewport).dom.defaultView;
  12019. var winH = outerWindow.innerHeight;
  12020. set$8(viewport, windowSizeData, winH + 'px');
  12021. return winH - toolbarHeight - dropupHeight;
  12022. };
  12023. var takeover = function (viewport, contentBody, toolbar, dropup) {
  12024. var outerWindow = owner$2(viewport).dom.defaultView;
  12025. var toolbarSetup = takeoverToolbar(toolbar);
  12026. var toolbarHeight = get$7(toolbar);
  12027. var dropupHeight = get$7(dropup);
  12028. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12029. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12030. var dropupSetup = takeoverDropup(dropup);
  12031. var isActive = true;
  12032. var restore = function () {
  12033. isActive = false;
  12034. toolbarSetup.restore();
  12035. viewportSetup.restore();
  12036. dropupSetup.restore();
  12037. };
  12038. var isExpanding = function () {
  12039. var currentWinHeight = outerWindow.innerHeight;
  12040. var lastWinHeight = getLastWindowSize(viewport);
  12041. return currentWinHeight > lastWinHeight;
  12042. };
  12043. var refresh = function () {
  12044. if (isActive) {
  12045. var newToolbarHeight = get$7(toolbar);
  12046. var dropupHeight_1 = get$7(dropup);
  12047. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12048. set$8(viewport, yFixedData, newToolbarHeight + 'px');
  12049. set$5(viewport, 'height', newHeight + 'px');
  12050. updatePadding(contentBody, viewport, dropup);
  12051. }
  12052. };
  12053. var setViewportOffset = function (newYOffset) {
  12054. var offsetPx = newYOffset + 'px';
  12055. set$8(viewport, yFixedData, offsetPx);
  12056. refresh();
  12057. };
  12058. updatePadding(contentBody, viewport, dropup);
  12059. return {
  12060. setViewportOffset: setViewportOffset,
  12061. isExpanding: isExpanding,
  12062. isShrinking: not(isExpanding),
  12063. refresh: refresh,
  12064. restore: restore
  12065. };
  12066. };
  12067. var animator = create$1();
  12068. var ANIMATION_STEP = 15;
  12069. var NUM_TOP_ANIMATION_FRAMES = 10;
  12070. var ANIMATION_RATE = 10;
  12071. var lastScroll = 'data-' + resolve('last-scroll-top');
  12072. var getTop = function (element) {
  12073. var raw = getRaw(element, 'top').getOr('0');
  12074. return parseInt(raw, 10);
  12075. };
  12076. var getScrollTop = function (element) {
  12077. return parseInt(element.dom.scrollTop, 10);
  12078. };
  12079. var moveScrollAndTop = function (element, destination, finalTop) {
  12080. return Future.nu(function (callback) {
  12081. var getCurrent = curry(getScrollTop, element);
  12082. var update = function (newScroll) {
  12083. element.dom.scrollTop = newScroll;
  12084. set$5(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12085. };
  12086. var finish = function () {
  12087. element.dom.scrollTop = destination;
  12088. set$5(element, 'top', finalTop + 'px');
  12089. callback(destination);
  12090. };
  12091. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12092. });
  12093. };
  12094. var moveOnlyScroll = function (element, destination) {
  12095. return Future.nu(function (callback) {
  12096. var getCurrent = curry(getScrollTop, element);
  12097. set$8(element, lastScroll, getCurrent());
  12098. var update = function (newScroll, abort) {
  12099. var previous = safeParse(element, lastScroll);
  12100. if (previous !== element.dom.scrollTop) {
  12101. abort(element.dom.scrollTop);
  12102. } else {
  12103. element.dom.scrollTop = newScroll;
  12104. set$8(element, lastScroll, newScroll);
  12105. }
  12106. };
  12107. var finish = function () {
  12108. element.dom.scrollTop = destination;
  12109. set$8(element, lastScroll, destination);
  12110. callback(destination);
  12111. };
  12112. var distance = Math.abs(destination - getCurrent());
  12113. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12114. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12115. });
  12116. };
  12117. var moveOnlyTop = function (element, destination) {
  12118. return Future.nu(function (callback) {
  12119. var getCurrent = curry(getTop, element);
  12120. var update = function (newTop) {
  12121. set$5(element, 'top', newTop + 'px');
  12122. };
  12123. var finish = function () {
  12124. update(destination);
  12125. callback(destination);
  12126. };
  12127. var distance = Math.abs(destination - getCurrent());
  12128. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12129. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12130. });
  12131. };
  12132. var updateTop = function (element, amount) {
  12133. var newTop = amount + getYFixedData(element) + 'px';
  12134. set$5(element, 'top', newTop);
  12135. };
  12136. var moveWindowScroll = function (toolbar, viewport, destY) {
  12137. var outerWindow = owner$2(toolbar).dom.defaultView;
  12138. return Future.nu(function (callback) {
  12139. updateTop(toolbar, destY);
  12140. updateTop(viewport, destY);
  12141. outerWindow.scrollTo(0, destY);
  12142. callback(destY);
  12143. });
  12144. };
  12145. function BackgroundActivity (doAction) {
  12146. var action = Cell(LazyValue.pure({}));
  12147. var start = function (value) {
  12148. var future = LazyValue.nu(function (callback) {
  12149. return doAction(value).get(callback);
  12150. });
  12151. action.set(future);
  12152. };
  12153. var idle = function (g) {
  12154. action.get().get(function () {
  12155. g();
  12156. });
  12157. };
  12158. return {
  12159. start: start,
  12160. idle: idle
  12161. };
  12162. }
  12163. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12164. var greenzone = getGreenzone(socket, dropup);
  12165. var refreshCursor = curry(refresh, cWin);
  12166. if (top > greenzone || bottom > greenzone) {
  12167. moveOnlyScroll(socket, socket.dom.scrollTop - greenzone + bottom).get(refreshCursor);
  12168. } else if (top < 0) {
  12169. moveOnlyScroll(socket, socket.dom.scrollTop + top).get(refreshCursor);
  12170. } else ;
  12171. };
  12172. var par$1 = function (asyncValues, nu) {
  12173. return nu(function (callback) {
  12174. var r = [];
  12175. var count = 0;
  12176. var cb = function (i) {
  12177. return function (value) {
  12178. r[i] = value;
  12179. count++;
  12180. if (count >= asyncValues.length) {
  12181. callback(r);
  12182. }
  12183. };
  12184. };
  12185. if (asyncValues.length === 0) {
  12186. callback([]);
  12187. } else {
  12188. each$1(asyncValues, function (asyncValue, i) {
  12189. asyncValue.get(cb(i));
  12190. });
  12191. }
  12192. });
  12193. };
  12194. var par = function (futures) {
  12195. return par$1(futures, Future.nu);
  12196. };
  12197. var updateFixed = function (element, property, winY, offsetY) {
  12198. var destination = winY + offsetY;
  12199. set$5(element, property, destination + 'px');
  12200. return Future.pure(offsetY);
  12201. };
  12202. var updateScrollingFixed = function (element, winY, offsetY) {
  12203. var destTop = winY + offsetY;
  12204. var oldProp = getRaw(element, 'top').getOr(offsetY);
  12205. var delta = destTop - parseInt(oldProp, 10);
  12206. var destScroll = element.dom.scrollTop + delta;
  12207. return moveScrollAndTop(element, destScroll, destTop);
  12208. };
  12209. var updateFixture = function (fixture, winY) {
  12210. return fixture.fold(function (element, property, offsetY) {
  12211. return updateFixed(element, property, winY, offsetY);
  12212. }, function (element, offsetY) {
  12213. return updateScrollingFixed(element, winY, offsetY);
  12214. });
  12215. };
  12216. var updatePositions = function (container, winY) {
  12217. var fixtures = findFixtures(container);
  12218. var updates = map$2(fixtures, function (fixture) {
  12219. return updateFixture(fixture, winY);
  12220. });
  12221. return par(updates);
  12222. };
  12223. var VIEW_MARGIN = 5;
  12224. var register = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  12225. var scroller = BackgroundActivity(function (y) {
  12226. return moveWindowScroll(toolstrip, socket, y);
  12227. });
  12228. var scrollBounds = function () {
  12229. var rects = getRectangles(cWin);
  12230. return Optional.from(rects[0]).bind(function (rect) {
  12231. var viewTop = rect.top - socket.dom.scrollTop;
  12232. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  12233. return outside ? Optional.some({
  12234. top: viewTop,
  12235. bottom: viewTop + rect.height
  12236. }) : Optional.none();
  12237. });
  12238. };
  12239. var scrollThrottle = last(function () {
  12240. scroller.idle(function () {
  12241. updatePositions(container, outerWindow.pageYOffset).get(function () {
  12242. var extraScroll = scrollBounds();
  12243. extraScroll.each(function (extra) {
  12244. socket.dom.scrollTop = socket.dom.scrollTop + extra.top;
  12245. });
  12246. scroller.start(0);
  12247. structure.refresh();
  12248. });
  12249. });
  12250. }, 1000);
  12251. var onScroll = bind(SugarElement.fromDom(outerWindow), 'scroll', function () {
  12252. if (outerWindow.pageYOffset < 0) {
  12253. return;
  12254. }
  12255. scrollThrottle.throttle();
  12256. });
  12257. updatePositions(container, outerWindow.pageYOffset).get(identity);
  12258. return { unbind: onScroll.unbind };
  12259. };
  12260. var setup = function (bag) {
  12261. var cWin = bag.cWin;
  12262. var ceBody = bag.ceBody;
  12263. var socket = bag.socket;
  12264. var toolstrip = bag.toolstrip;
  12265. var contentElement = bag.contentElement;
  12266. var keyboardType = bag.keyboardType;
  12267. var outerWindow = bag.outerWindow;
  12268. var dropup = bag.dropup;
  12269. var outerBody = bag.outerBody;
  12270. var structure = takeover(socket, ceBody, toolstrip, dropup);
  12271. var keyboardModel = keyboardType(outerBody, cWin, body(), contentElement);
  12272. var toEditing = function () {
  12273. keyboardModel.toEditing();
  12274. clearSelection();
  12275. };
  12276. var toReading = function () {
  12277. keyboardModel.toReading();
  12278. };
  12279. var onToolbarTouch = function (_event) {
  12280. keyboardModel.onToolbarTouch();
  12281. };
  12282. var onOrientation = onChange(outerWindow, {
  12283. onChange: noop,
  12284. onReady: structure.refresh
  12285. });
  12286. onOrientation.onAdjustment(function () {
  12287. structure.refresh();
  12288. });
  12289. var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () {
  12290. if (structure.isExpanding()) {
  12291. structure.refresh();
  12292. }
  12293. });
  12294. var onScroll = register(toolstrip, socket, outerBody, outerWindow, structure, cWin);
  12295. var unfocusedSelection = FakeSelection(cWin, contentElement);
  12296. var refreshSelection = function () {
  12297. if (unfocusedSelection.isActive()) {
  12298. unfocusedSelection.update();
  12299. }
  12300. };
  12301. var highlightSelection = function () {
  12302. unfocusedSelection.update();
  12303. };
  12304. var clearSelection = function () {
  12305. unfocusedSelection.clear();
  12306. };
  12307. var scrollIntoView$1 = function (top, bottom) {
  12308. scrollIntoView(cWin, socket, dropup, top, bottom);
  12309. };
  12310. var syncHeight = function () {
  12311. set$5(contentElement, 'height', contentElement.dom.contentWindow.document.body.scrollHeight + 'px');
  12312. };
  12313. var setViewportOffset = function (newYOffset) {
  12314. structure.setViewportOffset(newYOffset);
  12315. moveOnlyTop(socket, newYOffset).get(identity);
  12316. };
  12317. var destroy = function () {
  12318. structure.restore();
  12319. onOrientation.destroy();
  12320. onScroll.unbind();
  12321. onResize.unbind();
  12322. keyboardModel.destroy();
  12323. unfocusedSelection.destroy();
  12324. input(body(), blur$1);
  12325. };
  12326. return {
  12327. toEditing: toEditing,
  12328. toReading: toReading,
  12329. onToolbarTouch: onToolbarTouch,
  12330. refreshSelection: refreshSelection,
  12331. clearSelection: clearSelection,
  12332. highlightSelection: highlightSelection,
  12333. scrollIntoView: scrollIntoView$1,
  12334. updateToolbarPadding: noop,
  12335. setViewportOffset: setViewportOffset,
  12336. syncHeight: syncHeight,
  12337. refreshStructure: structure.refresh,
  12338. destroy: destroy
  12339. };
  12340. };
  12341. var create = function (platform, mask) {
  12342. var meta = tag();
  12343. var priorState = value();
  12344. var scrollEvents = value();
  12345. var iosApi = api$2();
  12346. var iosEvents = api$2();
  12347. var enter = function () {
  12348. mask.hide();
  12349. var doc = SugarElement.fromDom(document);
  12350. getActiveApi(platform.editor).each(function (editorApi) {
  12351. priorState.set({
  12352. socketHeight: getRaw(platform.socket, 'height'),
  12353. iframeHeight: getRaw(editorApi.frame, 'height'),
  12354. outerScroll: document.body.scrollTop
  12355. });
  12356. scrollEvents.set({ exclusives: exclusive(doc, '.' + scrollable) });
  12357. add$1(platform.container, resolve('fullscreen-maximized'));
  12358. clobberStyles(platform.container, editorApi.body);
  12359. meta.maximize();
  12360. set$5(platform.socket, 'overflow', 'scroll');
  12361. set$5(platform.socket, '-webkit-overflow-scrolling', 'touch');
  12362. focus$3(editorApi.body);
  12363. iosApi.set(setup({
  12364. cWin: editorApi.win,
  12365. ceBody: editorApi.body,
  12366. socket: platform.socket,
  12367. toolstrip: platform.toolstrip,
  12368. dropup: platform.dropup.element,
  12369. contentElement: editorApi.frame,
  12370. outerBody: platform.body,
  12371. outerWindow: platform.win,
  12372. keyboardType: stubborn
  12373. }));
  12374. iosApi.run(function (api) {
  12375. api.syncHeight();
  12376. });
  12377. iosEvents.set(initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  12378. });
  12379. };
  12380. var exit = function () {
  12381. meta.restore();
  12382. iosEvents.clear();
  12383. iosApi.clear();
  12384. mask.show();
  12385. priorState.on(function (s) {
  12386. s.socketHeight.each(function (h) {
  12387. set$5(platform.socket, 'height', h);
  12388. });
  12389. s.iframeHeight.each(function (h) {
  12390. set$5(platform.editor.getFrame(), 'height', h);
  12391. });
  12392. document.body.scrollTop = s.scrollTop;
  12393. });
  12394. priorState.clear();
  12395. scrollEvents.on(function (s) {
  12396. s.exclusives.unbind();
  12397. });
  12398. scrollEvents.clear();
  12399. remove$3(platform.container, resolve('fullscreen-maximized'));
  12400. restoreStyles();
  12401. deregister(platform.toolbar);
  12402. remove$2(platform.socket, 'overflow');
  12403. remove$2(platform.socket, '-webkit-overflow-scrolling');
  12404. blur$1(platform.editor.getFrame());
  12405. getActiveApi(platform.editor).each(function (editorApi) {
  12406. editorApi.clearSelection();
  12407. });
  12408. };
  12409. var refreshStructure = function () {
  12410. iosApi.run(function (api) {
  12411. api.refreshStructure();
  12412. });
  12413. };
  12414. return {
  12415. enter: enter,
  12416. refreshStructure: refreshStructure,
  12417. exit: exit
  12418. };
  12419. };
  12420. var produce = function (raw) {
  12421. var mobile = asRawOrDie$1('Getting IosWebapp schema', MobileSchema, raw);
  12422. set$5(mobile.toolstrip, 'width', '100%');
  12423. set$5(mobile.container, 'position', 'relative');
  12424. var onView = function () {
  12425. mobile.setReadOnly(mobile.readOnlyOnInit());
  12426. mode.enter();
  12427. };
  12428. var mask = build$1(sketch(onView, mobile.translate));
  12429. mobile.alloy.add(mask);
  12430. var maskApi = {
  12431. show: function () {
  12432. mobile.alloy.add(mask);
  12433. },
  12434. hide: function () {
  12435. mobile.alloy.remove(mask);
  12436. }
  12437. };
  12438. var mode = create(mobile, maskApi);
  12439. return {
  12440. setReadOnly: mobile.setReadOnly,
  12441. refreshStructure: mode.refreshStructure,
  12442. enter: mode.enter,
  12443. exit: mode.exit,
  12444. destroy: noop
  12445. };
  12446. };
  12447. function IosRealm (scrollIntoView) {
  12448. var alloy = OuterContainer({ classes: [resolve('ios-container')] });
  12449. var toolbar = ScrollingToolbar();
  12450. var webapp = api$2();
  12451. var switchToEdit = makeEditSwitch(webapp);
  12452. var socket = makeSocket();
  12453. var dropup = build(function () {
  12454. webapp.run(function (w) {
  12455. w.refreshStructure();
  12456. });
  12457. }, scrollIntoView);
  12458. alloy.add(toolbar.wrapper);
  12459. alloy.add(socket);
  12460. alloy.add(dropup.component);
  12461. var setToolbarGroups = function (rawGroups) {
  12462. var groups = toolbar.createGroups(rawGroups);
  12463. toolbar.setGroups(groups);
  12464. };
  12465. var setContextToolbar = function (rawGroups) {
  12466. var groups = toolbar.createGroups(rawGroups);
  12467. toolbar.setContextToolbar(groups);
  12468. };
  12469. var focusToolbar = function () {
  12470. toolbar.focus();
  12471. };
  12472. var restoreToolbar = function () {
  12473. toolbar.restoreToolbar();
  12474. };
  12475. var init = function (spec) {
  12476. webapp.set(produce(spec));
  12477. };
  12478. var exit = function () {
  12479. webapp.run(function (w) {
  12480. Replacing.remove(socket, switchToEdit);
  12481. w.exit();
  12482. });
  12483. };
  12484. var updateMode$1 = function (readOnly) {
  12485. updateMode(socket, switchToEdit, readOnly, alloy.root);
  12486. };
  12487. return {
  12488. system: alloy,
  12489. element: alloy.element,
  12490. init: init,
  12491. exit: exit,
  12492. setToolbarGroups: setToolbarGroups,
  12493. setContextToolbar: setContextToolbar,
  12494. focusToolbar: focusToolbar,
  12495. restoreToolbar: restoreToolbar,
  12496. updateMode: updateMode$1,
  12497. socket: socket,
  12498. dropup: dropup
  12499. };
  12500. }
  12501. var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12502. var derive = function (editor) {
  12503. var base = Optional.from(getSkinUrl(editor)).getOrThunk(function () {
  12504. return global$1.baseURL + '/skins/ui/oxide';
  12505. });
  12506. return {
  12507. content: base + '/content.mobile.min.css',
  12508. ui: base + '/skin.mobile.min.css'
  12509. };
  12510. };
  12511. var fireChange = function (realm, command, state) {
  12512. realm.system.broadcastOn([formatChanged], {
  12513. command: command,
  12514. state: state
  12515. });
  12516. };
  12517. var init = function (realm, editor) {
  12518. var allFormats = keys(editor.formatter.get());
  12519. each$1(allFormats, function (command) {
  12520. editor.formatter.formatChanged(command, function (state) {
  12521. fireChange(realm, command, state);
  12522. });
  12523. });
  12524. each$1([
  12525. 'ul',
  12526. 'ol'
  12527. ], function (command) {
  12528. editor.selection.selectorChanged(command, function (state, _data) {
  12529. fireChange(realm, command, state);
  12530. });
  12531. });
  12532. };
  12533. var fireSkinLoaded = function (editor) {
  12534. return function () {
  12535. var done = function () {
  12536. editor._skinLoaded = true;
  12537. editor.fire('SkinLoaded');
  12538. };
  12539. if (editor.initialized) {
  12540. done();
  12541. } else {
  12542. editor.on('init', done);
  12543. }
  12544. };
  12545. };
  12546. var READING = 'toReading';
  12547. var EDITING = 'toEditing';
  12548. var renderMobileTheme = function (editor) {
  12549. var renderUI = function () {
  12550. var targetNode = editor.getElement();
  12551. var cssUrls = derive(editor);
  12552. if (isSkinDisabled(editor) === false) {
  12553. var styleSheetLoader_1 = global$5.DOM.styleSheetLoader;
  12554. editor.contentCSS.push(cssUrls.content);
  12555. styleSheetLoader_1.load(cssUrls.ui, fireSkinLoaded(editor));
  12556. editor.on('remove', function () {
  12557. return styleSheetLoader_1.unload(cssUrls.ui);
  12558. });
  12559. } else {
  12560. fireSkinLoaded(editor)();
  12561. }
  12562. var doScrollIntoView = function () {
  12563. editor.fire('ScrollIntoView');
  12564. };
  12565. var realm = detect$1().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  12566. var original = SugarElement.fromDom(targetNode);
  12567. attachSystemAfter(original, realm.system);
  12568. var findFocusIn = function (elem) {
  12569. return search(elem).bind(function (focused) {
  12570. return realm.system.getByDom(focused).toOptional();
  12571. });
  12572. };
  12573. var outerWindow = targetNode.ownerDocument.defaultView;
  12574. var orientation = onChange(outerWindow, {
  12575. onChange: function () {
  12576. var alloy = realm.system;
  12577. alloy.broadcastOn([orientationChanged], { width: getActualWidth(outerWindow) });
  12578. },
  12579. onReady: noop
  12580. });
  12581. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  12582. if (ro === false) {
  12583. editor.selection.collapse();
  12584. }
  12585. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  12586. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  12587. editor.setMode(ro === true ? 'readonly' : 'design');
  12588. editor.fire(ro === true ? READING : EDITING);
  12589. realm.updateMode(ro);
  12590. };
  12591. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  12592. var dynamic = dynamicGroup.get();
  12593. var toolbars = {
  12594. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  12595. main: dynamic.backToMask.concat(mainGroups.get())
  12596. };
  12597. return toolbars;
  12598. };
  12599. var bindHandler = function (label, handler) {
  12600. editor.on(label, handler);
  12601. return {
  12602. unbind: function () {
  12603. editor.off(label);
  12604. }
  12605. };
  12606. };
  12607. editor.on('init', function () {
  12608. realm.init({
  12609. editor: {
  12610. getFrame: function () {
  12611. return SugarElement.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  12612. },
  12613. onDomChanged: function () {
  12614. return { unbind: noop };
  12615. },
  12616. onToReading: function (handler) {
  12617. return bindHandler(READING, handler);
  12618. },
  12619. onToEditing: function (handler) {
  12620. return bindHandler(EDITING, handler);
  12621. },
  12622. onScrollToCursor: function (handler) {
  12623. editor.on('ScrollIntoView', function (tinyEvent) {
  12624. handler(tinyEvent);
  12625. });
  12626. var unbind = function () {
  12627. editor.off('ScrollIntoView');
  12628. orientation.destroy();
  12629. };
  12630. return { unbind: unbind };
  12631. },
  12632. onTouchToolstrip: function () {
  12633. hideDropup();
  12634. },
  12635. onTouchContent: function () {
  12636. var toolbar = SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar')));
  12637. findFocusIn(toolbar).each(emitExecute);
  12638. realm.restoreToolbar();
  12639. hideDropup();
  12640. },
  12641. onTapContent: function (evt) {
  12642. var target = evt.target;
  12643. if (name$1(target) === 'img') {
  12644. editor.selection.select(target.dom);
  12645. evt.kill();
  12646. } else if (name$1(target) === 'a') {
  12647. var component = realm.system.getByDom(SugarElement.fromDom(editor.editorContainer));
  12648. component.each(function (container) {
  12649. if (Swapping.isAlpha(container)) {
  12650. openLink(target.dom);
  12651. }
  12652. });
  12653. }
  12654. }
  12655. },
  12656. container: SugarElement.fromDom(editor.editorContainer),
  12657. socket: SugarElement.fromDom(editor.contentAreaContainer),
  12658. toolstrip: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolstrip'))),
  12659. toolbar: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))),
  12660. dropup: realm.dropup,
  12661. alloy: realm.system,
  12662. translate: noop,
  12663. setReadOnly: function (ro) {
  12664. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  12665. },
  12666. readOnlyOnInit: function () {
  12667. return readOnlyOnInit();
  12668. }
  12669. });
  12670. var hideDropup = function () {
  12671. realm.dropup.disappear(function () {
  12672. realm.system.broadcastOn([dropupDismissed], {});
  12673. });
  12674. };
  12675. var backToMaskGroup = {
  12676. label: 'The first group',
  12677. scrollable: false,
  12678. items: [forToolbar('back', function () {
  12679. editor.selection.collapse();
  12680. realm.exit();
  12681. }, {}, editor)]
  12682. };
  12683. var backToReadOnlyGroup = {
  12684. label: 'Back to read only',
  12685. scrollable: false,
  12686. items: [forToolbar('readonly-back', function () {
  12687. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  12688. }, {}, editor)]
  12689. };
  12690. var readOnlyGroup = {
  12691. label: 'The read only mode group',
  12692. scrollable: true,
  12693. items: []
  12694. };
  12695. var features = setup$3(realm, editor);
  12696. var items = detect(editor, features);
  12697. var actionGroup = {
  12698. label: 'the action group',
  12699. scrollable: true,
  12700. items: items
  12701. };
  12702. var extraGroup = {
  12703. label: 'The extra group',
  12704. scrollable: false,
  12705. items: []
  12706. };
  12707. var mainGroups = Cell([
  12708. actionGroup,
  12709. extraGroup
  12710. ]);
  12711. var readOnlyGroups = Cell([
  12712. readOnlyGroup,
  12713. extraGroup
  12714. ]);
  12715. var dynamicGroup = Cell({
  12716. backToMask: [backToMaskGroup],
  12717. backToReadOnly: [backToReadOnlyGroup]
  12718. });
  12719. init(realm, editor);
  12720. });
  12721. editor.on('remove', function () {
  12722. realm.exit();
  12723. });
  12724. editor.on('detach', function () {
  12725. detachSystem(realm.system);
  12726. realm.system.destroy();
  12727. });
  12728. return {
  12729. iframeContainer: realm.socket.element.dom,
  12730. editorContainer: realm.element.dom
  12731. };
  12732. };
  12733. return {
  12734. getNotificationManagerImpl: function () {
  12735. return {
  12736. open: constant$1({
  12737. progressBar: { value: noop },
  12738. close: noop,
  12739. text: noop,
  12740. getEl: constant$1(null),
  12741. moveTo: noop,
  12742. moveRel: noop,
  12743. settings: {}
  12744. }),
  12745. close: noop,
  12746. reposition: noop,
  12747. getArgs: constant$1({})
  12748. };
  12749. },
  12750. renderUI: renderUI
  12751. };
  12752. };
  12753. function Theme () {
  12754. global$4.add('mobile', renderMobileTheme);
  12755. }
  12756. Theme();
  12757. }());